From 6f125c7090015ede1556509e7c1ac86fca80b5ab Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 11:32:40 +0200
Subject: [PATCH 001/901] Extract UTF-8 decoding logic
---
.../util/Utf8ByteBufDecoder.java | 67 +--------------
.../org/asynchttpclient/util/Utf8Decoder.java | 82 +++++++++++++++++++
2 files changed, 84 insertions(+), 65 deletions(-)
create mode 100644 client/src/main/java/org/asynchttpclient/util/Utf8Decoder.java
diff --git a/client/src/main/java/org/asynchttpclient/util/Utf8ByteBufDecoder.java b/client/src/main/java/org/asynchttpclient/util/Utf8ByteBufDecoder.java
index 24a36a6062..c5e46b8f8e 100644
--- a/client/src/main/java/org/asynchttpclient/util/Utf8ByteBufDecoder.java
+++ b/client/src/main/java/org/asynchttpclient/util/Utf8ByteBufDecoder.java
@@ -18,83 +18,20 @@
import java.nio.charset.CharacterCodingException;
-public class Utf8ByteBufDecoder {
+public class Utf8ByteBufDecoder extends Utf8Decoder {
private static final FastThreadLocal DECODERS = new FastThreadLocal() {
protected Utf8ByteBufDecoder initialValue() {
return new Utf8ByteBufDecoder();
};
};
-
+
public static Utf8ByteBufDecoder getCachedDecoder() {
Utf8ByteBufDecoder cached = DECODERS.get();
cached.reset();
return cached;
}
- private static final byte[] TYPES = new byte[] {//
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,/**/
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,/**/
- 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/**/
- 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 /**/
- };
-
- private static final byte[] STATES = new byte[] {//
- 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,/**/
- 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 24, 12, 12,/**/
- 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12,/**/
- 12, 12, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12,/**/
- 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 //
- };
-
- private static final int UTF8_ACCEPT = 0;
- private static final int UTF8_REJECT = 12;
-
- private StringBuilder sb = new StringBuilder();
- private int state = UTF8_ACCEPT;
- private int codePoint = 0;
-
- private void write(byte b) throws CharacterCodingException {
- int t = TYPES[b & 0xFF];
-
- codePoint = state != UTF8_ACCEPT ? (b & 0x3f) | (codePoint << 6) : (0xff >> t) & b;
- state = STATES[state + t];
-
- if (state == UTF8_ACCEPT) {
- if (codePoint < Character.MIN_HIGH_SURROGATE) {
- sb.append((char) codePoint);
- } else {
- appendCodePointChars();
- }
- } else if (state == UTF8_REJECT) {
- throw new CharacterCodingException();
- }
- }
-
- private void appendCodePointChars() {
- if (Character.isBmpCodePoint(codePoint)) {
- sb.append((char) codePoint);
-
- } else if (Character.isValidCodePoint(codePoint)) {
- char charIndexPlus1 = Character.lowSurrogate(codePoint);
- char charIndex = Character.highSurrogate(codePoint);
- sb.append(charIndex).append(charIndexPlus1);
-
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- public void reset() {
- sb.setLength(0);
- state = UTF8_ACCEPT;
- codePoint = 0;
- }
-
public String decode(Iterable bufs) throws CharacterCodingException {
for (ByteBuf buf : bufs) {
diff --git a/client/src/main/java/org/asynchttpclient/util/Utf8Decoder.java b/client/src/main/java/org/asynchttpclient/util/Utf8Decoder.java
new file mode 100644
index 0000000000..f98e37acfb
--- /dev/null
+++ b/client/src/main/java/org/asynchttpclient/util/Utf8Decoder.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
+package org.asynchttpclient.util;
+
+import java.nio.charset.CharacterCodingException;
+
+public abstract class Utf8Decoder {
+
+ private static final byte[] TYPES = new byte[] {//
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,/**/
+ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,/**/
+ 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/**/
+ 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 /**/
+ };
+
+ private static final byte[] STATES = new byte[] {//
+ 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,/**/
+ 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 24, 12, 12,/**/
+ 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12,/**/
+ 12, 12, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12,/**/
+ 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 //
+ };
+
+ protected static final int UTF8_ACCEPT = 0;
+ protected static final int UTF8_REJECT = 12;
+
+ protected StringBuilder sb = new StringBuilder();
+ protected int state = UTF8_ACCEPT;
+ private int codePoint = 0;
+
+ protected void write(byte b) throws CharacterCodingException {
+ int t = TYPES[b & 0xFF];
+
+ codePoint = state != UTF8_ACCEPT ? (b & 0x3f) | (codePoint << 6) : (0xff >> t) & b;
+ state = STATES[state + t];
+
+ if (state == UTF8_ACCEPT) {
+ if (codePoint < Character.MIN_HIGH_SURROGATE) {
+ sb.append((char) codePoint);
+ } else {
+ appendCodePointChars();
+ }
+ } else if (state == UTF8_REJECT) {
+ throw new CharacterCodingException();
+ }
+ }
+
+ private void appendCodePointChars() {
+ if (Character.isBmpCodePoint(codePoint)) {
+ sb.append((char) codePoint);
+
+ } else if (Character.isValidCodePoint(codePoint)) {
+ char charIndexPlus1 = Character.lowSurrogate(codePoint);
+ char charIndex = Character.highSurrogate(codePoint);
+ sb.append(charIndex).append(charIndexPlus1);
+
+ } else {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ public void reset() {
+ sb.setLength(0);
+ state = UTF8_ACCEPT;
+ codePoint = 0;
+ }
+}
From 7a6535ab0dba0b489ba250d051eb7fbcfd4142cd Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 11:34:29 +0200
Subject: [PATCH 002/901] [maven-release-plugin] prepare release
async-http-client-project-2.0.13
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
pom.xml | 2 +-
12 files changed, 12 insertions(+), 12 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 10a8742001..321cde5f41 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.13-SNAPSHOT
+ 2.0.134.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 52b7805fde..3a03ff1207 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.13-SNAPSHOT
+ 2.0.134.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 206bfee30d..f157ace8ec 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.13-SNAPSHOT
+ 2.0.13async-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 418c9a267a..dbe0471dbf 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.13-SNAPSHOT
+ 2.0.134.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 2d683923dd..dbf61cff46 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.13-SNAPSHOT
+ 2.0.134.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 32d634ad03..2a0b689047 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.13-SNAPSHOT
+ 2.0.13async-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index ddc94717a4..2007418e34 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.13-SNAPSHOT
+ 2.0.13async-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 0ede7712f2..faa4c54489 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.13-SNAPSHOT
+ 2.0.13netty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 69f21f0eff..48e3ba2377 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.13-SNAPSHOT
+ 2.0.134.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index e7407a205b..ec0b8073cb 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.13-SNAPSHOT
+ 2.0.13netty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 2b0b0ab424..b25642d658 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.13-SNAPSHOT
+ 2.0.13netty-resolver
diff --git a/pom.xml b/pom.xml
index b6ff545cc3..8cbc272cbe 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.13-SNAPSHOT
+ 2.0.13pom
The Async Http Client (AHC) library's purpose is to allow Java
From 2cb1d8a38a3d243ad20d021be6e06b45cd65bf02 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 11:34:34 +0200
Subject: [PATCH 003/901] [maven-release-plugin] prepare for next development
iteration
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
pom.xml | 2 +-
12 files changed, 12 insertions(+), 12 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 321cde5f41..f7914139bb 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.13
+ 2.0.14-SNAPSHOT4.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 3a03ff1207..c86d744a2b 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.13
+ 2.0.14-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index f157ace8ec..9d86877a7b 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.13
+ 2.0.14-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index dbe0471dbf..07b56e4fd6 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.13
+ 2.0.14-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index dbf61cff46..cdb2344e90 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.13
+ 2.0.14-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 2a0b689047..3f2dc43833 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.13
+ 2.0.14-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 2007418e34..8f59431f64 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.13
+ 2.0.14-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index faa4c54489..91fee57ca3 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.13
+ 2.0.14-SNAPSHOTnetty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 48e3ba2377..1a8ab4b8b9 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.13
+ 2.0.14-SNAPSHOT4.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index ec0b8073cb..9550ebd1d1 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.13
+ 2.0.14-SNAPSHOTnetty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index b25642d658..ec13d57c4b 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.13
+ 2.0.14-SNAPSHOTnetty-resolver
diff --git a/pom.xml b/pom.xml
index 8cbc272cbe..154eea0ed3 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.13
+ 2.0.14-SNAPSHOTpom
The Async Http Client (AHC) library's purpose is to allow Java
From b3075c89fa1240a5691a239acccacc5e6d56dc00 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 16:07:09 +0200
Subject: [PATCH 004/901] Extract Netty utils into dedicated module, close
#1237
---
client/pom.xml | 5 +
.../netty/EagerResponseBodyPart.java | 2 +-
.../netty/LazyResponseBodyPart.java | 2 +-
.../netty/ws/NettyWebSocket.java | 4 +-
.../org/asynchttpclient/ntlm/NtlmTest.java | 103 +++++++++++-------
netty-utils/pom.xml | 17 +++
.../netty}/util/ByteBufUtils.java | 6 +-
.../netty}/util/UsAsciiByteBufDecoder.java | 12 +-
.../netty}/util/Utf8ByteBufDecoder.java | 12 +-
.../netty}/util/Utf8Decoder.java | 2 +-
.../netty/util/ByteBufUtilsTest.java | 1 -
pom.xml | 6 +
12 files changed, 113 insertions(+), 59 deletions(-)
create mode 100644 netty-utils/pom.xml
rename {client/src/main/java/org/asynchttpclient => netty-utils/src/main/java/org/asynchttpclient/netty}/util/ByteBufUtils.java (90%)
rename {client/src/main/java/org/asynchttpclient => netty-utils/src/main/java/org/asynchttpclient/netty}/util/UsAsciiByteBufDecoder.java (84%)
rename {client/src/main/java/org/asynchttpclient => netty-utils/src/main/java/org/asynchttpclient/netty}/util/Utf8ByteBufDecoder.java (82%)
rename {client/src/main/java/org/asynchttpclient => netty-utils/src/main/java/org/asynchttpclient/netty}/util/Utf8Decoder.java (98%)
rename {client => netty-utils}/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java (95%)
diff --git a/client/pom.xml b/client/pom.xml
index f7914139bb..f454dcc3c8 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -25,6 +25,11 @@
+
+ org.asynchttpclient
+ async-http-client-netty-utils
+ ${project.version}
+ io.nettynetty-codec-http
diff --git a/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java b/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java
index f8020d260f..49450e12f1 100755
--- a/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java
+++ b/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java
@@ -12,7 +12,7 @@
*/
package org.asynchttpclient.netty;
-import static org.asynchttpclient.util.ByteBufUtils.byteBuf2Bytes;
+import static org.asynchttpclient.netty.util.ByteBufUtils.byteBuf2Bytes;
import io.netty.buffer.ByteBuf;
import java.nio.ByteBuffer;
diff --git a/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java b/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java
index 02159fb85e..61a1aea83b 100755
--- a/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java
+++ b/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java
@@ -17,7 +17,7 @@
import java.nio.ByteBuffer;
import org.asynchttpclient.HttpResponseBodyPart;
-import org.asynchttpclient.util.ByteBufUtils;
+import org.asynchttpclient.netty.util.ByteBufUtils;
/**
* A callback class used when an HTTP response body is received.
diff --git a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
index be7837fc05..b292e45868 100755
--- a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
+++ b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
@@ -14,7 +14,7 @@
package org.asynchttpclient.netty.ws;
import static io.netty.buffer.Unpooled.wrappedBuffer;
-import static org.asynchttpclient.util.ByteBufUtils.byteBuf2Bytes;
+import static org.asynchttpclient.netty.util.ByteBufUtils.byteBuf2Bytes;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
@@ -28,7 +28,7 @@
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
-import org.asynchttpclient.util.ByteBufUtils;
+import org.asynchttpclient.netty.util.ByteBufUtils;
import org.asynchttpclient.ws.WebSocket;
import org.asynchttpclient.ws.WebSocketByteListener;
import org.asynchttpclient.ws.WebSocketCloseCodeReasonListener;
diff --git a/client/src/test/java/org/asynchttpclient/ntlm/NtlmTest.java b/client/src/test/java/org/asynchttpclient/ntlm/NtlmTest.java
index 955e94f745..5f922175cc 100644
--- a/client/src/test/java/org/asynchttpclient/ntlm/NtlmTest.java
+++ b/client/src/test/java/org/asynchttpclient/ntlm/NtlmTest.java
@@ -15,10 +15,9 @@
import static org.asynchttpclient.Dsl.*;
import static org.testng.Assert.*;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
import java.io.IOException;
+import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@@ -27,13 +26,13 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.io.output.ByteArrayOutputStream;
import org.asynchttpclient.AbstractBasicTest;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Realm;
import org.asynchttpclient.Response;
import org.asynchttpclient.ntlm.NtlmEngine.Type2Message;
import org.asynchttpclient.util.Base64;
-import org.asynchttpclient.util.ByteBufUtils;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.testng.Assert;
import org.testng.annotations.Test;
@@ -97,7 +96,7 @@ public void lazyNTLMAuthTest() throws IOException, InterruptedException, Executi
public void preemptiveNTLMAuthTest() throws IOException, InterruptedException, ExecutionException {
ntlmAuthTest(realmBuilderBase().setUsePreemptiveAuth(true));
}
-
+
@Test
public void testGenerateType1Msg() {
NtlmEngine engine = new NtlmEngine();
@@ -119,73 +118,101 @@ public void testGenerateType3MsgThrowsExceptionWhenChallengeDoesNotFollowCorrect
fail("An NtlmEngineException must have occurred as challenge format is not correct");
}
+ private static byte[] longToBytes(long x) {
+ ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
+ buffer.putLong(x);
+ return buffer.array();
+ }
+
@Test(expectedExceptions = NtlmEngineException.class)
- public void testGenerateType3MsgThworsExceptionWhenType2IndicatorNotPresent() {
- ByteBuf buf = Unpooled.directBuffer();
- buf.writeBytes("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
- buf.writeByte(0);
+ public void testGenerateType3MsgThworsExceptionWhenType2IndicatorNotPresent() throws IOException {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
+ buf.write(0);
// type 2 indicator
- buf.writeByte(3).writeByte(0).writeByte(0).writeByte(0);
- buf.writeBytes("challenge".getBytes());
+ buf.write(3);
+ buf.write(0);
+ buf.write(0);
+ buf.write(0);
+ buf.write("challenge".getBytes());
NtlmEngine engine = new NtlmEngine();
- engine.generateType3Msg("username", "password", "localhost", "workstation", Base64.encode(ByteBufUtils.byteBuf2Bytes(buf)));
+ engine.generateType3Msg("username", "password", "localhost", "workstation", Base64.encode(buf.toByteArray()));
+ buf.close();
fail("An NtlmEngineException must have occurred as type 2 indicator is incorrect");
}
@Test(expectedExceptions = NtlmEngineException.class)
- public void testGenerateType3MsgThrowsExceptionWhenUnicodeSupportNotIndicated() {
- ByteBuf buf = Unpooled.directBuffer();
- buf.writeBytes("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
- buf.writeByte(0);
+ public void testGenerateType3MsgThrowsExceptionWhenUnicodeSupportNotIndicated() throws IOException {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
+ buf.write(0);
// type 2 indicator
- buf.writeByte(2).writeByte(0).writeByte(0).writeByte(0);
- buf.writeLong(1);
+ buf.write(2);
+ buf.write(0);
+ buf.write(0);
+ buf.write(0);
+
+ buf.write(longToBytes(1L)); // we want to write a Long
+
// flags
- buf.writeByte(0);// unicode support indicator
- buf.writeByte(0).writeByte(0).writeByte(0);
- buf.writeLong(1);// challenge
+ buf.write(0);// unicode support indicator
+ buf.write(0);
+ buf.write(0);
+ buf.write(0);
+
+ buf.write(longToBytes(1L));// challenge
NtlmEngine engine = new NtlmEngine();
- engine.generateType3Msg("username", "password", "localhost", "workstation", Base64.encode(ByteBufUtils.byteBuf2Bytes(buf)));
+ engine.generateType3Msg("username", "password", "localhost", "workstation", Base64.encode(buf.toByteArray()));
+ buf.close();
fail("An NtlmEngineException must have occurred as unicode support is not indicated");
}
- @Test(groups="standalone")
- public void testGenerateType2Msg(){
+ @Test(groups = "standalone")
+ public void testGenerateType2Msg() {
Type2Message type2Message = new Type2Message("TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==");
Assert.assertEquals(type2Message.getMessageLength(), 40, "This is a sample challenge that should return 40");
}
@Test
- public void testGenerateType3Msg() {
- ByteBuf buf = Unpooled.directBuffer();
- buf.writeBytes("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
- buf.writeByte(0);
+ public void testGenerateType3Msg() throws IOException {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
+ buf.write(0);
// type 2 indicator
- buf.writeByte(2).writeByte(0).writeByte(0).writeByte(0);
- buf.writeLong(0);
+ buf.write(2);
+ buf.write(0);
+ buf.write(0);
+ buf.write(0);
+
+ buf.write(longToBytes(0L)); // we want to write a Long
+
// flags
- buf.writeByte(1);// unicode support indicator
- buf.writeByte(0).writeByte(0).writeByte(0);
- buf.writeLong(1);// challenge
+ buf.write(1);// unicode support indicator
+ buf.write(0);
+ buf.write(0);
+ buf.write(0);
+
+ buf.write(longToBytes(1L));// challenge
NtlmEngine engine = new NtlmEngine();
- String type3Msg = engine.generateType3Msg("username", "password", "localhost", "workstation",
- Base64.encode(ByteBufUtils.byteBuf2Bytes(buf)));
- assertEquals(type3Msg,
+ String type3Msg = engine.generateType3Msg("username", "password", "localhost", "workstation", Base64.encode(buf.toByteArray()));
+ buf.close();
+ assertEquals(
+ type3Msg,
"TlRMTVNTUAADAAAAGAAYAEgAAAAYABgAYAAAABIAEgB4AAAAEAAQAIoAAAAWABYAmgAAAAAAAACwAAAAAQAAAgUBKAoAAAAP1g6lqqN1HZ0wSSxeQ5riQkyh7/UexwVlCPQm0SHU2vsDQm2wM6NbT2zPonPzLJL0TABPAEMAQQBMAEgATwBTAFQAdQBzAGUAcgBuAGEAbQBlAFcATwBSAEsAUwBUAEEAVABJAE8ATgA=",
"Incorrect type3 message generated");
}
@Test
public void testWriteULong() {
- //test different combinations so that different positions in the byte array will be written
+ // test different combinations so that different positions in the byte array will be written
byte[] buffer = new byte[4];
NtlmEngine.writeULong(buffer, 1, 0);
assertEquals(buffer, new byte[] { 1, 0, 0, 0 }, "Unsigned long value 1 was not written correctly to the buffer");
-
+
buffer = new byte[4];
NtlmEngine.writeULong(buffer, 257, 0);
assertEquals(buffer, new byte[] { 1, 1, 0, 0 }, "Unsigned long value 257 was not written correctly to the buffer");
-
+
buffer = new byte[4];
NtlmEngine.writeULong(buffer, 16777216, 0);
assertEquals(buffer, new byte[] { 0, 0, 0, 1 }, "Unsigned long value 16777216 was not written correctly to the buffer");
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
new file mode 100644
index 0000000000..de78616ea8
--- /dev/null
+++ b/netty-utils/pom.xml
@@ -0,0 +1,17 @@
+
+
+ org.asynchttpclient
+ async-http-client-project
+ 2.0.14-SNAPSHOT
+
+ 4.0.0
+ async-http-client-netty-utils
+ Asynchronous Http Client Netty Utils
+
+
+
+ io.netty
+ netty-buffer
+
+
+
diff --git a/client/src/main/java/org/asynchttpclient/util/ByteBufUtils.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
similarity index 90%
rename from client/src/main/java/org/asynchttpclient/util/ByteBufUtils.java
rename to netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
index 6f6efbd79c..2bf7a65e2c 100755
--- a/client/src/main/java/org/asynchttpclient/util/ByteBufUtils.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
@@ -11,7 +11,7 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-package org.asynchttpclient.util;
+package org.asynchttpclient.netty.util;
import io.netty.buffer.ByteBuf;
@@ -27,11 +27,11 @@ private ByteBufUtils() {
}
public static String byteBuf2Utf8String(ByteBuf buf) throws CharacterCodingException {
- return Utf8ByteBufDecoder.getCachedDecoder().decode(Collections.singleton(buf));
+ return Utf8ByteBufDecoder.pooled().decode(Collections.singleton(buf));
}
public static String byteBuf2UsAsciiString(ByteBuf buf) throws CharacterCodingException {
- return UsAsciiByteBufDecoder.getCachedDecoder().decode(Collections.singleton(buf));
+ return UsAsciiByteBufDecoder.pooled().decode(Collections.singleton(buf));
}
public static String byteBuf2String(ByteBuf buf, Charset charset) throws UTFDataFormatException, IndexOutOfBoundsException, CharacterCodingException {
diff --git a/client/src/main/java/org/asynchttpclient/util/UsAsciiByteBufDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
similarity index 84%
rename from client/src/main/java/org/asynchttpclient/util/UsAsciiByteBufDecoder.java
rename to netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
index 45039a1a3c..0dbd9faf38 100644
--- a/client/src/main/java/org/asynchttpclient/util/UsAsciiByteBufDecoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
@@ -11,23 +11,23 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-package org.asynchttpclient.util;
+package org.asynchttpclient.netty.util;
import io.netty.buffer.ByteBuf;
import io.netty.util.concurrent.FastThreadLocal;
public class UsAsciiByteBufDecoder {
- private static final FastThreadLocal DECODERS = new FastThreadLocal() {
+ private static final FastThreadLocal POOL = new FastThreadLocal() {
protected UsAsciiByteBufDecoder initialValue() {
return new UsAsciiByteBufDecoder();
};
};
- public static UsAsciiByteBufDecoder getCachedDecoder() {
- UsAsciiByteBufDecoder cached = DECODERS.get();
- cached.reset();
- return cached;
+ public static UsAsciiByteBufDecoder pooled() {
+ UsAsciiByteBufDecoder decoder = POOL.get();
+ decoder.reset();
+ return decoder;
}
private StringBuilder sb = new StringBuilder();
diff --git a/client/src/main/java/org/asynchttpclient/util/Utf8ByteBufDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
similarity index 82%
rename from client/src/main/java/org/asynchttpclient/util/Utf8ByteBufDecoder.java
rename to netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
index c5e46b8f8e..fddcdcdd4c 100644
--- a/client/src/main/java/org/asynchttpclient/util/Utf8ByteBufDecoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
@@ -11,7 +11,7 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-package org.asynchttpclient.util;
+package org.asynchttpclient.netty.util;
import io.netty.buffer.ByteBuf;
import io.netty.util.concurrent.FastThreadLocal;
@@ -20,16 +20,16 @@
public class Utf8ByteBufDecoder extends Utf8Decoder {
- private static final FastThreadLocal DECODERS = new FastThreadLocal() {
+ private static final FastThreadLocal POOL = new FastThreadLocal() {
protected Utf8ByteBufDecoder initialValue() {
return new Utf8ByteBufDecoder();
};
};
- public static Utf8ByteBufDecoder getCachedDecoder() {
- Utf8ByteBufDecoder cached = DECODERS.get();
- cached.reset();
- return cached;
+ public static Utf8ByteBufDecoder pooled() {
+ Utf8ByteBufDecoder decoder = POOL.get();
+ decoder.reset();
+ return decoder;
}
public String decode(Iterable bufs) throws CharacterCodingException {
diff --git a/client/src/main/java/org/asynchttpclient/util/Utf8Decoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
similarity index 98%
rename from client/src/main/java/org/asynchttpclient/util/Utf8Decoder.java
rename to netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
index f98e37acfb..db6aeabefa 100644
--- a/client/src/main/java/org/asynchttpclient/util/Utf8Decoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
@@ -11,7 +11,7 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-package org.asynchttpclient.util;
+package org.asynchttpclient.netty.util;
import java.nio.charset.CharacterCodingException;
diff --git a/client/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java b/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
similarity index 95%
rename from client/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
rename to netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
index 2b3a2f4b0f..fd80a58f6e 100644
--- a/client/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
+++ b/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
@@ -4,7 +4,6 @@
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
-import org.asynchttpclient.util.ByteBufUtils;
import org.testng.annotations.Test;
public class ByteBufUtilsTest {
diff --git a/pom.xml b/pom.xml
index 154eea0ed3..ca8ddf4d39 100644
--- a/pom.xml
+++ b/pom.xml
@@ -213,11 +213,17 @@
netty-bp
+ netty-utilsclientextras
+
+ io.netty
+ netty-buffer
+ ${netty.version}
+ io.nettynetty-codec-http
From af9a72b96460c31e7bf76753ab6ba7d7368a6cb8 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 16:07:22 +0200
Subject: [PATCH 005/901] Remove dead code
---
.../util/StringCharSequence.java | 54 --------------
.../asynchttpclient/util/Utf8UrlDecoder.java | 70 -------------------
2 files changed, 124 deletions(-)
delete mode 100644 client/src/main/java/org/asynchttpclient/util/StringCharSequence.java
delete mode 100644 client/src/main/java/org/asynchttpclient/util/Utf8UrlDecoder.java
diff --git a/client/src/main/java/org/asynchttpclient/util/StringCharSequence.java b/client/src/main/java/org/asynchttpclient/util/StringCharSequence.java
deleted file mode 100644
index a1cf2192f2..0000000000
--- a/client/src/main/java/org/asynchttpclient/util/StringCharSequence.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.util;
-
-/**
- * A CharSequence String wrapper that doesn't copy the char[] (damn new String implementation!!!)
- *
- * @author slandelle
- */
-public class StringCharSequence implements CharSequence {
-
- private final String value;
- private final int offset;
- public final int length;
-
- public StringCharSequence(String value, int offset, int length) {
- this.value = value;
- this.offset = offset;
- this.length = length;
- }
-
- @Override
- public int length() {
- return length;
- }
-
- @Override
- public char charAt(int index) {
- return value.charAt(offset + index);
- }
-
- @Override
- public CharSequence subSequence(int start, int end) {
- int offsetedEnd = offset + end;
- if (offsetedEnd < length)
- throw new ArrayIndexOutOfBoundsException();
- return new StringCharSequence(value, offset + start, end - start);
- }
-
- @Override
- public String toString() {
- return value.substring(offset, length);
- }
-}
diff --git a/client/src/main/java/org/asynchttpclient/util/Utf8UrlDecoder.java b/client/src/main/java/org/asynchttpclient/util/Utf8UrlDecoder.java
deleted file mode 100644
index 6a4c04cfce..0000000000
--- a/client/src/main/java/org/asynchttpclient/util/Utf8UrlDecoder.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.util;
-
-public final class Utf8UrlDecoder {
-
- private Utf8UrlDecoder() {
- }
-
- private static StringBuilder initSb(StringBuilder sb, String s, int i, int offset, int length) {
- if (sb != null) {
- return sb;
- } else {
- int initialSbLength = length > 500 ? length / 2 : length;
- return new StringBuilder(initialSbLength).append(s, offset, i);
- }
- }
-
- private static int hexaDigit(char c) {
- return Character.digit(c, 16);
- }
-
- public static CharSequence decode(String s) {
- return decode(s, 0, s.length());
- }
-
- public static CharSequence decode(final String s, final int offset, final int length) {
-
- StringBuilder sb = null;
- int i = offset;
- int end = length + offset;
-
- while (i < end) {
- char c = s.charAt(i);
- if (c == '+') {
- sb = initSb(sb, s, i, offset, length);
- sb.append(' ');
- i++;
-
- } else if (c == '%') {
- if (end - i < 3) // We expect 3 chars. 0 based i vs. 1 based length!
- throw new IllegalArgumentException("UTF8UrlDecoder: Incomplete trailing escape (%) pattern");
-
- int x, y;
- if ((x = hexaDigit(s.charAt(i + 1))) == -1 || (y = hexaDigit(s.charAt(i + 2))) == -1)
- throw new IllegalArgumentException("UTF8UrlDecoder: Malformed");
-
- sb = initSb(sb, s, i, offset, length);
- sb.append((char) (x * 16 + y));
- i += 3;
- } else {
- if (sb != null)
- sb.append(c);
- i++;
- }
- }
-
- return sb != null ? sb.toString() : new StringCharSequence(s, offset, length);
- }
-}
From fff0ab8b3e4d858165075f77becb0187c61b9d61 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 16:07:31 +0200
Subject: [PATCH 006/901] Minor clean up
---
.../src/main/java/org/asynchttpclient/util/StringUtils.java | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/client/src/main/java/org/asynchttpclient/util/StringUtils.java b/client/src/main/java/org/asynchttpclient/util/StringUtils.java
index b48e2cce2d..f125b2906d 100644
--- a/client/src/main/java/org/asynchttpclient/util/StringUtils.java
+++ b/client/src/main/java/org/asynchttpclient/util/StringUtils.java
@@ -18,7 +18,7 @@
public final class StringUtils {
- private static final ThreadLocal STRING_BUILDERS = new ThreadLocal() {
+ private static final ThreadLocal STRING_BUILDER_POOL = new ThreadLocal() {
protected StringBuilder initialValue() {
return new StringBuilder(512);
}
@@ -29,13 +29,12 @@ protected StringBuilder initialValue() {
* @return a pooled StringBuilder
*/
public static StringBuilder stringBuilder() {
- StringBuilder sb = STRING_BUILDERS.get();
+ StringBuilder sb = STRING_BUILDER_POOL.get();
sb.setLength(0);
return sb;
}
private StringUtils() {
- // unused
}
public static ByteBuffer charSequence2ByteBuffer(CharSequence cs, Charset charset) {
From 0058f267c6496c212d34771d05459047b6ec3e76 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 16:27:20 +0200
Subject: [PATCH 007/901] [maven-release-plugin] prepare release
async-http-client-project-2.0.14
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
13 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index f454dcc3c8..8ad0384a06 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14-SNAPSHOT
+ 2.0.144.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index c86d744a2b..a32ca42f08 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.14-SNAPSHOT
+ 2.0.144.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 9d86877a7b..b94c20c789 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.14-SNAPSHOT
+ 2.0.14async-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 07b56e4fd6..e4a92eaf62 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14-SNAPSHOT
+ 2.0.144.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index cdb2344e90..9f979840f2 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.14-SNAPSHOT
+ 2.0.144.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 3f2dc43833..89d2dadeb8 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.14-SNAPSHOT
+ 2.0.14async-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 8f59431f64..e03baca31c 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.14-SNAPSHOT
+ 2.0.14async-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 91fee57ca3..65e908c2c4 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.14-SNAPSHOT
+ 2.0.14netty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 1a8ab4b8b9..8c656e52b6 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14-SNAPSHOT
+ 2.0.144.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index 9550ebd1d1..e425947d53 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.14-SNAPSHOT
+ 2.0.14netty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index ec13d57c4b..2e03857719 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.14-SNAPSHOT
+ 2.0.14netty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index de78616ea8..ba3a514553 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14-SNAPSHOT
+ 2.0.144.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index ca8ddf4d39..806e8ed1f0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.14-SNAPSHOT
+ 2.0.14pom
The Async Http Client (AHC) library's purpose is to allow Java
From 61cd375b0881671f2ce271b916b9bbaa5909938e Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 16:27:26 +0200
Subject: [PATCH 008/901] [maven-release-plugin] prepare for next development
iteration
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
13 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 8ad0384a06..fffce6e875 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14
+ 2.0.15-SNAPSHOT4.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index a32ca42f08..a71a8362b4 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.14
+ 2.0.15-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index b94c20c789..8de1fcfcad 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.14
+ 2.0.15-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index e4a92eaf62..417e554bb4 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14
+ 2.0.15-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 9f979840f2..5f4bbb2dd5 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.14
+ 2.0.15-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 89d2dadeb8..c39037e117 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.14
+ 2.0.15-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index e03baca31c..05d4f93c3c 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.14
+ 2.0.15-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 65e908c2c4..c7a21ff88a 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.14
+ 2.0.15-SNAPSHOTnetty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 8c656e52b6..bbe5182a05 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14
+ 2.0.15-SNAPSHOT4.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index e425947d53..749bf0c075 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.14
+ 2.0.15-SNAPSHOTnetty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 2e03857719..c9039801b7 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.14
+ 2.0.15-SNAPSHOTnetty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index ba3a514553..a70646b204 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.14
+ 2.0.15-SNAPSHOT4.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index 806e8ed1f0..b5ab4f4e91 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.14
+ 2.0.15-SNAPSHOTpom
The Async Http Client (AHC) library's purpose is to allow Java
From 0757d83d3efce4a77b29fd34aa91347efe901123 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 26 Aug 2016 16:36:13 +0200
Subject: [PATCH 009/901] Minor clean up
---
.../DefaultAsyncHttpClientConfig.java | 5 ++--
.../proxy/ProxyServerSelector.java | 7 +-----
.../org/asynchttpclient/util/ProxyUtils.java | 25 +++++--------------
3 files changed, 9 insertions(+), 28 deletions(-)
diff --git a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java
index 51ca60511f..a888ed96ca 100644
--- a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java
+++ b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java
@@ -800,13 +800,12 @@ public Builder setValidateResponseHeaders(boolean validateResponseHeaders) {
}
public Builder setProxyServer(ProxyServer proxyServer) {
- this.proxyServerSelector = ProxyUtils.createProxyServerSelector(proxyServer);
+ this.proxyServerSelector = uri -> proxyServer;
return this;
}
public Builder setProxyServer(ProxyServer.Builder proxyServerBuilder) {
- this.proxyServerSelector = ProxyUtils.createProxyServerSelector(proxyServerBuilder.build());
- return this;
+ return setProxyServer(proxyServerBuilder.build());
}
public Builder setUseProxySelector(boolean useProxySelector) {
diff --git a/client/src/main/java/org/asynchttpclient/proxy/ProxyServerSelector.java b/client/src/main/java/org/asynchttpclient/proxy/ProxyServerSelector.java
index dc93a979ce..359878b485 100644
--- a/client/src/main/java/org/asynchttpclient/proxy/ProxyServerSelector.java
+++ b/client/src/main/java/org/asynchttpclient/proxy/ProxyServerSelector.java
@@ -18,10 +18,5 @@ public interface ProxyServerSelector {
/**
* A selector that always selects no proxy.
*/
- ProxyServerSelector NO_PROXY_SELECTOR = new ProxyServerSelector() {
- @Override
- public ProxyServer select(Uri uri) {
- return null;
- }
- };
+ ProxyServerSelector NO_PROXY_SELECTOR = uri -> null;
}
diff --git a/client/src/main/java/org/asynchttpclient/util/ProxyUtils.java b/client/src/main/java/org/asynchttpclient/util/ProxyUtils.java
index be57a4f9f9..569c8e649b 100644
--- a/client/src/main/java/org/asynchttpclient/util/ProxyUtils.java
+++ b/client/src/main/java/org/asynchttpclient/util/ProxyUtils.java
@@ -40,7 +40,7 @@
*/
public final class ProxyUtils {
- private final static Logger log = LoggerFactory.getLogger(ProxyUtils.class);
+ private final static Logger logger = LoggerFactory.getLogger(ProxyUtils.class);
/**
* The host to use as proxy.
@@ -123,7 +123,8 @@ public static ProxyServerSelector createProxyServerSelector(Properties propertie
proxyServer.setNonProxyHosts(new ArrayList<>(Arrays.asList(nonProxyHosts.split("\\|"))));
}
- return createProxyServerSelector(proxyServer.build());
+ ProxyServer proxy = proxyServer.build();
+ return uri -> proxy;
}
return ProxyServerSelector.NO_PROXY_SELECTOR;
@@ -157,7 +158,7 @@ public ProxyServer select(Uri uri) {
switch (proxy.type()) {
case HTTP:
if (!(proxy.address() instanceof InetSocketAddress)) {
- log.warn("Don't know how to connect to address " + proxy.address());
+ logger.warn("Don't know how to connect to address " + proxy.address());
return null;
} else {
InetSocketAddress address = (InetSocketAddress) proxy.address();
@@ -166,31 +167,17 @@ public ProxyServer select(Uri uri) {
case DIRECT:
return null;
default:
- log.warn("ProxySelector returned proxy type that we don't know how to use: " + proxy.type());
+ logger.warn("ProxySelector returned proxy type that we don't know how to use: " + proxy.type());
break;
}
}
}
return null;
} catch (URISyntaxException e) {
- log.warn(uri + " couldn't be turned into a java.net.URI", e);
+ logger.warn(uri + " couldn't be turned into a java.net.URI", e);
return null;
}
}
};
}
-
- /**
- * Create a proxy server selector that always selects a single proxy server.
- *
- * @param proxyServer The proxy server to select.
- * @return The proxy server selector.
- */
- public static ProxyServerSelector createProxyServerSelector(final ProxyServer proxyServer) {
- return new ProxyServerSelector() {
- public ProxyServer select(Uri uri) {
- return proxyServer;
- }
- };
- }
}
From e98f6fd1fde25c30e677513fd1beb7c07b6a89e3 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 29 Aug 2016 22:04:03 +0200
Subject: [PATCH 010/901] Upgrade Netty 4.0.41
---
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pom.xml b/pom.xml
index b5ab4f4e91..a4fc7760b5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -379,7 +379,7 @@
true1.81.8
- 4.0.40.Final
+ 4.0.41.Final1.7.211.1.76.9.10
From 0a0cdb81f9dd9c197370b89ba7d4af5281f2c73a Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 29 Aug 2016 22:11:57 +0200
Subject: [PATCH 011/901] Backport: Removed custom split method as it is not
effective anymore.
---
.../io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
index 3222566e06..2eb61a4444 100644
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
+++ b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
@@ -85,7 +85,7 @@ protected void encodeName(String name, ByteBuf buf) throws Exception {
return;
}
- final String[] labels = StringUtil.split(name, '.');
+ final String[] labels = name.split("\\.");
for (String label : labels) {
final int labelLen = label.length();
if (labelLen == 0) {
From 8f2b8a546dc8c9bbbe23102075c77525d2d76fa1 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Wed, 7 Sep 2016 10:12:04 +0200
Subject: [PATCH 012/901] Those are ints
---
.../org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java | 2 +-
.../asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java b/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java
index 7f3aae98af..0bd249049c 100755
--- a/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java
+++ b/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java
@@ -27,7 +27,7 @@ public ReadTimeoutTimerTask(//
NettyResponseFuture> nettyResponseFuture,//
NettyRequestSender requestSender,//
TimeoutsHolder timeoutsHolder,//
- long readTimeout) {
+ int readTimeout) {
super(nettyResponseFuture, requestSender, timeoutsHolder);
this.readTimeout = readTimeout;
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java b/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java
index 2546b69142..d108deea44 100755
--- a/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java
+++ b/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java
@@ -27,7 +27,7 @@ public RequestTimeoutTimerTask(//
NettyResponseFuture> nettyResponseFuture,//
NettyRequestSender requestSender,//
TimeoutsHolder timeoutsHolder,//
- long requestTimeout) {
+ int requestTimeout) {
super(nettyResponseFuture, requestSender, timeoutsHolder);
this.requestTimeout = requestTimeout;
}
From 596d4d941111797dc5dce29200958a5050537c3e Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Wed, 7 Sep 2016 10:12:14 +0200
Subject: [PATCH 013/901] Make constants public
---
.../main/java/org/asynchttpclient/netty/util/Utf8Decoder.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
index db6aeabefa..c4290804ea 100644
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
@@ -36,8 +36,8 @@ public abstract class Utf8Decoder {
12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 //
};
- protected static final int UTF8_ACCEPT = 0;
- protected static final int UTF8_REJECT = 12;
+ public static final int UTF8_ACCEPT = 0;
+ public static final int UTF8_REJECT = 12;
protected StringBuilder sb = new StringBuilder();
protected int state = UTF8_ACCEPT;
From cbb2cc924fd365c5f6dabf149e86161edbb8da97 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 9 Sep 2016 22:40:38 +0200
Subject: [PATCH 014/901] Upgrade netty-reactive-streams 1.0.7
---
client/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/pom.xml b/client/pom.xml
index fffce6e875..51159c36a3 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -52,7 +52,7 @@
com.typesafe.nettynetty-reactive-streams
- 1.0.6
+ 1.0.7org.javassist
From 622c498b468ae9620bc43e1d0befd375573c54ab Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 10 Sep 2016 23:27:34 +0200
Subject: [PATCH 015/901] Optimize UTF-8 HeapByteBuf(s) to String, close #1245
---
.../netty/ws/NettyWebSocket.java | 3 +-
.../netty/util/ByteBufUtils.java | 39 ++--
.../netty/util/UsAsciiByteBufDecoder.java | 48 ----
.../netty/util/Utf8ByteBufCharsetDecoder.java | 216 ++++++++++++++++++
.../netty/util/Utf8ByteBufDecoder.java | 50 ----
.../netty/util/Utf8Decoder.java | 82 -------
.../netty/util/ByteBufUtilsTest.java | 24 +-
7 files changed, 261 insertions(+), 201 deletions(-)
delete mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
create mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
delete mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
delete mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
diff --git a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
index b292e45868..c2903056a1 100755
--- a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
+++ b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
@@ -14,6 +14,7 @@
package org.asynchttpclient.netty.ws;
import static io.netty.buffer.Unpooled.wrappedBuffer;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asynchttpclient.netty.util.ByteBufUtils.byteBuf2Bytes;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaders;
@@ -220,7 +221,7 @@ public void onBinaryFrame(BinaryWebSocketFrame frame) {
public void onTextFrame(TextWebSocketFrame frame) {
if (interestedInTextMessages) {
try {
- notifyTextListeners(ByteBufUtils.byteBuf2Utf8String(frame.content()));
+ notifyTextListeners(ByteBufUtils.byteBuf2String(UTF_8, frame.content()));
} catch (CharacterCodingException e) {
throw new IllegalStateException(e);
}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
index 2bf7a65e2c..c5f66ac674 100755
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
@@ -13,35 +13,44 @@
*/
package org.asynchttpclient.netty.util;
+import static java.nio.charset.StandardCharsets.*;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.CompositeByteBuf;
+import io.netty.buffer.Unpooled;
-import java.io.UTFDataFormatException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.util.Collections;
public final class ByteBufUtils {
private ByteBufUtils() {
}
- public static String byteBuf2Utf8String(ByteBuf buf) throws CharacterCodingException {
- return Utf8ByteBufDecoder.pooled().decode(Collections.singleton(buf));
+ public static String byteBuf2String(Charset charset, ByteBuf buf) throws CharacterCodingException {
+ if (charset == UTF_8 || charset == US_ASCII) {
+ return Utf8ByteBufCharsetDecoder.decodeUtf8(buf);
+ } else {
+ return buf.toString(charset);
+ }
}
- public static String byteBuf2UsAsciiString(ByteBuf buf) throws CharacterCodingException {
- return UsAsciiByteBufDecoder.pooled().decode(Collections.singleton(buf));
- }
+ public static String byteBuf2String(Charset charset, ByteBuf... bufs) throws CharacterCodingException {
+ if (charset == UTF_8 || charset == US_ASCII) {
+ return Utf8ByteBufCharsetDecoder.decodeUtf8(bufs);
+ } else {
+ CompositeByteBuf composite = Unpooled.compositeBuffer(bufs.length);
- public static String byteBuf2String(ByteBuf buf, Charset charset) throws UTFDataFormatException, IndexOutOfBoundsException, CharacterCodingException {
+ try {
+ for (ByteBuf buf : bufs) {
+ buf.retain();
+ composite.addComponent(buf);
+ }
- if (charset.equals(StandardCharsets.US_ASCII)) {
- return byteBuf2UsAsciiString(buf);
- } else if (charset.equals(StandardCharsets.UTF_8)) {
- return byteBuf2Utf8String(buf);
- } else {
- return buf.toString(charset);
+ return composite.toString(charset);
+
+ } finally {
+ composite.release();
+ }
}
}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
deleted file mode 100644
index 0dbd9faf38..0000000000
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at
- * http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.netty.util;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.util.concurrent.FastThreadLocal;
-
-public class UsAsciiByteBufDecoder {
-
- private static final FastThreadLocal POOL = new FastThreadLocal() {
- protected UsAsciiByteBufDecoder initialValue() {
- return new UsAsciiByteBufDecoder();
- };
- };
-
- public static UsAsciiByteBufDecoder pooled() {
- UsAsciiByteBufDecoder decoder = POOL.get();
- decoder.reset();
- return decoder;
- }
-
- private StringBuilder sb = new StringBuilder();
-
- public void reset() {
- sb.setLength(0);
- }
-
- public String decode(Iterable bufs) {
- for (ByteBuf buf : bufs) {
- buf.forEachByte(b -> {
- sb.append((char) b);
- return true;
- });
- }
- return sb.toString();
- }
-}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
new file mode 100644
index 0000000000..1274409d7c
--- /dev/null
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
+package org.asynchttpclient.netty.util;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+
+public class Utf8ByteBufCharsetDecoder {
+
+ private static final ThreadLocal POOL = new ThreadLocal() {
+ protected Utf8ByteBufCharsetDecoder initialValue() {
+ return new Utf8ByteBufCharsetDecoder();
+ }
+ };
+
+ private static Utf8ByteBufCharsetDecoder pooledDecoder() {
+ Utf8ByteBufCharsetDecoder decoder = POOL.get();
+ decoder.reset();
+ return decoder;
+ }
+
+ public static String decodeUtf8(ByteBuf buf) throws CharacterCodingException {
+ return pooledDecoder().decode(buf);
+ }
+
+ public static String decodeUtf8(ByteBuf... bufs) throws CharacterCodingException {
+ return pooledDecoder().decode(bufs);
+ }
+
+ private final CharsetDecoder decoder = UTF_8.newDecoder();
+ protected CharBuffer charBuffer = allocateCharBuffer(1024);
+ private ByteBuffer splitCharBuffer;
+
+ protected void initSplitCharBuffer() {
+ if (splitCharBuffer == null) {
+ // UTF-8 chars are 4 bytes max
+ splitCharBuffer = ByteBuffer.allocate(4);
+ }
+ }
+
+ protected CharBuffer allocateCharBuffer(int l) {
+ return CharBuffer.allocate(l);
+ }
+
+ private void ensureCapacity(int l) {
+ if (charBuffer.position() == 0) {
+ if (charBuffer.capacity() < l) {
+ charBuffer = allocateCharBuffer(l);
+ }
+ } else if (charBuffer.remaining() < l) {
+ CharBuffer newCharBuffer = allocateCharBuffer(charBuffer.position() + l);
+ charBuffer.flip();
+ newCharBuffer.put(charBuffer);
+ charBuffer = newCharBuffer;
+ }
+ }
+
+ public void reset() {
+ decoder.reset();
+ charBuffer.position(0);
+ }
+
+ private static int charSize(byte firstByte) throws CharacterCodingException {
+ if ((firstByte >> 5) == -2 && (firstByte & 0x1e) != 0) {
+ // 2 bytes, 11 bits: 110xxxxx 10xxxxxx
+ return 2;
+
+ } else if ((firstByte >> 4) == -2) {
+ // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx
+ return 3;
+
+ } else if ((firstByte >> 3) == -2) {
+ // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ return 4;
+
+ } else {
+ // charSize isn't supposed to be called for regular bytes
+ throw new CharacterCodingException();
+ }
+ }
+
+ private void handleSplitCharBuffer(ByteBuffer nioBuffer, boolean endOfInput) throws CharacterCodingException {
+ // TODO we could save charSize
+ int missingBytes = charSize(splitCharBuffer.get(0)) - splitCharBuffer.position();
+
+ if (nioBuffer.remaining() < missingBytes) {
+ if (endOfInput) {
+ throw new CharacterCodingException();
+ }
+
+ // still not enough bytes
+ splitCharBuffer.put(nioBuffer);
+
+ } else {
+ // FIXME better way?
+ for (int i = 0; i < missingBytes; i++) {
+ splitCharBuffer.put(nioBuffer.get());
+ }
+
+ splitCharBuffer.flip();
+ CoderResult res = decoder.decode(splitCharBuffer, charBuffer, endOfInput && !nioBuffer.hasRemaining());
+ if (res.isError()) {
+ res.throwException();
+ }
+
+ splitCharBuffer.position(0);
+ }
+ }
+
+ protected void decodePartial(ByteBuffer nioBuffer, boolean endOfInput) throws CharacterCodingException {
+ // deal with pending splitCharBuffer
+ if (splitCharBuffer != null && splitCharBuffer.position() > 0 && nioBuffer.hasRemaining()) {
+ handleSplitCharBuffer(nioBuffer, endOfInput);
+ }
+
+ // decode remaining buffer
+ if (nioBuffer.hasRemaining()) {
+ CoderResult res = decoder.decode(nioBuffer, charBuffer, endOfInput);
+ if (res.isUnderflow()) {
+ if (nioBuffer.remaining() > 0) {
+ initSplitCharBuffer();
+ splitCharBuffer.put(nioBuffer);
+ }
+ } else if (res.isError()) {
+ res.throwException();
+ }
+ }
+ }
+
+ private void decode(ByteBuffer[] nioBuffers, int length) throws CharacterCodingException {
+ int count = nioBuffers.length;
+ for (int i = 0; i < count; i++) {
+ decodePartial(nioBuffers[i].duplicate(), i == count - 1);
+ }
+ }
+
+ private void decodeSingleNioBuffer(ByteBuffer nioBuffer, int length) throws CharacterCodingException {
+ CoderResult res = decoder.decode(nioBuffer, charBuffer, true);
+ if (res.isError()) {
+ res.throwException();
+ }
+ }
+
+ public String decode(ByteBuf buf) throws CharacterCodingException {
+ if (buf.isDirect()) {
+ return buf.toString(UTF_8);
+ }
+
+ int length = buf.readableBytes();
+ ensureCapacity(length);
+
+ if (buf.nioBufferCount() == 1) {
+ decodeSingleNioBuffer(buf.internalNioBuffer(buf.readerIndex(), length).duplicate(), length);
+ } else {
+ decode(buf.nioBuffers(), buf.readableBytes());
+ }
+
+ return charBuffer.flip().toString();
+ }
+
+ public String decode(ByteBuf... bufs) throws CharacterCodingException {
+
+ int totalSize = 0;
+ int totalNioBuffers = 0;
+ boolean direct = false;
+ for (ByteBuf buf : bufs) {
+ if (buf.isDirect()) {
+ direct = true;
+ break;
+ }
+ totalSize += buf.readableBytes();
+ totalNioBuffers += buf.nioBufferCount();
+ }
+
+ if (direct) {
+ ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bufs);
+ try {
+ return wrappedBuffer.toString(UTF_8);
+ } finally {
+ wrappedBuffer.release();
+ }
+
+ } else {
+ ByteBuffer[] nioBuffers = new ByteBuffer[totalNioBuffers];
+ int i = 0;
+ for (ByteBuf buf : bufs) {
+ for (ByteBuffer nioBuffer : buf.nioBuffers()) {
+ nioBuffers[i++] = nioBuffer;
+ }
+ }
+
+ ensureCapacity(totalSize);
+ decode(nioBuffers, totalSize);
+
+ return charBuffer.flip().toString();
+ }
+ }
+}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
deleted file mode 100644
index fddcdcdd4c..0000000000
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at
- * http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.netty.util;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.util.concurrent.FastThreadLocal;
-
-import java.nio.charset.CharacterCodingException;
-
-public class Utf8ByteBufDecoder extends Utf8Decoder {
-
- private static final FastThreadLocal POOL = new FastThreadLocal() {
- protected Utf8ByteBufDecoder initialValue() {
- return new Utf8ByteBufDecoder();
- };
- };
-
- public static Utf8ByteBufDecoder pooled() {
- Utf8ByteBufDecoder decoder = POOL.get();
- decoder.reset();
- return decoder;
- }
-
- public String decode(Iterable bufs) throws CharacterCodingException {
-
- for (ByteBuf buf : bufs) {
- buf.forEachByte(value -> {
- write(value);
- return true;
- });
- }
-
- if (state == UTF8_ACCEPT) {
- return sb.toString();
- } else {
- throw new CharacterCodingException();
- }
- }
-}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
deleted file mode 100644
index c4290804ea..0000000000
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at
- * http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.netty.util;
-
-import java.nio.charset.CharacterCodingException;
-
-public abstract class Utf8Decoder {
-
- private static final byte[] TYPES = new byte[] {//
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,/**/
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,/**/
- 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/**/
- 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 /**/
- };
-
- private static final byte[] STATES = new byte[] {//
- 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,/**/
- 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 24, 12, 12,/**/
- 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12,/**/
- 12, 12, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12,/**/
- 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 //
- };
-
- public static final int UTF8_ACCEPT = 0;
- public static final int UTF8_REJECT = 12;
-
- protected StringBuilder sb = new StringBuilder();
- protected int state = UTF8_ACCEPT;
- private int codePoint = 0;
-
- protected void write(byte b) throws CharacterCodingException {
- int t = TYPES[b & 0xFF];
-
- codePoint = state != UTF8_ACCEPT ? (b & 0x3f) | (codePoint << 6) : (0xff >> t) & b;
- state = STATES[state + t];
-
- if (state == UTF8_ACCEPT) {
- if (codePoint < Character.MIN_HIGH_SURROGATE) {
- sb.append((char) codePoint);
- } else {
- appendCodePointChars();
- }
- } else if (state == UTF8_REJECT) {
- throw new CharacterCodingException();
- }
- }
-
- private void appendCodePointChars() {
- if (Character.isBmpCodePoint(codePoint)) {
- sb.append((char) codePoint);
-
- } else if (Character.isValidCodePoint(codePoint)) {
- char charIndexPlus1 = Character.lowSurrogate(codePoint);
- char charIndex = Character.highSurrogate(codePoint);
- sb.append(charIndex).append(charIndexPlus1);
-
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- public void reset() {
- sb.setLength(0);
- state = UTF8_ACCEPT;
- codePoint = 0;
- }
-}
diff --git a/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java b/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
index fd80a58f6e..a7da5290f2 100644
--- a/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
+++ b/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
@@ -1,5 +1,19 @@
+/*
+ * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.netty.util;
+import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.testng.Assert.assertEquals;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@@ -10,18 +24,18 @@ public class ByteBufUtilsTest {
@Test
public void testByteBuf2BytesHasBackingArray() {
- byte[] input = "testdata".getBytes();
- ByteBuf inputBuf = Unpooled.copiedBuffer(input);
+ byte[] inputBytes = "testdata".getBytes(US_ASCII);
+ ByteBuf inputBuf = Unpooled.wrappedBuffer(inputBytes);
byte[] output = ByteBufUtils.byteBuf2Bytes(inputBuf);
- assertEquals(output, input, "The bytes returned by byteBuf2Bytes do not match the bytes in the ByteBuf parameter");
+ assertEquals(output, inputBytes);
}
@Test
public void testByteBuf2BytesNoBackingArray() {
+ byte[] inputBytes = "testdata".getBytes(US_ASCII);
ByteBuf inputBuf = Unpooled.directBuffer();
- byte[] inputBytes = "testdata".getBytes();
inputBuf.writeBytes(inputBytes);
byte[] output = ByteBufUtils.byteBuf2Bytes(inputBuf);
- assertEquals(output, inputBytes, "The bytes returned by byteBuf2Bytes do not match the bytes in the ByteBuf parameter");
+ assertEquals(output, inputBytes);
}
}
From 5d027b10f5e5f7d1279af8f61ef415c0938f3d2f Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 10 Sep 2016 23:33:03 +0200
Subject: [PATCH 016/901] [maven-release-plugin] prepare release
async-http-client-project-2.0.15
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
13 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 51159c36a3..7b8c67d3fa 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index a71a8362b4..217f12c9c7 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 8de1fcfcad..d11049e921 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15-SNAPSHOT
+ 2.0.15async-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 417e554bb4..9a1eb9d7dd 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 5f4bbb2dd5..de7a2b8bcf 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index c39037e117..7677e6cf3d 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15-SNAPSHOT
+ 2.0.15async-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 05d4f93c3c..bd311d3239 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15-SNAPSHOT
+ 2.0.15async-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index c7a21ff88a..63cf0f16d8 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15-SNAPSHOT
+ 2.0.15netty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index bbe5182a05..175f38af13 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index 749bf0c075..c6c0d596af 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.15-SNAPSHOT
+ 2.0.15netty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index c9039801b7..0fdb75246c 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15-SNAPSHOT
+ 2.0.15netty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index a70646b204..6db7dea0de 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index a4fc7760b5..86b0641f64 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.15-SNAPSHOT
+ 2.0.15pom
The Async Http Client (AHC) library's purpose is to allow Java
From 676a28bf82c5a90fcff63f079cebd9628b2513af Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 10 Sep 2016 23:33:10 +0200
Subject: [PATCH 017/901] [maven-release-plugin] prepare for next development
iteration
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
13 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 7b8c67d3fa..1b0f7bd327 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 217f12c9c7..aec5d9435e 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index d11049e921..dda4498657 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15
+ 2.0.16-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 9a1eb9d7dd..811f531089 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index de7a2b8bcf..e1906e8a5b 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 7677e6cf3d..a3fda543c1 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15
+ 2.0.16-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index bd311d3239..bc402747b5 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15
+ 2.0.16-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 63cf0f16d8..18f123e93c 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15
+ 2.0.16-SNAPSHOTnetty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 175f38af13..8d40fd4704 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index c6c0d596af..f7e8499c9d 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.15
+ 2.0.16-SNAPSHOTnetty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 0fdb75246c..55de914163 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15
+ 2.0.16-SNAPSHOTnetty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index 6db7dea0de..bf6b58e705 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index 86b0641f64..eb1463fee2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.15
+ 2.0.16-SNAPSHOTpom
The Async Http Client (AHC) library's purpose is to allow Java
From ba16cfc938d90f8d7fa3e6b7f484fc7baf9daebc Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sun, 11 Sep 2016 00:01:56 +0200
Subject: [PATCH 018/901] Short path when one single buf
---
.../asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
index 1274409d7c..ccc35c27dd 100644
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
@@ -177,6 +177,9 @@ public String decode(ByteBuf buf) throws CharacterCodingException {
}
public String decode(ByteBuf... bufs) throws CharacterCodingException {
+ if (bufs.length == 1) {
+ return decode(bufs[0]);
+ }
int totalSize = 0;
int totalNioBuffers = 0;
From d72b89e042b41b8f32d4883702a37886d00e23ac Mon Sep 17 00:00:00 2001
From: Dmitriy Dumanskiy
Date: Mon, 12 Sep 2016 23:34:03 +0300
Subject: [PATCH 019/901] #1246 added "ThreadSafe" in comments section for
DefaultAsyncHttpClient
---
.../main/java/org/asynchttpclient/DefaultAsyncHttpClient.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
index 897b6e25e8..db884e55ad 100644
--- a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
+++ b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
@@ -33,6 +33,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+/**
+ * Default and threadsafe implementation of {@link AsyncHttpClient}.
+ */
public class DefaultAsyncHttpClient implements AsyncHttpClient {
private final static Logger LOGGER = LoggerFactory.getLogger(DefaultAsyncHttpClient.class);
From 8fb7c9d236251d8df4671a74ca48ab198e34d5a5 Mon Sep 17 00:00:00 2001
From: Tom Wieczorek
Date: Sun, 18 Sep 2016 18:05:14 +0200
Subject: [PATCH 020/901] Enable asynchronous cancellation of AsyncHttpSingle.
(#1250)
AsyncHttpSingle is currently not forwarding an unsubscription to AsyncHttpClient, it just aborts request processing when an AsyncHandler callback method is invoked. To actually eagerly cancel a request on unsubscription, use the request future to actually forward the cancellation to AsyncHttpClient.
---
.../extras/rxjava/UnsubscribedException.java | 6 ++--
.../extras/rxjava/single/AsyncHttpSingle.java | 25 +++++++++++----
.../rxjava/single/AsyncHttpSingleTest.java | 32 +++++++++++++++++++
3 files changed, 55 insertions(+), 8 deletions(-)
diff --git a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java
index f954f7236e..c1a7099dbe 100644
--- a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java
+++ b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java
@@ -12,16 +12,18 @@
*/
package org.asynchttpclient.extras.rxjava;
+import java.util.concurrent.CancellationException;
+
/**
* Indicates that an {@code Observer} unsubscribed during the processing of a HTTP request.
*/
@SuppressWarnings("serial")
-public class UnsubscribedException extends RuntimeException {
+public class UnsubscribedException extends CancellationException {
public UnsubscribedException() {
}
public UnsubscribedException(final Throwable cause) {
- super(cause);
+ initCause(cause);
}
}
diff --git a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java
index d244fbba84..4e95aab846 100644
--- a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java
+++ b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java
@@ -20,10 +20,13 @@
import org.asynchttpclient.Response;
import org.asynchttpclient.handler.ProgressAsyncHandler;
+import java.util.concurrent.Future;
+
import rx.Single;
import rx.SingleSubscriber;
-import rx.functions.Action1;
import rx.functions.Func0;
+import rx.functions.Func1;
+import rx.subscriptions.Subscriptions;
/**
* Wraps HTTP requests into RxJava {@code Single} instances.
@@ -54,14 +57,17 @@ public static Single create(BoundRequestBuilder builder) {
*
* @param requestTemplate called to start the HTTP request with an
* {@code AysncHandler} that builds the HTTP response and
- * propagates results to the returned {@code Single}
+ * propagates results to the returned {@code Single}. The
+ * {@code Future} that is returned by {@code requestTemplate}
+ * will be used to cancel the request when the {@code Single} is
+ * unsubscribed.
*
* @return a {@code Single} that executes new requests on subscription by
* calling {@code requestTemplate} and that emits the response
*
* @throws NullPointerException if {@code requestTemplate} is {@code null}
*/
- public static Single create(Action1 super AsyncHandler>> requestTemplate) {
+ public static Single create(Func1 super AsyncHandler>, ? extends Future>> requestTemplate) {
return create(requestTemplate, AsyncCompletionHandlerBase::new);
}
@@ -92,7 +98,10 @@ public static Single create(BoundRequestBuilder builder, Func0 extends
*
* @param requestTemplate called to start the HTTP request with an
* {@code AysncHandler} that builds the HTTP response and
- * propagates results to the returned {@code Single}
+ * propagates results to the returned {@code Single}. The
+ * {@code Future} that is returned by {@code requestTemplate}
+ * will be used to cancel the request when the {@code Single} is
+ * unsubscribed.
* @param handlerSupplier supplies the desired {@code AsyncHandler}
* instances that are used to produce results
*
@@ -104,13 +113,17 @@ public static Single create(BoundRequestBuilder builder, Func0 extends
* @throws NullPointerException if at least one of the parameters is
* {@code null}
*/
- public static Single create(Action1 super AsyncHandler>> requestTemplate,
+ public static Single create(Func1 super AsyncHandler>, ? extends Future>> requestTemplate,
Func0 extends AsyncHandler extends T>> handlerSupplier) {
requireNonNull(requestTemplate);
requireNonNull(handlerSupplier);
- return Single.create(subscriber -> requestTemplate.call(createBridge(subscriber, handlerSupplier.call())));
+ return Single.create(subscriber -> {
+ final AsyncHandler> bridge = createBridge(subscriber, handlerSupplier.call());
+ final Future> responseFuture = requestTemplate.call(bridge);
+ subscriber.add(Subscriptions.from(responseFuture));
+ });
}
static AsyncHandler> createBridge(SingleSubscriber super T> subscriber, AsyncHandler extends T> handler) {
diff --git a/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java b/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
index d0039bc73f..83ada0a068 100644
--- a/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
+++ b/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
@@ -18,6 +18,7 @@
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -25,6 +26,7 @@
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
@@ -34,13 +36,16 @@
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.HttpResponseStatus;
import org.asynchttpclient.Response;
+import org.asynchttpclient.extras.rxjava.UnsubscribedException;
import org.asynchttpclient.handler.ProgressAsyncHandler;
import org.mockito.InOrder;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
import rx.Single;
import rx.exceptions.CompositeException;
@@ -82,6 +87,8 @@ public void testSuccessfulCompletion() throws Exception {
} catch (final Throwable t) {
bridge.onThrowable(t);
}
+
+ return mock(Future.class);
} , () -> handler);
final TestSubscriber
diff --git a/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java b/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
index 83ada0a068..55ae64c15a 100644
--- a/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
+++ b/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
@@ -66,6 +66,7 @@ public void testFailsOnNullHandlerSupplier() {
@Test(groups = "standalone")
public void testSuccessfulCompletion() throws Exception {
+ @SuppressWarnings("unchecked")
final AsyncHandler handler = mock(AsyncHandler.class);
when(handler.onCompleted()).thenReturn(handler);
@@ -106,6 +107,7 @@ public void testSuccessfulCompletion() throws Exception {
@Test(groups = "standalone")
public void testSuccessfulCompletionWithProgress() throws Exception {
+ @SuppressWarnings("unchecked")
final ProgressAsyncHandler handler = mock(ProgressAsyncHandler.class);
when(handler.onCompleted()).thenReturn(handler);
final InOrder inOrder = inOrder(handler);
@@ -171,6 +173,7 @@ public void testNewRequestForEachSubscription() throws Exception {
public void testErrorPropagation() throws Exception {
final RuntimeException expectedException = new RuntimeException("expected");
+ @SuppressWarnings("unchecked")
final AsyncHandler handler = mock(AsyncHandler.class);
when(handler.onCompleted()).thenReturn(handler);
final InOrder inOrder = inOrder(handler);
@@ -214,6 +217,7 @@ public void testErrorPropagation() throws Exception {
public void testErrorInOnCompletedPropagation() throws Exception {
final RuntimeException expectedException = new RuntimeException("expected");
+ @SuppressWarnings("unchecked")
final AsyncHandler handler = mock(AsyncHandler.class);
when(handler.onCompleted()).thenThrow(expectedException);
@@ -243,6 +247,7 @@ public void testErrorInOnThrowablePropagation() throws Exception {
final RuntimeException processingException = new RuntimeException("processing");
final RuntimeException thrownException = new RuntimeException("thrown");
+ @SuppressWarnings("unchecked")
final AsyncHandler handler = mock(AsyncHandler.class);
doThrow(thrownException).when(handler).onThrowable(processingException);
@@ -296,6 +301,7 @@ public State onStatusReceived(HttpResponseStatus status) {
@Test(groups = "standalone")
public void testUnsubscribe() throws Exception {
+ @SuppressWarnings("unchecked")
final AsyncHandler handler = mock(AsyncHandler.class);
final Future> future = mock(Future.class);
final AtomicReference> bridgeRef = new AtomicReference<>();
From 9689dea08e01e98da15096bc2ada36b8d9a563d4 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 29 Oct 2016 09:47:18 +0200
Subject: [PATCH 073/901] [maven-release-plugin] prepare release
async-http-client-project-2.0.21
---
client/pom.xml | 2 +-
example/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
14 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index becf73c1f0..17bb7f1fb7 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21-SNAPSHOT
+ 2.0.214.0.0async-http-client
diff --git a/example/pom.xml b/example/pom.xml
index c85d62ab97..abec85711d 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21-SNAPSHOT
+ 2.0.214.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index a724493cae..09d158bdb4 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.21-SNAPSHOT
+ 2.0.214.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 4859d949b1..50ec34df48 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.21-SNAPSHOT
+ 2.0.21async-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 67bdc7706d..bc13feda9f 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21-SNAPSHOT
+ 2.0.214.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index c35fc6ce1a..0f63df293a 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.21-SNAPSHOT
+ 2.0.214.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 7c96111ba3..9e4cf8f3f3 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.21-SNAPSHOT
+ 2.0.21async-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 58500cd6e8..0346fe640f 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.21-SNAPSHOT
+ 2.0.21async-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 4f0e41a0d7..53c723af22 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.21-SNAPSHOT
+ 2.0.21netty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index e0dba8f60b..417c3813b9 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21-SNAPSHOT
+ 2.0.214.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index f6cf3bd78c..872c83058d 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.21-SNAPSHOT
+ 2.0.21netty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 647baab2fa..cf17a6d5ae 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.21-SNAPSHOT
+ 2.0.21netty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index 7efd0353eb..ff7d442b2b 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21-SNAPSHOT
+ 2.0.214.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index 809ecfdc0b..7056a3fab1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.21-SNAPSHOT
+ 2.0.21pom
The Async Http Client (AHC) library's purpose is to allow Java
From 8988ecadcb1aab09d3651afde084928c017542fd Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 29 Oct 2016 09:47:24 +0200
Subject: [PATCH 074/901] [maven-release-plugin] prepare for next development
iteration
---
client/pom.xml | 2 +-
example/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
14 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 17bb7f1fb7..31d5153b27 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21
+ 2.0.22-SNAPSHOT4.0.0async-http-client
diff --git a/example/pom.xml b/example/pom.xml
index abec85711d..eecf3b339b 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21
+ 2.0.22-SNAPSHOT4.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 09d158bdb4..7cca1704ab 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.21
+ 2.0.22-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 50ec34df48..700ee9afa1 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.21
+ 2.0.22-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index bc13feda9f..5f31d528f2 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21
+ 2.0.22-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 0f63df293a..ed1373a3af 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.21
+ 2.0.22-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 9e4cf8f3f3..0b4d3cad9b 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.21
+ 2.0.22-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 0346fe640f..8593da1585 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.21
+ 2.0.22-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 53c723af22..8a878b8e82 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.21
+ 2.0.22-SNAPSHOTnetty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 417c3813b9..1deec666d6 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21
+ 2.0.22-SNAPSHOT4.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index 872c83058d..e4cb0eecce 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.21
+ 2.0.22-SNAPSHOTnetty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index cf17a6d5ae..881c726356 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.21
+ 2.0.22-SNAPSHOTnetty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index ff7d442b2b..5ff00181f5 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.21
+ 2.0.22-SNAPSHOT4.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index 7056a3fab1..edead3b84a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.21
+ 2.0.22-SNAPSHOTpom
The Async Http Client (AHC) library's purpose is to allow Java
From 86c07cc4064b2875864f6d467eb0961a1b0851b7 Mon Sep 17 00:00:00 2001
From: Dmitry Spikhalskiy
Date: Tue, 1 Nov 2016 11:13:24 +0300
Subject: [PATCH 075/901] Expose additional set headers method for headers with
single and multiple values (#1296)
Thanks!
---
.../asynchttpclient/RequestBuilderBase.java | 81 +++++++++++++++++--
1 file changed, 75 insertions(+), 6 deletions(-)
diff --git a/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java b/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java
index 0beba8b256..0af80b936a 100644
--- a/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java
+++ b/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java
@@ -168,11 +168,48 @@ public T setVirtualHost(String virtualHost) {
return asDerivedType();
}
+ /**
+ * Remove all added headers
+ *
+ * @return {@code this}
+ */
+ public T clearHeaders() {
+ this.headers.clear();
+ return asDerivedType();
+ }
+
+ /**
+ * Set uni-value header for the request
+ *
+ * @param name header name
+ * @param value header value to set
+ * @return {@code this}
+ */
public T setHeader(CharSequence name, String value) {
this.headers.set(name, value);
return asDerivedType();
}
+ /**
+ * Set multi-values header for the request
+ *
+ * @param name header name
+ * @param values {@code Iterable} with multiple header values to set
+ * @return {@code this}
+ */
+ public T setHeader(CharSequence name, Iterable values) {
+ this.headers.set(name, values);
+ return asDerivedType();
+ }
+
+ /**
+ * Add a header value for the request. If a header with {@code name} was setup for this request already -
+ * call will add one more header value and convert it to multi-value header
+ *
+ * @param name header name
+ * @param value header value to add
+ * @return {@code this}
+ */
public T addHeader(CharSequence name, String value) {
if (value == null) {
LOGGER.warn("Value was null, set to \"\"");
@@ -183,6 +220,19 @@ public T addHeader(CharSequence name, String value) {
return asDerivedType();
}
+ /**
+ * Add header values for the request. If a header with {@code name} was setup for this request already -
+ * call will add more header values and convert it to multi-value header
+ *
+ * @param name header name
+ * @param values {@code Iterable} with multiple header values to add
+ * @return {@code}
+ */
+ public T addHeader(CharSequence name, Iterable values) {
+ this.headers.add(name, values);
+ return asDerivedType();
+ }
+
public T setHeaders(HttpHeaders headers) {
if (headers == null)
this.headers.clear();
@@ -191,13 +241,32 @@ public T setHeaders(HttpHeaders headers) {
return asDerivedType();
}
- public T setHeaders(Map> headers) {
- this.headers.clear();
+ /**
+ * Set request headers using a map {@code headers} of pair (Header name, Header values)
+ * This method could be used to setup multi-valued headers
+ *
+ * @param headers map of header names as the map keys and header values {@link Iterable} as the map values
+ * @return {@code this}
+ */
+ public T setHeaders(Map> headers) {
+ clearHeaders();
if (headers != null) {
- for (Map.Entry> entry : headers.entrySet()) {
- String headerName = entry.getKey();
- this.headers.add(headerName, entry.getValue());
- }
+ headers.forEach((name, values) -> this.headers.add(name, values));
+ }
+ return asDerivedType();
+ }
+
+ /**
+ * Set single-value request headers using a map {@code headers} of pairs (Header name, Header value).
+ * To set headers with multiple values use {@link #setHeaders(Map)}
+ *
+ * @param headers map of header names as the map keys and header values as the map values
+ * @return {@code this}
+ */
+ public T setSingleHeaders(Map headers) {
+ clearHeaders();
+ if (headers != null) {
+ headers.forEach((name, value) -> this.headers.add(name, value));
}
return asDerivedType();
}
From a9a6ae520ed425a009aa14f420bc9d128a854246 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Wed, 2 Nov 2016 21:13:57 +0100
Subject: [PATCH 076/901] nit
---
client/src/test/resources/logback-test.xml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/src/test/resources/logback-test.xml b/client/src/test/resources/logback-test.xml
index 4acf278710..3ddbad8487 100644
--- a/client/src/test/resources/logback-test.xml
+++ b/client/src/test/resources/logback-test.xml
@@ -7,7 +7,7 @@
-
+
-
\ No newline at end of file
+
From 1da0a86cffdf99d9d0533773b6b7ccaacb0da34b Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Wed, 2 Nov 2016 21:14:22 +0100
Subject: [PATCH 077/901] Add warning about blocking operation, see #1298
---
client/src/main/java/org/asynchttpclient/AsyncHandler.java | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/client/src/main/java/org/asynchttpclient/AsyncHandler.java b/client/src/main/java/org/asynchttpclient/AsyncHandler.java
index 99ff742715..0b00cc179a 100644
--- a/client/src/main/java/org/asynchttpclient/AsyncHandler.java
+++ b/client/src/main/java/org/asynchttpclient/AsyncHandler.java
@@ -40,6 +40,10 @@
* client.prepareGet("http://.../").execute(ah);
*
* It is recommended to create a new instance instead.
+ *
+ * Do NOT perform any blocking operation in there, typically trying to send another request and call get() on its future.
+ * There's a chance you might end up in a dead lock.
+ * If you really to perform blocking operation, executed it in a different dedicated thread pool.
*
* @param Type of object returned by the {@link java.util.concurrent.Future#get}
*/
From abafe2b150bb27db690a29b3d173bb13dbcad011 Mon Sep 17 00:00:00 2001
From: Grenville Wilson
Date: Sat, 5 Nov 2016 04:36:51 -0400
Subject: [PATCH 078/901] Fixing a broken test (#1300)
---
.../java/org/asynchttpclient/PerRequestRelative302Test.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/src/test/java/org/asynchttpclient/PerRequestRelative302Test.java b/client/src/test/java/org/asynchttpclient/PerRequestRelative302Test.java
index cc079e475d..8156aa0e36 100644
--- a/client/src/test/java/org/asynchttpclient/PerRequestRelative302Test.java
+++ b/client/src/test/java/org/asynchttpclient/PerRequestRelative302Test.java
@@ -91,12 +91,12 @@ public void runAllSequentiallyBecauseNotThreadSafe() throws Exception {
public void redirected302Test() throws Exception {
isSet.getAndSet(false);
try (AsyncHttpClient c = asyncHttpClient()) {
- Response response = c.prepareGet(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", "http://www.microsoft.com/").execute().get();
+ Response response = c.prepareGet(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", "https://www.microsoft.com/").execute().get();
assertNotNull(response);
assertEquals(response.getStatusCode(), 200);
- String anyMicrosoftPage = "http://www.microsoft.com[^:]*:80";
+ String anyMicrosoftPage = "https://www.microsoft.com[^:]*:443";
String baseUrl = getBaseUrl(response.getUri());
assertTrue(baseUrl.matches(anyMicrosoftPage), "response does not show redirection to " + anyMicrosoftPage);
From a887e92c44393255ddc624425f5c248fdf35a68c Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Thu, 3 Nov 2016 08:19:21 +0100
Subject: [PATCH 079/901] Missing file headers
---
.../codec/http/HttpContentDecoder.java | 253 ++++++++++++++++++
.../AsyncHttpClientDefaultsTest.java | 13 +
.../asynchttpclient/PostRedirectGetTest.java | 1 -
.../{RC10KTest.java => RC1KTest.java} | 12 +-
.../org/asynchttpclient/RedirectBodyTest.java | 13 +
.../resumable/MapResumableProcessor.java | 13 +
...PropertiesBasedResumableProcesserTest.java | 3 +-
.../resumable/ResumableAsyncHandlerTest.java | 3 +-
...ResumableRandomAccessFileListenerTest.java | 13 +
.../netty/EventPipelineTest.java | 1 -
.../netty/NettyAsyncResponseTest.java | 1 -
.../netty/NettyResponseFutureTest.java | 13 +
.../ReactiveStreamsDownLoadTest.java | 13 +
.../ByteArrayBodyGeneratorTest.java | 1 -
.../multipart/part/MultipartPartTest.java | 13 +
.../org/asynchttpclient/test/EchoHandler.java | 13 +
.../org/asynchttpclient/test/TestUtils.java | 13 +
.../asynchttpclient/uri/UriParserTest.java | 13 +
.../asynchttpclient/util/HttpUtilsTest.java | 13 +
.../org/asynchttpclient/ws/EchoSocket.java | 13 +
20 files changed, 417 insertions(+), 14 deletions(-)
create mode 100644 client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java
rename client/src/test/java/org/asynchttpclient/{RC10KTest.java => RC1KTest.java} (94%)
diff --git a/client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java b/client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java
new file mode 100644
index 0000000000..3cfadcb0db
--- /dev/null
+++ b/client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright 2012 The Netty Project
+ *
+ * The Netty Project 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 io.netty.handler.codec.http;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.embedded.EmbeddedChannel;
+import io.netty.handler.codec.CodecException;
+import io.netty.handler.codec.MessageToMessageDecoder;
+import io.netty.util.ReferenceCountUtil;
+
+import java.util.List;
+
+/**
+ * Decodes the content of the received {@link HttpRequest} and {@link HttpContent}.
+ * The original content is replaced with the new content decoded by the
+ * {@link EmbeddedChannel}, which is created by {@link #newContentDecoder(String)}.
+ * Once decoding is finished, the value of the 'Content-Encoding'
+ * header is set to the target content encoding, as returned by {@link #getTargetContentEncoding(String)}.
+ * Also, the 'Content-Length' header is updated to the length of the
+ * decoded content. If the content encoding of the original is not supported
+ * by the decoder, {@link #newContentDecoder(String)} should return {@code null}
+ * so that no decoding occurs (i.e. pass-through).
+ *
+ * Please note that this is an abstract class. You have to extend this class
+ * and implement {@link #newContentDecoder(String)} properly to make this class
+ * functional. For example, refer to the source code of {@link HttpContentDecompressor}.
+ *
+ * This handler must be placed after {@link HttpObjectDecoder} in the pipeline
+ * so that this handler can intercept HTTP requests after {@link HttpObjectDecoder}
+ * converts {@link ByteBuf}s into HTTP requests.
+ */
+public abstract class HttpContentDecoder extends MessageToMessageDecoder {
+
+ protected ChannelHandlerContext ctx;
+ private EmbeddedChannel decoder;
+ private boolean continueResponse;
+
+ @Override
+ protected void decode(ChannelHandlerContext ctx, HttpObject msg, List out) throws Exception {
+ if (msg instanceof HttpResponse && ((HttpResponse) msg).getStatus().code() == 100) {
+
+ if (!(msg instanceof LastHttpContent)) {
+ continueResponse = true;
+ }
+ // 100-continue response must be passed through.
+ out.add(ReferenceCountUtil.retain(msg));
+ return;
+ }
+
+ if (continueResponse) {
+ if (msg instanceof LastHttpContent) {
+ continueResponse = false;
+ }
+ // 100-continue response must be passed through.
+ out.add(ReferenceCountUtil.retain(msg));
+ return;
+ }
+
+ if (msg instanceof HttpMessage) {
+ cleanup();
+ final HttpMessage message = (HttpMessage) msg;
+ final HttpHeaders headers = message.headers();
+
+ // Determine the content encoding.
+ String contentEncoding = headers.get(HttpHeaders.Names.CONTENT_ENCODING);
+ if (contentEncoding != null) {
+ contentEncoding = contentEncoding.trim();
+ } else {
+ contentEncoding = HttpHeaders.Values.IDENTITY;
+ }
+ decoder = newContentDecoder(contentEncoding);
+
+ if (decoder == null) {
+ if (message instanceof HttpContent) {
+ ((HttpContent) message).retain();
+ }
+ out.add(message);
+ return;
+ }
+
+ // Remove content-length header:
+ // the correct value can be set only after all chunks are processed/decoded.
+ // If buffering is not an issue, add HttpObjectAggregator down the chain, it will set the header.
+ // Otherwise, rely on LastHttpContent message.
+ if (headers.contains(HttpHeaders.Names.CONTENT_LENGTH)) {
+ headers.remove(HttpHeaders.Names.CONTENT_LENGTH);
+ headers.set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
+ }
+
+ // set new content encoding,
+ CharSequence targetContentEncoding = getTargetContentEncoding(contentEncoding);
+ if (HttpHeaders.Values.IDENTITY.equals(targetContentEncoding)) {
+ // Do NOT set the 'Content-Encoding' header if the target encoding is 'identity'
+ // as per: http://tools.ietf.org/html/rfc2616#section-14.11
+ headers.remove(HttpHeaders.Names.CONTENT_ENCODING);
+ } else {
+ headers.set(HttpHeaders.Names.CONTENT_ENCODING, targetContentEncoding);
+ }
+
+ if (message instanceof HttpContent) {
+ // If message is a full request or response object (headers + data), don't copy data part into out.
+ // Output headers only; data part will be decoded below.
+ // Note: "copy" object must not be an instance of LastHttpContent class,
+ // as this would (erroneously) indicate the end of the HttpMessage to other handlers.
+ HttpMessage copy;
+ if (message instanceof HttpRequest) {
+ HttpRequest r = (HttpRequest) message; // HttpRequest or FullHttpRequest
+ copy = new DefaultHttpRequest(r.getProtocolVersion(), r.getMethod(), r.getUri());
+ } else if (message instanceof HttpResponse) {
+ HttpResponse r = (HttpResponse) message; // HttpResponse or FullHttpResponse
+ copy = new DefaultHttpResponse(r.getProtocolVersion(), r.getStatus());
+ } else {
+ throw new CodecException("Object of class " + message.getClass().getName() +
+ " is not a HttpRequest or HttpResponse");
+ }
+ copy.headers().set(message.headers());
+ copy.setDecoderResult(message.getDecoderResult());
+ out.add(copy);
+ } else {
+ out.add(message);
+ }
+ }
+
+ if (msg instanceof HttpContent) {
+ final HttpContent c = (HttpContent) msg;
+ if (decoder == null) {
+ out.add(c.retain());
+ } else {
+ decodeContent(c, out);
+ }
+ }
+ }
+
+ private void decodeContent(HttpContent c, List out) {
+ ByteBuf content = c.content();
+
+ decode(content, out);
+
+ if (c instanceof LastHttpContent) {
+ finishDecode(out);
+
+ LastHttpContent last = (LastHttpContent) c;
+ // Generate an additional chunk if the decoder produced
+ // the last product on closure,
+ HttpHeaders headers = last.trailingHeaders();
+ if (headers.isEmpty()) {
+ out.add(LastHttpContent.EMPTY_LAST_CONTENT);
+ } else {
+ out.add(new ComposedLastHttpContent(headers));
+ }
+ }
+ }
+
+ /**
+ * Returns a new {@link EmbeddedChannel} that decodes the HTTP message
+ * content encoded in the specified contentEncoding.
+ *
+ * @param contentEncoding the value of the {@code "Content-Encoding"} header
+ * @return a new {@link EmbeddedChannel} if the specified encoding is supported.
+ * {@code null} otherwise (alternatively, you can throw an exception
+ * to block unknown encoding).
+ */
+ protected abstract EmbeddedChannel newContentDecoder(String contentEncoding) throws Exception;
+
+ /**
+ * Returns the expected content encoding of the decoded content.
+ * This getMethod returns {@code "identity"} by default, which is the case for
+ * most decoders.
+ *
+ * @param contentEncoding the value of the {@code "Content-Encoding"} header
+ * @return the expected content encoding of the new content
+ */
+ protected String getTargetContentEncoding(
+ @SuppressWarnings("UnusedParameters") String contentEncoding) throws Exception {
+ return HttpHeaders.Values.IDENTITY;
+ }
+
+ @Override
+ public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
+ cleanup();
+ super.handlerRemoved(ctx);
+ }
+
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+ cleanup();
+ super.channelInactive(ctx);
+ }
+
+ @Override
+ public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
+ this.ctx = ctx;
+ super.handlerAdded(ctx);
+ }
+
+ private void cleanup() {
+ if (decoder != null) {
+ // Clean-up the previous decoder if not cleaned up correctly.
+ if (decoder.finish()) {
+ for (;;) {
+ ByteBuf buf = (ByteBuf) decoder.readInbound();
+ if (buf == null) {
+ break;
+ }
+ // Release the buffer
+ buf.release();
+ }
+ }
+ decoder = null;
+ }
+ }
+
+ private void decode(ByteBuf in, List out) {
+ // call retain here as it will call release after its written to the channel
+ decoder.writeInbound(in.retain());
+ fetchDecoderOutput(out);
+ }
+
+ private void finishDecode(List out) {
+ if (decoder.finish()) {
+ fetchDecoderOutput(out);
+ }
+ decoder = null;
+ }
+
+ private void fetchDecoderOutput(List out) {
+ for (;;) {
+ ByteBuf buf = (ByteBuf) decoder.readInbound();
+ if (buf == null) {
+ break;
+ }
+ if (!buf.isReadable()) {
+ buf.release();
+ continue;
+ }
+ out.add(new DefaultHttpContent(buf));
+ }
+ }
+}
diff --git a/client/src/test/java/org/asynchttpclient/AsyncHttpClientDefaultsTest.java b/client/src/test/java/org/asynchttpclient/AsyncHttpClientDefaultsTest.java
index 00e4d7c4c9..07ae6a574d 100644
--- a/client/src/test/java/org/asynchttpclient/AsyncHttpClientDefaultsTest.java
+++ b/client/src/test/java/org/asynchttpclient/AsyncHttpClientDefaultsTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient;
import static org.asynchttpclient.config.AsyncHttpClientConfigDefaults.ASYNC_CLIENT_CONFIG_ROOT;
diff --git a/client/src/test/java/org/asynchttpclient/PostRedirectGetTest.java b/client/src/test/java/org/asynchttpclient/PostRedirectGetTest.java
index 2e01e28549..bc414b1405 100644
--- a/client/src/test/java/org/asynchttpclient/PostRedirectGetTest.java
+++ b/client/src/test/java/org/asynchttpclient/PostRedirectGetTest.java
@@ -10,7 +10,6 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-
package org.asynchttpclient;
import static org.asynchttpclient.Dsl.*;
diff --git a/client/src/test/java/org/asynchttpclient/RC10KTest.java b/client/src/test/java/org/asynchttpclient/RC1KTest.java
similarity index 94%
rename from client/src/test/java/org/asynchttpclient/RC10KTest.java
rename to client/src/test/java/org/asynchttpclient/RC1KTest.java
index e0d0fe6024..848b37e97a 100644
--- a/client/src/test/java/org/asynchttpclient/RC10KTest.java
+++ b/client/src/test/java/org/asynchttpclient/RC1KTest.java
@@ -40,12 +40,12 @@
import org.testng.annotations.Test;
/**
- * Reverse C10K Problem test.
+ * Reverse C1K Problem test.
*
* @author Hubert Iwaniuk
*/
-public class RC10KTest extends AbstractBasicTest {
- private static final int C10K = 1000;
+public class RC1KTest extends AbstractBasicTest {
+ private static final int C1K = 1000;
private static final String ARG_HEADER = "Arg";
private static final int SRV_COUNT = 10;
protected Server[] servers = new Server[SRV_COUNT];
@@ -89,10 +89,10 @@ public void handle(String s, Request r, HttpServletRequest req, HttpServletRespo
@Test(timeOut = 10 * 60 * 1000, groups = "scalability")
public void rc10kProblem() throws IOException, ExecutionException, TimeoutException, InterruptedException {
- try (AsyncHttpClient ahc = asyncHttpClient(config().setMaxConnectionsPerHost(C10K).setKeepAlive(true))) {
- List> resps = new ArrayList<>(C10K);
+ try (AsyncHttpClient ahc = asyncHttpClient(config().setMaxConnectionsPerHost(C1K).setKeepAlive(true))) {
+ List> resps = new ArrayList<>(C1K);
int i = 0;
- while (i < C10K) {
+ while (i < C1K) {
resps.add(ahc.prepareGet(String.format("http://localhost:%d/%d", ports[i % SRV_COUNT], i)).execute(new MyAsyncHandler(i++)));
}
i = 0;
diff --git a/client/src/test/java/org/asynchttpclient/RedirectBodyTest.java b/client/src/test/java/org/asynchttpclient/RedirectBodyTest.java
index d406748bb5..8de3d2b98d 100644
--- a/client/src/test/java/org/asynchttpclient/RedirectBodyTest.java
+++ b/client/src/test/java/org/asynchttpclient/RedirectBodyTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient;
import static org.asynchttpclient.Dsl.*;
diff --git a/client/src/test/java/org/asynchttpclient/handler/resumable/MapResumableProcessor.java b/client/src/test/java/org/asynchttpclient/handler/resumable/MapResumableProcessor.java
index 1f43328b5b..fdb120d884 100644
--- a/client/src/test/java/org/asynchttpclient/handler/resumable/MapResumableProcessor.java
+++ b/client/src/test/java/org/asynchttpclient/handler/resumable/MapResumableProcessor.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.handler.resumable;
import org.asynchttpclient.handler.resumable.ResumableAsyncHandler.ResumableProcessor;
diff --git a/client/src/test/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcesserTest.java b/client/src/test/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcesserTest.java
index 6f5bbb33d6..9935a853e9 100644
--- a/client/src/test/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcesserTest.java
+++ b/client/src/test/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcesserTest.java
@@ -1,5 +1,3 @@
-package org.asynchttpclient.handler.resumable;
-
/*
* Copyright (c) 2010 Sonatype, Inc. All rights reserved.
*
@@ -12,6 +10,7 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
+package org.asynchttpclient.handler.resumable;
import static org.testng.Assert.assertEquals;
diff --git a/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandlerTest.java b/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandlerTest.java
index 9da7024cfc..2fa7e402ed 100644
--- a/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandlerTest.java
+++ b/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandlerTest.java
@@ -1,5 +1,3 @@
-package org.asynchttpclient.handler.resumable;
-
/*
* Copyright (c) 2010 Sonatype, Inc. All rights reserved.
*
@@ -12,6 +10,7 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
+package org.asynchttpclient.handler.resumable;
import static org.asynchttpclient.Dsl.get;
import static org.mockito.Matchers.anyObject;
diff --git a/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListenerTest.java b/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListenerTest.java
index f064c63dd3..663143371b 100644
--- a/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListenerTest.java
+++ b/client/src/test/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListenerTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.handler.resumable;
import static org.mockito.Mockito.*;
diff --git a/client/src/test/java/org/asynchttpclient/netty/EventPipelineTest.java b/client/src/test/java/org/asynchttpclient/netty/EventPipelineTest.java
index 5fb91a02f2..ac51e2a23d 100644
--- a/client/src/test/java/org/asynchttpclient/netty/EventPipelineTest.java
+++ b/client/src/test/java/org/asynchttpclient/netty/EventPipelineTest.java
@@ -10,7 +10,6 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-
package org.asynchttpclient.netty;
import static org.asynchttpclient.Dsl.*;
diff --git a/client/src/test/java/org/asynchttpclient/netty/NettyAsyncResponseTest.java b/client/src/test/java/org/asynchttpclient/netty/NettyAsyncResponseTest.java
index 646a8326c6..9d02fca7af 100644
--- a/client/src/test/java/org/asynchttpclient/netty/NettyAsyncResponseTest.java
+++ b/client/src/test/java/org/asynchttpclient/netty/NettyAsyncResponseTest.java
@@ -10,7 +10,6 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-
package org.asynchttpclient.netty;
import static org.testng.Assert.*;
diff --git a/client/src/test/java/org/asynchttpclient/netty/NettyResponseFutureTest.java b/client/src/test/java/org/asynchttpclient/netty/NettyResponseFutureTest.java
index 748b104582..6ef118c7d6 100644
--- a/client/src/test/java/org/asynchttpclient/netty/NettyResponseFutureTest.java
+++ b/client/src/test/java/org/asynchttpclient/netty/NettyResponseFutureTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.netty;
import static org.testng.Assert.*;
diff --git a/client/src/test/java/org/asynchttpclient/reactivestreams/ReactiveStreamsDownLoadTest.java b/client/src/test/java/org/asynchttpclient/reactivestreams/ReactiveStreamsDownLoadTest.java
index 78f9900f79..1d92babfba 100644
--- a/client/src/test/java/org/asynchttpclient/reactivestreams/ReactiveStreamsDownLoadTest.java
+++ b/client/src/test/java/org/asynchttpclient/reactivestreams/ReactiveStreamsDownLoadTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.reactivestreams;
import java.io.ByteArrayOutputStream;
diff --git a/client/src/test/java/org/asynchttpclient/request/body/generators/ByteArrayBodyGeneratorTest.java b/client/src/test/java/org/asynchttpclient/request/body/generators/ByteArrayBodyGeneratorTest.java
index 052c2d847d..5826215b63 100644
--- a/client/src/test/java/org/asynchttpclient/request/body/generators/ByteArrayBodyGeneratorTest.java
+++ b/client/src/test/java/org/asynchttpclient/request/body/generators/ByteArrayBodyGeneratorTest.java
@@ -10,7 +10,6 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
-
package org.asynchttpclient.request.body.generators;
import static org.testng.Assert.assertEquals;
diff --git a/client/src/test/java/org/asynchttpclient/request/body/multipart/part/MultipartPartTest.java b/client/src/test/java/org/asynchttpclient/request/body/multipart/part/MultipartPartTest.java
index 24411f3c2a..b7b9890ce4 100644
--- a/client/src/test/java/org/asynchttpclient/request/body/multipart/part/MultipartPartTest.java
+++ b/client/src/test/java/org/asynchttpclient/request/body/multipart/part/MultipartPartTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.request.body.multipart.part;
import static java.nio.charset.StandardCharsets.UTF_8;
diff --git a/client/src/test/java/org/asynchttpclient/test/EchoHandler.java b/client/src/test/java/org/asynchttpclient/test/EchoHandler.java
index dd024ec3ae..ec707ad334 100644
--- a/client/src/test/java/org/asynchttpclient/test/EchoHandler.java
+++ b/client/src/test/java/org/asynchttpclient/test/EchoHandler.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.test;
import org.eclipse.jetty.server.Request;
diff --git a/client/src/test/java/org/asynchttpclient/test/TestUtils.java b/client/src/test/java/org/asynchttpclient/test/TestUtils.java
index 5d0bff9538..9a5fc201b4 100644
--- a/client/src/test/java/org/asynchttpclient/test/TestUtils.java
+++ b/client/src/test/java/org/asynchttpclient/test/TestUtils.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.test;
import static java.nio.charset.StandardCharsets.UTF_8;
diff --git a/client/src/test/java/org/asynchttpclient/uri/UriParserTest.java b/client/src/test/java/org/asynchttpclient/uri/UriParserTest.java
index 69ea3d8776..2f33996262 100644
--- a/client/src/test/java/org/asynchttpclient/uri/UriParserTest.java
+++ b/client/src/test/java/org/asynchttpclient/uri/UriParserTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.uri;
import static org.testng.Assert.*;
diff --git a/client/src/test/java/org/asynchttpclient/util/HttpUtilsTest.java b/client/src/test/java/org/asynchttpclient/util/HttpUtilsTest.java
index d5afd7937d..cf88947da1 100644
--- a/client/src/test/java/org/asynchttpclient/util/HttpUtilsTest.java
+++ b/client/src/test/java/org/asynchttpclient/util/HttpUtilsTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.util;
import static org.testng.Assert.*;
diff --git a/client/src/test/java/org/asynchttpclient/ws/EchoSocket.java b/client/src/test/java/org/asynchttpclient/ws/EchoSocket.java
index dcb7d75ea6..e239e2a64d 100644
--- a/client/src/test/java/org/asynchttpclient/ws/EchoSocket.java
+++ b/client/src/test/java/org/asynchttpclient/ws/EchoSocket.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2015 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.ws;
import org.eclipse.jetty.websocket.api.Session;
From b641b46db4f01fdbbce2fe6d544cca4b4b27b3b5 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 5 Nov 2016 10:38:46 +0100
Subject: [PATCH 080/901] Fix TestNG actual/expected
---
client/src/test/java/org/asynchttpclient/RealmTest.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/src/test/java/org/asynchttpclient/RealmTest.java b/client/src/test/java/org/asynchttpclient/RealmTest.java
index 168410af17..c72b6615a6 100644
--- a/client/src/test/java/org/asynchttpclient/RealmTest.java
+++ b/client/src/test/java/org/asynchttpclient/RealmTest.java
@@ -71,7 +71,7 @@ private void testOldDigest(String qop) {
String ha2 = getMd5(method + ":" + uri.getPath());
String expectedResponse = getMd5(ha1 + ":" + nonce + ":" + ha2);
- assertEquals(expectedResponse, orig.getResponse());
+ assertEquals(orig.getResponse(), expectedResponse);
}
@Test(groups = "standalone")
@@ -96,7 +96,7 @@ public void testStrongDigest() {
String ha2 = getMd5(method + ":" + uri.getPath());
String expectedResponse = getMd5(ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2);
- assertEquals(expectedResponse, orig.getResponse());
+ assertEquals(orig.getResponse(), expectedResponse);
}
private String getMd5(String what) {
From cd6caa10e7fe5bdfc8f7df3e4cafab809bd1e947 Mon Sep 17 00:00:00 2001
From: Grenville Wilson
Date: Mon, 31 Oct 2016 16:43:17 -0400
Subject: [PATCH 081/901] PR comments addressed, tests fixed
---
.../org/asynchttpclient/AsyncHttpClient.java | 7 +
.../java/org/asynchttpclient/ClientStats.java | 78 ++++++++
.../DefaultAsyncHttpClient.java | 5 +
.../asynchttpclient/channel/ChannelPool.java | 5 +
.../channel/NoopChannelPool.java | 7 +
.../netty/channel/ChannelManager.java | 8 +
.../netty/channel/DefaultChannelPool.java | 10 ++
.../org/asynchttpclient/ClientStatsTest.java | 169 ++++++++++++++++++
.../org/asynchttpclient/test/EchoHandler.java | 3 +-
.../extras/registry/BadAsyncHttpClient.java | 5 +
.../extras/registry/TestAsyncHttpClient.java | 4 +
11 files changed, 300 insertions(+), 1 deletion(-)
create mode 100644 client/src/main/java/org/asynchttpclient/ClientStats.java
create mode 100644 client/src/test/java/org/asynchttpclient/ClientStatsTest.java
diff --git a/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java b/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java
index 784f65b89d..c21cd59af1 100755
--- a/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java
+++ b/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java
@@ -266,4 +266,11 @@ public interface AsyncHttpClient extends Closeable {
* @return a {@link Future} of type Response
*/
ListenableFuture executeRequest(RequestBuilder requestBuilder);
+
+ /***
+ * Return details about pooled connections.
+ *
+ * @return a {@link ClientStats}
+ */
+ ClientStats getClientStats();
}
diff --git a/client/src/main/java/org/asynchttpclient/ClientStats.java b/client/src/main/java/org/asynchttpclient/ClientStats.java
new file mode 100644
index 0000000000..625c19aa5e
--- /dev/null
+++ b/client/src/main/java/org/asynchttpclient/ClientStats.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2010 Ning, Inc.
+ *
+ * This program is licensed 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.asynchttpclient;
+
+import java.util.Objects;
+
+/**
+ * A record class representing the state of an (@link org.asynchttpclient.AsyncHttpClient)
+ */
+public class ClientStats {
+
+ private final long activeConnectionCount;
+ private final long idleConnectionCount;
+
+ public ClientStats(final long activeConnectionCount,
+ final long idleConnectionCount) {
+ this.activeConnectionCount = activeConnectionCount;
+ this.idleConnectionCount = idleConnectionCount;
+ }
+
+ /**
+ * @return The sum of {@link #getActiveConnectionCount()} and {@link #getIdleConnectionCount()},
+ * a long representing the total number of connections in the connection pool.
+ */
+ public long getTotalConnectionCount() {
+ return activeConnectionCount + idleConnectionCount;
+ }
+
+ /**
+ * @return A long representing the number of active connection in the connection pool.
+ */
+ public long getActiveConnectionCount() {
+ return activeConnectionCount;
+ }
+
+ /**
+ *
+ * @return A long representing the number of idle connections in the connection pool.
+ */
+ public long getIdleConnectionCount() {
+ return idleConnectionCount;
+ }
+
+ @Override
+ public String toString() {
+ return "There are " + getTotalConnectionCount() +
+ " total connections, " + getActiveConnectionCount() +
+ " are active and " + getIdleConnectionCount() + " are idle.";
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ final ClientStats that = (ClientStats) o;
+ return activeConnectionCount == that.activeConnectionCount &&
+ idleConnectionCount == that.idleConnectionCount;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(activeConnectionCount, idleConnectionCount);
+ }
+}
diff --git a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
index db884e55ad..74fd6d26ab 100644
--- a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
+++ b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
@@ -255,6 +255,11 @@ public EventLoopGroup getEventLoopGroup() {
return channelManager.getEventLoopGroup();
}
+ @Override
+ public ClientStats getClientStats() {
+ return channelManager.getClientStats();
+ }
+
protected BoundRequestBuilder requestBuilder(String method, String url) {
return new BoundRequestBuilder(this, method, config.isDisableUrlEncodingForBoundRequests()).setUrl(url).setSignatureCalculator(signatureCalculator);
}
diff --git a/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java b/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java
index f8cea67fe6..15c43844ed 100755
--- a/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java
@@ -70,4 +70,9 @@ public interface ChannelPool {
* @param selector the selector
*/
void flushPartitions(ChannelPoolPartitionSelector selector);
+
+ /**
+ * @return The number of idle channels.
+ */
+ long getIdleChannelCount();
}
diff --git a/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java b/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
index f5b59fab6a..c48e48787a 100644
--- a/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
@@ -50,4 +50,11 @@ public void flushPartition(Object partitionKey) {
@Override
public void flushPartitions(ChannelPoolPartitionSelector selector) {
}
+
+ @Override
+ public long getIdleChannelCount() {
+ return 0;
+ }
+
+
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
index bdd559ef44..fa0fbfa03e 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
@@ -51,6 +51,7 @@
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHttpClientConfig;
+import org.asynchttpclient.ClientStats;
import org.asynchttpclient.SslEngineFactory;
import org.asynchttpclient.channel.ChannelPool;
import org.asynchttpclient.channel.ChannelPoolPartitioning;
@@ -488,4 +489,11 @@ public ChannelPool getChannelPool() {
public EventLoopGroup getEventLoopGroup() {
return eventLoopGroup;
}
+
+ public ClientStats getClientStats() {
+ final long totalConnectionCount = openChannels.size();
+ final long idleConnectionCount = channelPool.getIdleChannelCount();
+ final long activeConnectionCount = totalConnectionCount - idleConnectionCount;
+ return new ClientStats(activeConnectionCount, idleConnectionCount);
+ }
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
index 878db3a290..6d21e7c079 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
@@ -356,6 +356,16 @@ public void flushPartitions(ChannelPoolPartitionSelector selector) {
}
}
+ @Override
+ public long getIdleChannelCount() {
+ return partitions.reduceValuesToLong(
+ Long.MAX_VALUE,
+ ConcurrentLinkedDeque::size,
+ 0,
+ (left, right) -> left + right
+ );
+ }
+
public enum PoolLeaseStrategy {
LIFO {
public E lease(Deque d) {
diff --git a/client/src/test/java/org/asynchttpclient/ClientStatsTest.java b/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
new file mode 100644
index 0000000000..f7606eb627
--- /dev/null
+++ b/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
@@ -0,0 +1,169 @@
+package org.asynchttpclient;
+
+import static org.asynchttpclient.Dsl.asyncHttpClient;
+import static org.asynchttpclient.Dsl.config;
+import static org.testng.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.testng.annotations.Test;
+
+/**
+ * Created by grenville on 9/25/16.
+ */
+public class ClientStatsTest extends AbstractBasicTest {
+
+ @Test(groups = "standalone")
+ public void testClientStatus() throws Throwable {
+ try (final DefaultAsyncHttpClient client = (DefaultAsyncHttpClient) asyncHttpClient(config().setKeepAlive(true).setPooledConnectionIdleTimeout(5000))) {
+ final String url = getTargetUrl();
+
+ final ClientStats emptyStats = client.getClientStats();
+
+ assertEquals(emptyStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
+ assertEquals(emptyStats.getActiveConnectionCount(), 0);
+ assertEquals(emptyStats.getIdleConnectionCount(), 0);
+ assertEquals(emptyStats.getTotalConnectionCount(), 0);
+
+ final List> futures = new ArrayList<>();
+ for (int i = 0; i < 5; i++) {
+ logger.info("{} requesting url [{}]...", i, url);
+ futures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
+ }
+
+ Thread.sleep(2000);
+
+ final ClientStats activeStats = client.getClientStats();
+
+ assertEquals(activeStats.toString(), "There are 5 total connections, 5 are active and 0 are idle.");
+ assertEquals(activeStats.getActiveConnectionCount(), 5);
+ assertEquals(activeStats.getIdleConnectionCount(), 0);
+ assertEquals(activeStats.getTotalConnectionCount(), 5);
+
+ for (final ListenableFuture future : futures) {
+ future.get();
+ }
+
+ Thread.sleep(1000);
+
+ final ClientStats idleStats = client.getClientStats();
+
+ assertEquals(idleStats.toString(), "There are 5 total connections, 0 are active and 5 are idle.");
+ assertEquals(idleStats.getActiveConnectionCount(), 0);
+ assertEquals(idleStats.getIdleConnectionCount(), 5);
+ assertEquals(idleStats.getTotalConnectionCount(), 5);
+
+ // Let's make sure the active count is correct when reusing cached connections.
+
+ final List> repeatedFutures = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ logger.info("{} requesting url [{}]...", i, url);
+ repeatedFutures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
+ }
+
+ Thread.sleep(2000);
+
+ final ClientStats activeCachedStats = client.getClientStats();
+
+ assertEquals(activeCachedStats.toString(), "There are 5 total connections, 3 are active and 2 are idle.");
+ assertEquals(activeCachedStats.getActiveConnectionCount(), 3);
+ assertEquals(activeCachedStats.getIdleConnectionCount(), 2);
+ assertEquals(activeCachedStats.getTotalConnectionCount(), 5);
+
+ for (final ListenableFuture future : repeatedFutures) {
+ future.get();
+ }
+
+ Thread.sleep(1000);
+
+ final ClientStats idleCachedStats = client.getClientStats();
+
+ assertEquals(idleCachedStats.toString(), "There are 3 total connections, 0 are active and 3 are idle.");
+ assertEquals(idleCachedStats.getActiveConnectionCount(), 0);
+ assertEquals(idleCachedStats.getIdleConnectionCount(), 3);
+ assertEquals(idleCachedStats.getTotalConnectionCount(), 3);
+
+ Thread.sleep(5000);
+
+ final ClientStats timeoutStats = client.getClientStats();
+
+ assertEquals(timeoutStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
+ assertEquals(timeoutStats.getActiveConnectionCount(), 0);
+ assertEquals(timeoutStats.getIdleConnectionCount(), 0);
+ assertEquals(timeoutStats.getTotalConnectionCount(), 0);
+ }
+ }
+
+ @Test(groups = "standalone")
+ public void testClientStatusNoKeepalive() throws Throwable {
+ try (final DefaultAsyncHttpClient client = (DefaultAsyncHttpClient) asyncHttpClient(config().setKeepAlive(false))) {
+ final String url = getTargetUrl();
+
+ final ClientStats emptyStats = client.getClientStats();
+
+ assertEquals(emptyStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
+ assertEquals(emptyStats.getActiveConnectionCount(), 0);
+ assertEquals(emptyStats.getIdleConnectionCount(), 0);
+ assertEquals(emptyStats.getTotalConnectionCount(), 0);
+
+ final List> futures = new ArrayList<>();
+ for (int i = 0; i < 5; i++) {
+ logger.info("{} requesting url [{}]...", i, url);
+ futures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
+ }
+
+ Thread.sleep(2000);
+
+ final ClientStats activeStats = client.getClientStats();
+
+ assertEquals(activeStats.toString(), "There are 5 total connections, 5 are active and 0 are idle.");
+ assertEquals(activeStats.getActiveConnectionCount(), 5);
+ assertEquals(activeStats.getIdleConnectionCount(), 0);
+ assertEquals(activeStats.getTotalConnectionCount(), 5);
+
+ for (final ListenableFuture future : futures) {
+ future.get();
+ }
+
+ Thread.sleep(1000);
+
+ final ClientStats idleStats = client.getClientStats();
+
+ assertEquals(idleStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
+ assertEquals(idleStats.getActiveConnectionCount(), 0);
+ assertEquals(idleStats.getIdleConnectionCount(), 0);
+ assertEquals(idleStats.getTotalConnectionCount(), 0);
+
+ // Let's make sure the active count is correct when reusing cached connections.
+
+ final List> repeatedFutures = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ logger.info("{} requesting url [{}]...", i, url);
+ repeatedFutures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
+ }
+
+ Thread.sleep(2000);
+
+ final ClientStats activeCachedStats = client.getClientStats();
+
+ assertEquals(activeCachedStats.toString(), "There are 3 total connections, 3 are active and 0 are idle.");
+ assertEquals(activeCachedStats.getActiveConnectionCount(), 3);
+ assertEquals(activeCachedStats.getIdleConnectionCount(), 0);
+ assertEquals(activeCachedStats.getTotalConnectionCount(), 3);
+
+ for (final ListenableFuture future : repeatedFutures) {
+ future.get();
+ }
+
+ Thread.sleep(1000);
+
+ final ClientStats idleCachedStats = client.getClientStats();
+
+ assertEquals(idleCachedStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
+ assertEquals(idleCachedStats.getActiveConnectionCount(), 0);
+ assertEquals(idleCachedStats.getIdleConnectionCount(), 0);
+ assertEquals(idleCachedStats.getTotalConnectionCount(), 0);
+ }
+ }
+}
diff --git a/client/src/test/java/org/asynchttpclient/test/EchoHandler.java b/client/src/test/java/org/asynchttpclient/test/EchoHandler.java
index ec707ad334..71bb57561c 100644
--- a/client/src/test/java/org/asynchttpclient/test/EchoHandler.java
+++ b/client/src/test/java/org/asynchttpclient/test/EchoHandler.java
@@ -55,8 +55,9 @@ public void handle(String pathInContext, Request request, HttpServletRequest htt
param = e.nextElement().toString();
if (param.startsWith("LockThread")) {
+ final int sleepTime = httpRequest.getIntHeader(param);
try {
- Thread.sleep(40 * 1000);
+ Thread.sleep(sleepTime == -1 ? 40 : sleepTime * 1000);
} catch (InterruptedException ex) {
}
}
diff --git a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
index 41c083fe51..568fb073c5 100644
--- a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
+++ b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
@@ -125,4 +125,9 @@ public ListenableFuture executeRequest(RequestBuilder requestBuilder, Asy
public ListenableFuture executeRequest(RequestBuilder requestBuilder) {
return null;
}
+
+ @Override
+ public ClientStats getClientStats() {
+ return null;
+ }
}
diff --git a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
index febee33bc3..d9e4fec592 100644
--- a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
+++ b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
@@ -122,4 +122,8 @@ public ListenableFuture executeRequest(RequestBuilder requestBuilder)
return null;
}
+ @Override
+ public ClientStats getClientStats() {
+ return null;
+ }
}
From 81cb9baad7f1c06608af09d64dddb91f1a50c872 Mon Sep 17 00:00:00 2001
From: Grenville Wilson
Date: Mon, 31 Oct 2016 16:58:37 -0400
Subject: [PATCH 082/901] Got a little overeager with reverting my import
changes
---
.../org/asynchttpclient/extras/registry/BadAsyncHttpClient.java | 1 +
.../org/asynchttpclient/extras/registry/TestAsyncHttpClient.java | 1 +
2 files changed, 2 insertions(+)
diff --git a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
index 568fb073c5..b69893d6ad 100644
--- a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
+++ b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
@@ -15,6 +15,7 @@
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.BoundRequestBuilder;
+import org.asynchttpclient.ClientStats;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Request;
diff --git a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
index d9e4fec592..7c5a0ca1fc 100644
--- a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
+++ b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
@@ -15,6 +15,7 @@
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.BoundRequestBuilder;
+import org.asynchttpclient.ClientStats;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Request;
From 552e4cd2e9359228ec5f9390cc2bbf64ee957eb0 Mon Sep 17 00:00:00 2001
From: Grenville Wilson
Date: Wed, 2 Nov 2016 21:08:31 -0400
Subject: [PATCH 083/901] Small tweaks and changes in response to PR comments
---
.../java/org/asynchttpclient/ClientStats.java | 25 +++----
.../channel/NoopChannelPool.java | 2 -
.../netty/channel/DefaultChannelPool.java | 7 +-
.../org/asynchttpclient/ClientStatsTest.java | 72 ++++++++++---------
.../extras/registry/BadAsyncHttpClient.java | 2 +-
.../extras/registry/TestAsyncHttpClient.java | 2 +-
6 files changed, 52 insertions(+), 58 deletions(-)
diff --git a/client/src/main/java/org/asynchttpclient/ClientStats.java b/client/src/main/java/org/asynchttpclient/ClientStats.java
index 625c19aa5e..ab4f931f1f 100644
--- a/client/src/main/java/org/asynchttpclient/ClientStats.java
+++ b/client/src/main/java/org/asynchttpclient/ClientStats.java
@@ -1,18 +1,15 @@
/*
- * Copyright 2010 Ning, Inc.
+ * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
*
- * This program is licensed 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.
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
*
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient;
@@ -26,8 +23,8 @@ public class ClientStats {
private final long activeConnectionCount;
private final long idleConnectionCount;
- public ClientStats(final long activeConnectionCount,
- final long idleConnectionCount) {
+ public ClientStats(long activeConnectionCount,
+ long idleConnectionCount) {
this.activeConnectionCount = activeConnectionCount;
this.idleConnectionCount = idleConnectionCount;
}
diff --git a/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java b/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
index c48e48787a..4ba0e0e8dd 100644
--- a/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
@@ -55,6 +55,4 @@ public void flushPartitions(ChannelPoolPartitionSelector selector) {
public long getIdleChannelCount() {
return 0;
}
-
-
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
index 6d21e7c079..c27c1b0775 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
@@ -358,12 +358,7 @@ public void flushPartitions(ChannelPoolPartitionSelector selector) {
@Override
public long getIdleChannelCount() {
- return partitions.reduceValuesToLong(
- Long.MAX_VALUE,
- ConcurrentLinkedDeque::size,
- 0,
- (left, right) -> left + right
- );
+ return partitions.values().stream().mapToLong(ConcurrentLinkedDeque::size).sum();
}
public enum PoolLeaseStrategy {
diff --git a/client/src/test/java/org/asynchttpclient/ClientStatsTest.java b/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
index f7606eb627..149cf86774 100644
--- a/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
+++ b/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
@@ -1,3 +1,16 @@
+/*
+ * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient;
import static org.asynchttpclient.Dsl.asyncHttpClient;
@@ -6,6 +19,9 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.testng.annotations.Test;
@@ -16,7 +32,7 @@ public class ClientStatsTest extends AbstractBasicTest {
@Test(groups = "standalone")
public void testClientStatus() throws Throwable {
- try (final DefaultAsyncHttpClient client = (DefaultAsyncHttpClient) asyncHttpClient(config().setKeepAlive(true).setPooledConnectionIdleTimeout(5000))) {
+ try (final AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(true).setPooledConnectionIdleTimeout(5000))) {
final String url = getTargetUrl();
final ClientStats emptyStats = client.getClientStats();
@@ -26,11 +42,10 @@ public void testClientStatus() throws Throwable {
assertEquals(emptyStats.getIdleConnectionCount(), 0);
assertEquals(emptyStats.getTotalConnectionCount(), 0);
- final List> futures = new ArrayList<>();
- for (int i = 0; i < 5; i++) {
- logger.info("{} requesting url [{}]...", i, url);
- futures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
- }
+ final List> futures =
+ Stream.generate(() -> client.prepareGet(url).setHeader("LockThread","6").execute())
+ .limit(5)
+ .collect(Collectors.toList());
Thread.sleep(2000);
@@ -41,9 +56,7 @@ public void testClientStatus() throws Throwable {
assertEquals(activeStats.getIdleConnectionCount(), 0);
assertEquals(activeStats.getTotalConnectionCount(), 5);
- for (final ListenableFuture future : futures) {
- future.get();
- }
+ futures.forEach(future -> future.toCompletableFuture().join());
Thread.sleep(1000);
@@ -56,11 +69,10 @@ public void testClientStatus() throws Throwable {
// Let's make sure the active count is correct when reusing cached connections.
- final List> repeatedFutures = new ArrayList<>();
- for (int i = 0; i < 3; i++) {
- logger.info("{} requesting url [{}]...", i, url);
- repeatedFutures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
- }
+ final List> repeatedFutures =
+ Stream.generate(() -> client.prepareGet(url).setHeader("LockThread","6").execute())
+ .limit(3)
+ .collect(Collectors.toList());
Thread.sleep(2000);
@@ -71,9 +83,7 @@ public void testClientStatus() throws Throwable {
assertEquals(activeCachedStats.getIdleConnectionCount(), 2);
assertEquals(activeCachedStats.getTotalConnectionCount(), 5);
- for (final ListenableFuture future : repeatedFutures) {
- future.get();
- }
+ repeatedFutures.forEach(future -> future.toCompletableFuture().join());
Thread.sleep(1000);
@@ -97,7 +107,7 @@ public void testClientStatus() throws Throwable {
@Test(groups = "standalone")
public void testClientStatusNoKeepalive() throws Throwable {
- try (final DefaultAsyncHttpClient client = (DefaultAsyncHttpClient) asyncHttpClient(config().setKeepAlive(false))) {
+ try (final AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(false))) {
final String url = getTargetUrl();
final ClientStats emptyStats = client.getClientStats();
@@ -107,11 +117,10 @@ public void testClientStatusNoKeepalive() throws Throwable {
assertEquals(emptyStats.getIdleConnectionCount(), 0);
assertEquals(emptyStats.getTotalConnectionCount(), 0);
- final List> futures = new ArrayList<>();
- for (int i = 0; i < 5; i++) {
- logger.info("{} requesting url [{}]...", i, url);
- futures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
- }
+ final List> futures =
+ Stream.generate(() -> client.prepareGet(url).setHeader("LockThread","6").execute())
+ .limit(5)
+ .collect(Collectors.toList());
Thread.sleep(2000);
@@ -122,9 +131,7 @@ public void testClientStatusNoKeepalive() throws Throwable {
assertEquals(activeStats.getIdleConnectionCount(), 0);
assertEquals(activeStats.getTotalConnectionCount(), 5);
- for (final ListenableFuture future : futures) {
- future.get();
- }
+ futures.forEach(future -> future.toCompletableFuture().join());
Thread.sleep(1000);
@@ -137,11 +144,10 @@ public void testClientStatusNoKeepalive() throws Throwable {
// Let's make sure the active count is correct when reusing cached connections.
- final List> repeatedFutures = new ArrayList<>();
- for (int i = 0; i < 3; i++) {
- logger.info("{} requesting url [{}]...", i, url);
- repeatedFutures.add(client.prepareGet(url).setHeader("LockThread", "6").execute());
- }
+ final List> repeatedFutures =
+ Stream.generate(() -> client.prepareGet(url).setHeader("LockThread","6").execute())
+ .limit(3)
+ .collect(Collectors.toList());
Thread.sleep(2000);
@@ -152,9 +158,7 @@ public void testClientStatusNoKeepalive() throws Throwable {
assertEquals(activeCachedStats.getIdleConnectionCount(), 0);
assertEquals(activeCachedStats.getTotalConnectionCount(), 3);
- for (final ListenableFuture future : repeatedFutures) {
- future.get();
- }
+ repeatedFutures.forEach(future -> future.toCompletableFuture().join());
Thread.sleep(1000);
diff --git a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
index b69893d6ad..05ecd3f779 100644
--- a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
+++ b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/BadAsyncHttpClient.java
@@ -129,6 +129,6 @@ public ListenableFuture executeRequest(RequestBuilder requestBuilder)
@Override
public ClientStats getClientStats() {
- return null;
+ throw new UnsupportedOperationException();
}
}
diff --git a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
index 7c5a0ca1fc..fc2d5eae94 100644
--- a/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
+++ b/extras/registry/src/test/java/org/asynchttpclient/extras/registry/TestAsyncHttpClient.java
@@ -125,6 +125,6 @@ public ListenableFuture executeRequest(RequestBuilder requestBuilder)
@Override
public ClientStats getClientStats() {
- return null;
+ throw new UnsupportedOperationException();
}
}
From 5f7089ec851c5ce27ea85e143c02cfc2c0ea92e0 Mon Sep 17 00:00:00 2001
From: Grenville Wilson
Date: Sun, 6 Nov 2016 00:19:10 -0400
Subject: [PATCH 084/901] Adding per-host statistics
---
.../java/org/asynchttpclient/ClientStats.java | 57 +++++++++-----
.../java/org/asynchttpclient/HostStats.java | 74 +++++++++++++++++++
.../asynchttpclient/channel/ChannelPool.java | 6 +-
.../channel/NoopChannelPool.java | 7 +-
.../netty/channel/ChannelManager.java | 37 ++++++++--
.../netty/channel/DefaultChannelPool.java | 19 ++++-
.../org/asynchttpclient/ClientStatsTest.java | 60 +++++++++------
7 files changed, 202 insertions(+), 58 deletions(-)
create mode 100644 client/src/main/java/org/asynchttpclient/HostStats.java
diff --git a/client/src/main/java/org/asynchttpclient/ClientStats.java b/client/src/main/java/org/asynchttpclient/ClientStats.java
index ab4f931f1f..4bafd7b4c1 100644
--- a/client/src/main/java/org/asynchttpclient/ClientStats.java
+++ b/client/src/main/java/org/asynchttpclient/ClientStats.java
@@ -13,50 +13,68 @@
*/
package org.asynchttpclient;
+import java.util.Collections;
+import java.util.Map;
import java.util.Objects;
/**
- * A record class representing the state of an (@link org.asynchttpclient.AsyncHttpClient)
+ * A record class representing the state of an (@link org.asynchttpclient.AsyncHttpClient).
*/
public class ClientStats {
- private final long activeConnectionCount;
- private final long idleConnectionCount;
+ private final Map statsPerHost;
- public ClientStats(long activeConnectionCount,
- long idleConnectionCount) {
- this.activeConnectionCount = activeConnectionCount;
- this.idleConnectionCount = idleConnectionCount;
+ public ClientStats(Map statsPerHost) {
+ this.statsPerHost = Collections.unmodifiableMap(statsPerHost);
}
/**
- * @return The sum of {@link #getActiveConnectionCount()} and {@link #getIdleConnectionCount()},
+ * @return A map from hostname to statistics on that host's connections.
+ * The returned map is an {@link java.util.Collections.UnmodifiableMap}.
+ */
+ public Map getStatsPerHost() {
+ return statsPerHost;
+ }
+
+ /**
+ * @return The sum of {@link #getTotalActiveConnectionCount()} and {@link #getTotalIdleConnectionCount()},
* a long representing the total number of connections in the connection pool.
*/
public long getTotalConnectionCount() {
- return activeConnectionCount + idleConnectionCount;
+ return statsPerHost
+ .values()
+ .stream()
+ .mapToLong(HostStats::getHostConnectionCount)
+ .sum();
}
/**
- * @return A long representing the number of active connection in the connection pool.
+ * @return A long representing the number of active connections in the connection pool.
*/
- public long getActiveConnectionCount() {
- return activeConnectionCount;
+ public long getTotalActiveConnectionCount() {
+ return statsPerHost
+ .values()
+ .stream()
+ .mapToLong(HostStats::getHostActiveConnectionCount)
+ .sum();
}
/**
- *
* @return A long representing the number of idle connections in the connection pool.
*/
- public long getIdleConnectionCount() {
- return idleConnectionCount;
+ public long getTotalIdleConnectionCount() {
+ return statsPerHost
+ .values()
+ .stream()
+ .mapToLong(HostStats::getHostIdleConnectionCount)
+ .sum();
}
@Override
public String toString() {
return "There are " + getTotalConnectionCount() +
- " total connections, " + getActiveConnectionCount() +
- " are active and " + getIdleConnectionCount() + " are idle.";
+ " total connections, " + getTotalActiveConnectionCount() +
+ " are active and " + getTotalIdleConnectionCount() + " are idle.";
}
@Override
@@ -64,12 +82,11 @@ public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final ClientStats that = (ClientStats) o;
- return activeConnectionCount == that.activeConnectionCount &&
- idleConnectionCount == that.idleConnectionCount;
+ return Objects.equals(statsPerHost, that.statsPerHost);
}
@Override
public int hashCode() {
- return Objects.hash(activeConnectionCount, idleConnectionCount);
+ return Objects.hashCode(statsPerHost);
}
}
diff --git a/client/src/main/java/org/asynchttpclient/HostStats.java b/client/src/main/java/org/asynchttpclient/HostStats.java
new file mode 100644
index 0000000000..87d9278820
--- /dev/null
+++ b/client/src/main/java/org/asynchttpclient/HostStats.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
+package org.asynchttpclient;
+
+import java.util.Objects;
+
+/**
+ * A record class representing the status of connections to some host.
+ */
+public class HostStats {
+
+ private final long activeConnectionCount;
+ private final long idleConnectionCount;
+
+ public HostStats(long activeConnectionCount,
+ long idleConnectionCount) {
+ this.activeConnectionCount = activeConnectionCount;
+ this.idleConnectionCount = idleConnectionCount;
+ }
+
+ /**
+ * @return The sum of {@link #getHostActiveConnectionCount()} and {@link #getHostIdleConnectionCount()},
+ * a long representing the total number of connections to this host.
+ */
+ public long getHostConnectionCount() {
+ return activeConnectionCount + idleConnectionCount;
+ }
+
+ /**
+ * @return A long representing the number of active connections to the host.
+ */
+ public long getHostActiveConnectionCount() {
+ return activeConnectionCount;
+ }
+
+ /**
+ * @return A long representing the number of idle connections in the connection pool.
+ */
+ public long getHostIdleConnectionCount() {
+ return idleConnectionCount;
+ }
+
+ @Override
+ public String toString() {
+ return "There are " + getHostConnectionCount() +
+ " total connections, " + getHostActiveConnectionCount() +
+ " are active and " + getHostIdleConnectionCount() + " are idle.";
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ final HostStats hostStats = (HostStats) o;
+ return activeConnectionCount == hostStats.activeConnectionCount &&
+ idleConnectionCount == hostStats.idleConnectionCount;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(activeConnectionCount, idleConnectionCount);
+ }
+}
diff --git a/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java b/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java
index 15c43844ed..0d20df349d 100755
--- a/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/channel/ChannelPool.java
@@ -13,6 +13,8 @@
*/
package org.asynchttpclient.channel;
+import java.util.Map;
+
import io.netty.channel.Channel;
public interface ChannelPool {
@@ -72,7 +74,7 @@ public interface ChannelPool {
void flushPartitions(ChannelPoolPartitionSelector selector);
/**
- * @return The number of idle channels.
+ * @return The number of idle channels per host.
*/
- long getIdleChannelCount();
+ Map getIdleChannelCountPerHost();
}
diff --git a/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java b/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
index 4ba0e0e8dd..30ec3875e2 100644
--- a/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/channel/NoopChannelPool.java
@@ -13,6 +13,9 @@
*/
package org.asynchttpclient.channel;
+import java.util.Collections;
+import java.util.Map;
+
import io.netty.channel.Channel;
public enum NoopChannelPool implements ChannelPool {
@@ -52,7 +55,7 @@ public void flushPartitions(ChannelPoolPartitionSelector selector) {
}
@Override
- public long getIdleChannelCount() {
- return 0;
+ public Map getIdleChannelCountPerHost() {
+ return Collections.emptyMap();
}
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
index fa0fbfa03e..8b45754559 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
@@ -40,19 +40,23 @@
import io.netty.util.concurrent.GlobalEventExecutor;
import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.OptionalLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
-import org.asynchttpclient.AsyncHandler;
-import org.asynchttpclient.AsyncHttpClientConfig;
-import org.asynchttpclient.ClientStats;
-import org.asynchttpclient.SslEngineFactory;
+import org.asynchttpclient.*;
import org.asynchttpclient.channel.ChannelPool;
import org.asynchttpclient.channel.ChannelPoolPartitioning;
import org.asynchttpclient.channel.NoopChannelPool;
@@ -491,9 +495,26 @@ public EventLoopGroup getEventLoopGroup() {
}
public ClientStats getClientStats() {
- final long totalConnectionCount = openChannels.size();
- final long idleConnectionCount = channelPool.getIdleChannelCount();
- final long activeConnectionCount = totalConnectionCount - idleConnectionCount;
- return new ClientStats(activeConnectionCount, idleConnectionCount);
+ final Map totalConnectionsPerHost = openChannels
+ .stream()
+ .map(Channel::remoteAddress)
+ .filter(a -> a.getClass() == InetSocketAddress.class)
+ .map(a -> (InetSocketAddress) a)
+ .map(InetSocketAddress::getHostName)
+ .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
+ final Map idleConnectionsPerHost = channelPool.getIdleChannelCountPerHost();
+ final Map statsPerHost = totalConnectionsPerHost
+ .entrySet()
+ .stream()
+ .collect(Collectors.toMap(
+ Entry::getKey,
+ entry -> {
+ final long totalConnectionCount = entry.getValue();
+ final long idleConnectionCount = idleConnectionsPerHost.getOrDefault(entry.getKey(), 0L);
+ final long activeConnectionCount = totalConnectionCount - idleConnectionCount;
+ return new HostStats(activeConnectionCount, idleConnectionCount);
+ }
+ ));
+ return new ClientStats(statsPerHost);
}
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
index c27c1b0775..0a8312bae1 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
@@ -21,11 +21,14 @@
import io.netty.util.Timer;
import io.netty.util.TimerTask;
+import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.stream.Collectors;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.channel.ChannelPool;
@@ -120,6 +123,10 @@ public boolean takeOwnership() {
return owned.compareAndSet(false, true);
}
+ public Channel getChannel() {
+ return channel;
+ }
+
@Override
// only depends on channel
public boolean equals(Object o) {
@@ -357,8 +364,16 @@ public void flushPartitions(ChannelPoolPartitionSelector selector) {
}
@Override
- public long getIdleChannelCount() {
- return partitions.values().stream().mapToLong(ConcurrentLinkedDeque::size).sum();
+ public Map getIdleChannelCountPerHost() {
+ return partitions
+ .values()
+ .stream()
+ .flatMap(ConcurrentLinkedDeque::stream)
+ .map(idle -> idle.getChannel().remoteAddress())
+ .filter(a -> a.getClass() == InetSocketAddress.class)
+ .map(a -> (InetSocketAddress) a)
+ .map(InetSocketAddress::getHostName)
+ .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
public enum PoolLeaseStrategy {
diff --git a/client/src/test/java/org/asynchttpclient/ClientStatsTest.java b/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
index 149cf86774..10c04d10d1 100644
--- a/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
+++ b/client/src/test/java/org/asynchttpclient/ClientStatsTest.java
@@ -16,10 +16,9 @@
import static org.asynchttpclient.Dsl.asyncHttpClient;
import static org.asynchttpclient.Dsl.config;
import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNull;
-import java.util.ArrayList;
import java.util.List;
-import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -30,6 +29,8 @@
*/
public class ClientStatsTest extends AbstractBasicTest {
+ private final static String hostname = "localhost";
+
@Test(groups = "standalone")
public void testClientStatus() throws Throwable {
try (final AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(true).setPooledConnectionIdleTimeout(5000))) {
@@ -38,9 +39,10 @@ public void testClientStatus() throws Throwable {
final ClientStats emptyStats = client.getClientStats();
assertEquals(emptyStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
- assertEquals(emptyStats.getActiveConnectionCount(), 0);
- assertEquals(emptyStats.getIdleConnectionCount(), 0);
+ assertEquals(emptyStats.getTotalActiveConnectionCount(), 0);
+ assertEquals(emptyStats.getTotalIdleConnectionCount(), 0);
assertEquals(emptyStats.getTotalConnectionCount(), 0);
+ assertNull(emptyStats.getStatsPerHost().get(hostname));
final List> futures =
Stream.generate(() -> client.prepareGet(url).setHeader("LockThread","6").execute())
@@ -52,9 +54,10 @@ public void testClientStatus() throws Throwable {
final ClientStats activeStats = client.getClientStats();
assertEquals(activeStats.toString(), "There are 5 total connections, 5 are active and 0 are idle.");
- assertEquals(activeStats.getActiveConnectionCount(), 5);
- assertEquals(activeStats.getIdleConnectionCount(), 0);
+ assertEquals(activeStats.getTotalActiveConnectionCount(), 5);
+ assertEquals(activeStats.getTotalIdleConnectionCount(), 0);
assertEquals(activeStats.getTotalConnectionCount(), 5);
+ assertEquals(activeStats.getStatsPerHost().get(hostname).getHostConnectionCount(), 5);
futures.forEach(future -> future.toCompletableFuture().join());
@@ -63,9 +66,10 @@ public void testClientStatus() throws Throwable {
final ClientStats idleStats = client.getClientStats();
assertEquals(idleStats.toString(), "There are 5 total connections, 0 are active and 5 are idle.");
- assertEquals(idleStats.getActiveConnectionCount(), 0);
- assertEquals(idleStats.getIdleConnectionCount(), 5);
+ assertEquals(idleStats.getTotalActiveConnectionCount(), 0);
+ assertEquals(idleStats.getTotalIdleConnectionCount(), 5);
assertEquals(idleStats.getTotalConnectionCount(), 5);
+ assertEquals(idleStats.getStatsPerHost().get(hostname).getHostConnectionCount(), 5);
// Let's make sure the active count is correct when reusing cached connections.
@@ -79,9 +83,10 @@ public void testClientStatus() throws Throwable {
final ClientStats activeCachedStats = client.getClientStats();
assertEquals(activeCachedStats.toString(), "There are 5 total connections, 3 are active and 2 are idle.");
- assertEquals(activeCachedStats.getActiveConnectionCount(), 3);
- assertEquals(activeCachedStats.getIdleConnectionCount(), 2);
+ assertEquals(activeCachedStats.getTotalActiveConnectionCount(), 3);
+ assertEquals(activeCachedStats.getTotalIdleConnectionCount(), 2);
assertEquals(activeCachedStats.getTotalConnectionCount(), 5);
+ assertEquals(activeCachedStats.getStatsPerHost().get(hostname).getHostConnectionCount(), 5);
repeatedFutures.forEach(future -> future.toCompletableFuture().join());
@@ -90,18 +95,20 @@ public void testClientStatus() throws Throwable {
final ClientStats idleCachedStats = client.getClientStats();
assertEquals(idleCachedStats.toString(), "There are 3 total connections, 0 are active and 3 are idle.");
- assertEquals(idleCachedStats.getActiveConnectionCount(), 0);
- assertEquals(idleCachedStats.getIdleConnectionCount(), 3);
+ assertEquals(idleCachedStats.getTotalActiveConnectionCount(), 0);
+ assertEquals(idleCachedStats.getTotalIdleConnectionCount(), 3);
assertEquals(idleCachedStats.getTotalConnectionCount(), 3);
+ assertEquals(idleCachedStats.getStatsPerHost().get(hostname).getHostConnectionCount(), 3);
Thread.sleep(5000);
final ClientStats timeoutStats = client.getClientStats();
assertEquals(timeoutStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
- assertEquals(timeoutStats.getActiveConnectionCount(), 0);
- assertEquals(timeoutStats.getIdleConnectionCount(), 0);
+ assertEquals(timeoutStats.getTotalActiveConnectionCount(), 0);
+ assertEquals(timeoutStats.getTotalIdleConnectionCount(), 0);
assertEquals(timeoutStats.getTotalConnectionCount(), 0);
+ assertNull(timeoutStats.getStatsPerHost().get(hostname));
}
}
@@ -113,9 +120,10 @@ public void testClientStatusNoKeepalive() throws Throwable {
final ClientStats emptyStats = client.getClientStats();
assertEquals(emptyStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
- assertEquals(emptyStats.getActiveConnectionCount(), 0);
- assertEquals(emptyStats.getIdleConnectionCount(), 0);
+ assertEquals(emptyStats.getTotalActiveConnectionCount(), 0);
+ assertEquals(emptyStats.getTotalIdleConnectionCount(), 0);
assertEquals(emptyStats.getTotalConnectionCount(), 0);
+ assertNull(emptyStats.getStatsPerHost().get(hostname));
final List> futures =
Stream.generate(() -> client.prepareGet(url).setHeader("LockThread","6").execute())
@@ -127,9 +135,10 @@ public void testClientStatusNoKeepalive() throws Throwable {
final ClientStats activeStats = client.getClientStats();
assertEquals(activeStats.toString(), "There are 5 total connections, 5 are active and 0 are idle.");
- assertEquals(activeStats.getActiveConnectionCount(), 5);
- assertEquals(activeStats.getIdleConnectionCount(), 0);
+ assertEquals(activeStats.getTotalActiveConnectionCount(), 5);
+ assertEquals(activeStats.getTotalIdleConnectionCount(), 0);
assertEquals(activeStats.getTotalConnectionCount(), 5);
+ assertEquals(activeStats.getStatsPerHost().get(hostname).getHostConnectionCount(), 5);
futures.forEach(future -> future.toCompletableFuture().join());
@@ -138,9 +147,10 @@ public void testClientStatusNoKeepalive() throws Throwable {
final ClientStats idleStats = client.getClientStats();
assertEquals(idleStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
- assertEquals(idleStats.getActiveConnectionCount(), 0);
- assertEquals(idleStats.getIdleConnectionCount(), 0);
+ assertEquals(idleStats.getTotalActiveConnectionCount(), 0);
+ assertEquals(idleStats.getTotalIdleConnectionCount(), 0);
assertEquals(idleStats.getTotalConnectionCount(), 0);
+ assertNull(idleStats.getStatsPerHost().get(hostname));
// Let's make sure the active count is correct when reusing cached connections.
@@ -154,9 +164,10 @@ public void testClientStatusNoKeepalive() throws Throwable {
final ClientStats activeCachedStats = client.getClientStats();
assertEquals(activeCachedStats.toString(), "There are 3 total connections, 3 are active and 0 are idle.");
- assertEquals(activeCachedStats.getActiveConnectionCount(), 3);
- assertEquals(activeCachedStats.getIdleConnectionCount(), 0);
+ assertEquals(activeCachedStats.getTotalActiveConnectionCount(), 3);
+ assertEquals(activeCachedStats.getTotalIdleConnectionCount(), 0);
assertEquals(activeCachedStats.getTotalConnectionCount(), 3);
+ assertEquals(activeCachedStats.getStatsPerHost().get(hostname).getHostConnectionCount(), 3);
repeatedFutures.forEach(future -> future.toCompletableFuture().join());
@@ -165,9 +176,10 @@ public void testClientStatusNoKeepalive() throws Throwable {
final ClientStats idleCachedStats = client.getClientStats();
assertEquals(idleCachedStats.toString(), "There are 0 total connections, 0 are active and 0 are idle.");
- assertEquals(idleCachedStats.getActiveConnectionCount(), 0);
- assertEquals(idleCachedStats.getIdleConnectionCount(), 0);
+ assertEquals(idleCachedStats.getTotalActiveConnectionCount(), 0);
+ assertEquals(idleCachedStats.getTotalIdleConnectionCount(), 0);
assertEquals(idleCachedStats.getTotalConnectionCount(), 0);
+ assertNull(idleCachedStats.getStatsPerHost().get(hostname));
}
}
}
From 2ded5269fd6087fdb51d5e31564fdf7198daf92d Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 17:43:30 +0100
Subject: [PATCH 085/901] Don't use ==
---
.../java/org/asynchttpclient/netty/util/ByteBufUtils.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
index c5f66ac674..95729f62ea 100755
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
@@ -27,7 +27,7 @@ private ByteBufUtils() {
}
public static String byteBuf2String(Charset charset, ByteBuf buf) throws CharacterCodingException {
- if (charset == UTF_8 || charset == US_ASCII) {
+ if (charset.equals(UTF_8) || charset.equals(US_ASCII)) {
return Utf8ByteBufCharsetDecoder.decodeUtf8(buf);
} else {
return buf.toString(charset);
@@ -35,7 +35,7 @@ public static String byteBuf2String(Charset charset, ByteBuf buf) throws Charact
}
public static String byteBuf2String(Charset charset, ByteBuf... bufs) throws CharacterCodingException {
- if (charset == UTF_8 || charset == US_ASCII) {
+ if (charset.equals(UTF_8) || charset.equals(US_ASCII)) {
return Utf8ByteBufCharsetDecoder.decodeUtf8(bufs);
} else {
CompositeByteBuf composite = Unpooled.compositeBuffer(bufs.length);
From e9364a63d783b5871058ccfe9ec2ed33c48c2c2d Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 18:10:02 +0100
Subject: [PATCH 086/901] ByteBufUtils shouldn't release input ByteBufs, close
#1302
---
.../netty/util/ByteBufUtils.java | 31 +++++++++++--------
.../netty/util/Utf8ByteBufCharsetDecoder.java | 8 +----
2 files changed, 19 insertions(+), 20 deletions(-)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
index 95729f62ea..237ea001f4 100755
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
@@ -34,23 +34,28 @@ public static String byteBuf2String(Charset charset, ByteBuf buf) throws Charact
}
}
+ public static String decodeNonOptimized(Charset charset, ByteBuf... bufs) {
+
+ CompositeByteBuf composite = Unpooled.compositeBuffer(bufs.length);
+
+ try {
+ for (ByteBuf buf : bufs) {
+ buf.retain();
+ composite.addComponent(buf);
+ }
+
+ return composite.toString(charset);
+
+ } finally {
+ composite.release();
+ }
+ }
+
public static String byteBuf2String(Charset charset, ByteBuf... bufs) throws CharacterCodingException {
if (charset.equals(UTF_8) || charset.equals(US_ASCII)) {
return Utf8ByteBufCharsetDecoder.decodeUtf8(bufs);
} else {
- CompositeByteBuf composite = Unpooled.compositeBuffer(bufs.length);
-
- try {
- for (ByteBuf buf : bufs) {
- buf.retain();
- composite.addComponent(buf);
- }
-
- return composite.toString(charset);
-
- } finally {
- composite.release();
- }
+ return decodeNonOptimized(charset, bufs);
}
}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
index ccc35c27dd..b6155653ec 100644
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
@@ -15,7 +15,6 @@
import static java.nio.charset.StandardCharsets.UTF_8;
import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
@@ -194,12 +193,7 @@ public String decode(ByteBuf... bufs) throws CharacterCodingException {
}
if (direct) {
- ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bufs);
- try {
- return wrappedBuffer.toString(UTF_8);
- } finally {
- wrappedBuffer.release();
- }
+ return ByteBufUtils.decodeNonOptimized(UTF_8, bufs);
} else {
ByteBuffer[] nioBuffers = new ByteBuffer[totalNioBuffers];
From baee03a0cc4aecdbeee6c0ced3d0d8d89072a941 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 18:12:08 +0100
Subject: [PATCH 087/901] Add test (disabled for now) for #1299
---
.../asynchttpclient/EofTerminatedTest.java | 57 +++++++++++++++++++
1 file changed, 57 insertions(+)
create mode 100644 client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
diff --git a/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java b/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
new file mode 100644
index 0000000000..760ec24238
--- /dev/null
+++ b/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
+package org.asynchttpclient;
+
+import static io.netty.handler.codec.http.HttpHeaders.Names.*;
+import static io.netty.handler.codec.http.HttpHeaders.Values.*;
+import static org.asynchttpclient.Dsl.*;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.eclipse.jetty.server.Request;
+import org.eclipse.jetty.server.handler.AbstractHandler;
+import org.eclipse.jetty.server.handler.gzip.GzipHandler;
+import org.testng.annotations.Test;
+
+public class EofTerminatedTest extends AbstractBasicTest {
+
+ private static class StreamHandler extends AbstractHandler {
+ @Override
+ public void handle(String pathInContext, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
+ request.getResponse().getHttpOutput().sendContent(EofTerminatedTest.class.getClassLoader().getResourceAsStream("SimpleTextFile.txt"));
+ }
+ }
+
+ protected String getTargetUrl() {
+ return String.format("http://localhost:%d/", port1);
+ }
+
+ @Override
+ public AbstractHandler configureHandler() throws Exception {
+ GzipHandler gzipHandler = new GzipHandler();
+ gzipHandler.setHandler(new StreamHandler());
+ return gzipHandler;
+ }
+
+ @Test(enabled = false)
+ public void testEolTerminatedResponse() throws Exception {
+ try (AsyncHttpClient ahc = asyncHttpClient(config().setMaxRequestRetry(0))) {
+ ahc.executeRequest(ahc.prepareGet(getTargetUrl()).setHeader(ACCEPT_ENCODING, GZIP_DEFLATE).setHeader(CONNECTION, CLOSE).build()).get();
+ }
+ }
+}
From 2f22564a2ac58246b465f2d3edb74c71d9876776 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 18:19:18 +0100
Subject: [PATCH 088/901] [maven-release-plugin] prepare release
async-http-client-project-2.0.22
---
client/pom.xml | 2 +-
example/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
14 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 31d5153b27..8ab067a6f7 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22-SNAPSHOT
+ 2.0.224.0.0async-http-client
diff --git a/example/pom.xml b/example/pom.xml
index eecf3b339b..1a90ea8678 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22-SNAPSHOT
+ 2.0.224.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 7cca1704ab..9b93845ef7 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.22-SNAPSHOT
+ 2.0.224.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 700ee9afa1..8e85ab70ea 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.22-SNAPSHOT
+ 2.0.22async-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 5f31d528f2..9b97610a9d 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22-SNAPSHOT
+ 2.0.224.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index ed1373a3af..b2e7cd725e 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.22-SNAPSHOT
+ 2.0.224.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 0b4d3cad9b..9d6fe8d41a 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.22-SNAPSHOT
+ 2.0.22async-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 8593da1585..2965eeb435 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.22-SNAPSHOT
+ 2.0.22async-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 8a878b8e82..76fedcbb5d 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.22-SNAPSHOT
+ 2.0.22netty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 1deec666d6..49c79b2ebe 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22-SNAPSHOT
+ 2.0.224.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index e4cb0eecce..dfed18f487 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.22-SNAPSHOT
+ 2.0.22netty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 881c726356..3a0852248f 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.22-SNAPSHOT
+ 2.0.22netty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index 5ff00181f5..0dd9455139 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22-SNAPSHOT
+ 2.0.224.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index edead3b84a..474092ecc1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.22-SNAPSHOT
+ 2.0.22pom
The Async Http Client (AHC) library's purpose is to allow Java
From 3150d6ba81e403c2740a7db59e5a43385d2176e5 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 18:19:25 +0100
Subject: [PATCH 089/901] [maven-release-plugin] prepare for next development
iteration
---
client/pom.xml | 2 +-
example/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
14 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 8ab067a6f7..608c47e0d0 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22
+ 2.0.23-SNAPSHOT4.0.0async-http-client
diff --git a/example/pom.xml b/example/pom.xml
index 1a90ea8678..bcc2645836 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22
+ 2.0.23-SNAPSHOT4.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 9b93845ef7..65122ed06d 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.22
+ 2.0.23-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 8e85ab70ea..47c2ef084c 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.22
+ 2.0.23-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 9b97610a9d..1b138ef9f8 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22
+ 2.0.23-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index b2e7cd725e..4cc86f354e 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.22
+ 2.0.23-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 9d6fe8d41a..d645c45e83 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.22
+ 2.0.23-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 2965eeb435..0da09c3284 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.22
+ 2.0.23-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 76fedcbb5d..bf8ea73629 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.22
+ 2.0.23-SNAPSHOTnetty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 49c79b2ebe..78861e4577 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22
+ 2.0.23-SNAPSHOT4.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index dfed18f487..8aa954c6b3 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.22
+ 2.0.23-SNAPSHOTnetty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 3a0852248f..948e20d689 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.22
+ 2.0.23-SNAPSHOTnetty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index 0dd9455139..96b2c66e57 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.22
+ 2.0.23-SNAPSHOT4.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index 474092ecc1..caac14bf4b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.22
+ 2.0.23-SNAPSHOTpom
The Async Http Client (AHC) library's purpose is to allow Java
From b903186ab7e07f3c0ad268626edcfa1dd5d418c3 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 20:14:39 +0100
Subject: [PATCH 090/901] minor clean up
---
.../netty/util/Utf8ByteBufCharsetDecoder.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
index b6155653ec..7f4c863635 100644
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
@@ -182,17 +182,17 @@ public String decode(ByteBuf... bufs) throws CharacterCodingException {
int totalSize = 0;
int totalNioBuffers = 0;
- boolean direct = false;
+ boolean withoutArray = false;
for (ByteBuf buf : bufs) {
- if (buf.isDirect()) {
- direct = true;
+ if (!buf.hasArray()) {
+ withoutArray = true;
break;
}
totalSize += buf.readableBytes();
totalNioBuffers += buf.nioBufferCount();
}
- if (direct) {
+ if (withoutArray) {
return ByteBufUtils.decodeNonOptimized(UTF_8, bufs);
} else {
From b3c4ba57d33ec8a25819ea9d5704e63aa8d20a9e Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 21:54:13 +0100
Subject: [PATCH 091/901] Properly clear Utf8ByteBufCharsetDecoder's
charBuffer, close #1303
---
.../asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
index 7f4c863635..09061db233 100644
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
@@ -74,7 +74,7 @@ private void ensureCapacity(int l) {
public void reset() {
decoder.reset();
- charBuffer.position(0);
+ charBuffer.clear();
}
private static int charSize(byte firstByte) throws CharacterCodingException {
From 3a0b4b4aa07ee83a908cbebe0eea2fb7a4e76e76 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 21:57:07 +0100
Subject: [PATCH 092/901] [maven-release-plugin] prepare release
async-http-client-project-2.0.23
---
client/pom.xml | 2 +-
example/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
14 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 608c47e0d0..72673722d3 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23-SNAPSHOT
+ 2.0.234.0.0async-http-client
diff --git a/example/pom.xml b/example/pom.xml
index bcc2645836..34a42b5e27 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23-SNAPSHOT
+ 2.0.234.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 65122ed06d..b3e20d55b2 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.23-SNAPSHOT
+ 2.0.234.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 47c2ef084c..5230516c30 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.23-SNAPSHOT
+ 2.0.23async-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 1b138ef9f8..a7995e76d4 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23-SNAPSHOT
+ 2.0.234.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 4cc86f354e..d83752d438 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.23-SNAPSHOT
+ 2.0.234.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index d645c45e83..664b8e57dd 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.23-SNAPSHOT
+ 2.0.23async-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 0da09c3284..20b12df958 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.23-SNAPSHOT
+ 2.0.23async-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index bf8ea73629..3ca96f5a2a 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.23-SNAPSHOT
+ 2.0.23netty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 78861e4577..ff199c474a 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23-SNAPSHOT
+ 2.0.234.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index 8aa954c6b3..e17362b05a 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.23-SNAPSHOT
+ 2.0.23netty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 948e20d689..4f480b4265 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.23-SNAPSHOT
+ 2.0.23netty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index 96b2c66e57..2dc4a722e3 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23-SNAPSHOT
+ 2.0.234.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index caac14bf4b..15dec3d670 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.23-SNAPSHOT
+ 2.0.23pom
The Async Http Client (AHC) library's purpose is to allow Java
From 71cc2f58460bffa5e2ed77bff9ceb6a5c4f52e5b Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 7 Nov 2016 21:57:14 +0100
Subject: [PATCH 093/901] [maven-release-plugin] prepare for next development
iteration
---
client/pom.xml | 2 +-
example/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
14 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 72673722d3..4fdaf851ac 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23
+ 2.0.24-SNAPSHOT4.0.0async-http-client
diff --git a/example/pom.xml b/example/pom.xml
index 34a42b5e27..e4a5306d5e 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23
+ 2.0.24-SNAPSHOT4.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index b3e20d55b2..302b26ee5f 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.23
+ 2.0.24-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 5230516c30..321b25ad4e 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.23
+ 2.0.24-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index a7995e76d4..441e0dcd3d 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23
+ 2.0.24-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index d83752d438..c1e2e9e4df 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.23
+ 2.0.24-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 664b8e57dd..de60bd5978 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.23
+ 2.0.24-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 20b12df958..14b14bc29d 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.23
+ 2.0.24-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 3ca96f5a2a..d57b1ca864 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.23
+ 2.0.24-SNAPSHOTnetty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index ff199c474a..4994aeed77 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23
+ 2.0.24-SNAPSHOT4.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index e17362b05a..a8d09e9d9f 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.23
+ 2.0.24-SNAPSHOTnetty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 4f480b4265..48c1335b2d 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.23
+ 2.0.24-SNAPSHOTnetty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index 2dc4a722e3..9cbfc310ad 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.23
+ 2.0.24-SNAPSHOT4.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index 15dec3d670..412e9bdd3a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.23
+ 2.0.24-SNAPSHOTpom
The Async Http Client (AHC) library's purpose is to allow Java
From bd263b218ab116329fbdb178fd56245aa98fb7aa Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Tue, 8 Nov 2016 14:35:43 +0100
Subject: [PATCH 094/901] Remove forked HttpContentDecoder, close #1304
---
.../codec/http/HttpContentDecoder.java | 253 ------------------
1 file changed, 253 deletions(-)
delete mode 100644 client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java
diff --git a/client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java b/client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java
deleted file mode 100644
index 3cfadcb0db..0000000000
--- a/client/src/main/java/io/netty/handler/codec/http/HttpContentDecoder.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Copyright 2012 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.http;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.embedded.EmbeddedChannel;
-import io.netty.handler.codec.CodecException;
-import io.netty.handler.codec.MessageToMessageDecoder;
-import io.netty.util.ReferenceCountUtil;
-
-import java.util.List;
-
-/**
- * Decodes the content of the received {@link HttpRequest} and {@link HttpContent}.
- * The original content is replaced with the new content decoded by the
- * {@link EmbeddedChannel}, which is created by {@link #newContentDecoder(String)}.
- * Once decoding is finished, the value of the 'Content-Encoding'
- * header is set to the target content encoding, as returned by {@link #getTargetContentEncoding(String)}.
- * Also, the 'Content-Length' header is updated to the length of the
- * decoded content. If the content encoding of the original is not supported
- * by the decoder, {@link #newContentDecoder(String)} should return {@code null}
- * so that no decoding occurs (i.e. pass-through).
- *
- * Please note that this is an abstract class. You have to extend this class
- * and implement {@link #newContentDecoder(String)} properly to make this class
- * functional. For example, refer to the source code of {@link HttpContentDecompressor}.
- *
- org.asynchttpclient
+ io.nettynetty-resolver-dns
- ${project.version}org.reactivestreams
diff --git a/client/src/main/java/io/netty/channel/ChannelId.java b/client/src/main/java/io/netty/channel/ChannelId.java
deleted file mode 100644
index 5baa48f2a3..0000000000
--- a/client/src/main/java/io/netty/channel/ChannelId.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project 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 io.netty.channel;
-
-import java.io.Serializable;
-
-/**
- * Represents the globally unique identifier of a {@link Channel}.
- *
- * The identifier is generated from various sources listed in the following:
- *
- *
MAC address (EUI-48 or EUI-64) or the network adapter, preferably a globally unique one,
- *
the current process ID,
- *
{@link System#currentTimeMillis()},
- *
{@link System#nanoTime()},
- *
a random 32-bit integer, and
- *
a sequentially incremented 32-bit integer.
- *
- *
- * The global uniqueness of the generated identifier mostly depends on the MAC address and the current process ID,
- * which are auto-detected at the class-loading time in best-effort manner. If all attempts to acquire them fail,
- * a warning message is logged, and random values will be used instead. Alternatively, you can specify them manually
- * via system properties:
- *
- *
{@code io.netty.machineId} - hexadecimal representation of 48 (or 64) bit integer,
- * optionally separated by colon or hyphen.
- *
{@code io.netty.processId} - an integer between 0 and 65535
- *
- */
-public interface ChannelId extends Serializable, Comparable {
- /**
- * @return the short but globally non-unique string representation of the {@link ChannelId}.
- */
- String asShortText();
-
- /**
- * @return the long yet globally unique string representation of the {@link ChannelId}.
- */
- String asLongText();
-}
diff --git a/client/src/main/java/io/netty/channel/DefaultChannelId.java b/client/src/main/java/io/netty/channel/DefaultChannelId.java
deleted file mode 100644
index 3e7c42c3b3..0000000000
--- a/client/src/main/java/io/netty/channel/DefaultChannelId.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project 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 io.netty.channel;
-
-import io.netty.buffer.ByteBufUtil;
-import io.netty.util.internal.MacAddressUtil;
-import io.netty.util.internal.EmptyArrays;
-import io.netty.util.internal.PlatformDependent;
-import io.netty.util.internal.SystemPropertyUtil;
-import io.netty.util.internal.ThreadLocalRandom;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.regex.Pattern;
-
-/**
- * The default {@link ChannelId} implementation.
- */
-public final class DefaultChannelId implements ChannelId {
-
- private static final long serialVersionUID = 3884076183504074063L;
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelId.class);
-
- private static final Pattern MACHINE_ID_PATTERN = Pattern.compile("^(?:[0-9a-fA-F][:-]?){6,8}$");
- private static final int MACHINE_ID_LEN = MacAddressUtil.MAC_ADDRESS_LENGTH;
- private static final byte[] MACHINE_ID;
- private static final int PROCESS_ID_LEN = 4;
- // Maximal value for 64bit systems is 2^22. See man 5 proc.
- // See https://github.com/netty/netty/issues/2706
- private static final int MAX_PROCESS_ID = 4194304;
- private static final int PROCESS_ID;
- private static final int SEQUENCE_LEN = 4;
- private static final int TIMESTAMP_LEN = 8;
- private static final int RANDOM_LEN = 4;
-
- private static final AtomicInteger nextSequence = new AtomicInteger();
-
- static ChannelId newInstance() {
- DefaultChannelId id = new DefaultChannelId();
- id.init();
- return id;
- }
-
- static {
- int processId = -1;
- String customProcessId = SystemPropertyUtil.get("io.netty.processId");
- if (customProcessId != null) {
- try {
- processId = Integer.parseInt(customProcessId);
- } catch (NumberFormatException e) {
- // Malformed input.
- }
-
- if (processId < 0 || processId > MAX_PROCESS_ID) {
- processId = -1;
- logger.warn("-Dio.netty.processId: {} (malformed)", customProcessId);
- } else if (logger.isDebugEnabled()) {
- logger.debug("-Dio.netty.processId: {} (user-set)", processId);
- }
- }
-
- if (processId < 0) {
- processId = defaultProcessId();
- if (logger.isDebugEnabled()) {
- logger.debug("-Dio.netty.processId: {} (auto-detected)", processId);
- }
- }
-
- PROCESS_ID = processId;
-
- byte[] machineId = null;
- String customMachineId = SystemPropertyUtil.get("io.netty.machineId");
- if (customMachineId != null) {
- if (MACHINE_ID_PATTERN.matcher(customMachineId).matches()) {
- machineId = parseMachineId(customMachineId);
- logger.debug("-Dio.netty.machineId: {} (user-set)", customMachineId);
- } else {
- logger.warn("-Dio.netty.machineId: {} (malformed)", customMachineId);
- }
- }
-
- if (machineId == null) {
- machineId = defaultMachineId();
- if (logger.isDebugEnabled()) {
- logger.debug("-Dio.netty.machineId: {} (auto-detected)", MacAddressUtil.formatAddress(machineId));
- }
- }
-
- MACHINE_ID = machineId;
- }
-
- @SuppressWarnings("DynamicRegexReplaceableByCompiledPattern")
- private static byte[] parseMachineId(String value) {
- // Strip separators.
- value = value.replaceAll("[:-]", "");
-
- byte[] machineId = new byte[MACHINE_ID_LEN];
- for (int i = 0; i < value.length(); i += 2) {
- machineId[i] = (byte) Integer.parseInt(value.substring(i, i + 2), 16);
- }
-
- return machineId;
- }
-
- private static byte[] defaultMachineId() {
- byte[] bestMacAddr = MacAddressUtil.bestAvailableMac();
- if (bestMacAddr == null) {
- bestMacAddr = new byte[MacAddressUtil.MAC_ADDRESS_LENGTH];
- ThreadLocalRandom.current().nextBytes(bestMacAddr);
- logger.warn(
- "Failed to find a usable hardware address from the network interfaces; using random bytes: {}",
- MacAddressUtil.formatAddress(bestMacAddr));
- }
- return bestMacAddr;
- }
-
- private static int defaultProcessId() {
- final ClassLoader loader = PlatformDependent.getSystemClassLoader();
- String value;
- try {
- // Invoke java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
- Class> mgmtFactoryType = Class.forName("java.lang.management.ManagementFactory", true, loader);
- Class> runtimeMxBeanType = Class.forName("java.lang.management.RuntimeMXBean", true, loader);
-
- Method getRuntimeMXBean = mgmtFactoryType.getMethod("getRuntimeMXBean", EmptyArrays.EMPTY_CLASSES);
- Object bean = getRuntimeMXBean.invoke(null, EmptyArrays.EMPTY_OBJECTS);
- Method getName = runtimeMxBeanType.getDeclaredMethod("getName", EmptyArrays.EMPTY_CLASSES);
- value = (String) getName.invoke(bean, EmptyArrays.EMPTY_OBJECTS);
- } catch (Exception e) {
- logger.debug("Could not invoke ManagementFactory.getRuntimeMXBean().getName(); Android?", e);
- try {
- // Invoke android.os.Process.myPid()
- Class> processType = Class.forName("android.os.Process", true, loader);
- Method myPid = processType.getMethod("myPid", EmptyArrays.EMPTY_CLASSES);
- value = myPid.invoke(null, EmptyArrays.EMPTY_OBJECTS).toString();
- } catch (Exception e2) {
- logger.debug("Could not invoke Process.myPid(); not Android?", e2);
- value = "";
- }
- }
-
- int atIndex = value.indexOf('@');
- if (atIndex >= 0) {
- value = value.substring(0, atIndex);
- }
-
- int pid;
- try {
- pid = Integer.parseInt(value);
- } catch (NumberFormatException e) {
- // value did not contain an integer.
- pid = -1;
- }
-
- if (pid < 0 || pid > MAX_PROCESS_ID) {
- pid = ThreadLocalRandom.current().nextInt(MAX_PROCESS_ID + 1);
- logger.warn("Failed to find the current process ID from '{}'; using a random value: {}", value, pid);
- }
-
- return pid;
- }
-
- private final byte[] data = new byte[MACHINE_ID_LEN + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN + RANDOM_LEN];
- private int hashCode;
-
- private transient String shortValue;
- private transient String longValue;
-
- private void init() {
- int i = 0;
-
- // machineId
- System.arraycopy(MACHINE_ID, 0, data, i, MACHINE_ID_LEN);
- i += MACHINE_ID_LEN;
-
- // processId
- i = writeInt(i, PROCESS_ID);
-
- // sequence
- i = writeInt(i, nextSequence.getAndIncrement());
-
- // timestamp (kind of)
- i = writeLong(i, Long.reverse(System.nanoTime()) ^ System.currentTimeMillis());
-
- // random
- int random = ThreadLocalRandom.current().nextInt();
- hashCode = random;
- i = writeInt(i, random);
-
- assert i == data.length;
- }
-
- private int writeInt(int i, int value) {
- data[i ++] = (byte) (value >>> 24);
- data[i ++] = (byte) (value >>> 16);
- data[i ++] = (byte) (value >>> 8);
- data[i ++] = (byte) value;
- return i;
- }
-
- private int writeLong(int i, long value) {
- data[i ++] = (byte) (value >>> 56);
- data[i ++] = (byte) (value >>> 48);
- data[i ++] = (byte) (value >>> 40);
- data[i ++] = (byte) (value >>> 32);
- data[i ++] = (byte) (value >>> 24);
- data[i ++] = (byte) (value >>> 16);
- data[i ++] = (byte) (value >>> 8);
- data[i ++] = (byte) value;
- return i;
- }
-
- @Override
- public String asShortText() {
- String shortValue = this.shortValue;
- if (shortValue == null) {
- this.shortValue = shortValue = ByteBufUtil.hexDump(
- data, MACHINE_ID_LEN + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN, RANDOM_LEN);
- }
- return shortValue;
- }
-
- @Override
- public String asLongText() {
- String longValue = this.longValue;
- if (longValue == null) {
- this.longValue = longValue = newLongValue();
- }
- return longValue;
- }
-
- private String newLongValue() {
- StringBuilder buf = new StringBuilder(2 * data.length + 5);
- int i = 0;
- i = appendHexDumpField(buf, i, MACHINE_ID_LEN);
- i = appendHexDumpField(buf, i, PROCESS_ID_LEN);
- i = appendHexDumpField(buf, i, SEQUENCE_LEN);
- i = appendHexDumpField(buf, i, TIMESTAMP_LEN);
- i = appendHexDumpField(buf, i, RANDOM_LEN);
- assert i == data.length;
- return buf.substring(0, buf.length() - 1);
- }
-
- private int appendHexDumpField(StringBuilder buf, int i, int length) {
- buf.append(ByteBufUtil.hexDump(data, i, length));
- buf.append('-');
- i += length;
- return i;
- }
-
- @Override
- public int hashCode() {
- return hashCode;
- }
-
- @Override
- public int compareTo(ChannelId o) {
- return 0;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
-
- if (!(obj instanceof DefaultChannelId)) {
- return false;
- }
-
- return Arrays.equals(data, ((DefaultChannelId) obj).data);
- }
-
- @Override
- public String toString() {
- return asShortText();
- }
-}
\ No newline at end of file
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java b/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
index 2c76a78d96..1e61514af4 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
@@ -13,14 +13,12 @@
*/
package org.asynchttpclient.netty.channel;
-import java.util.concurrent.atomic.AtomicBoolean;
-
import io.netty.channel.Channel;
-import io.netty.channel.ChannelId;
-import io.netty.channel.DefaultChannelId;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
+import java.util.concurrent.atomic.AtomicBoolean;
+
import org.asynchttpclient.netty.DiscardEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -30,7 +28,6 @@ public class Channels {
private static final Logger LOGGER = LoggerFactory.getLogger(Channels.class);
private static final AttributeKey DEFAULT_ATTRIBUTE = AttributeKey.valueOf("default");
- private static final AttributeKey CHANNEL_ID_ATTRIBUTE = AttributeKey.valueOf("channelId");
private static final AttributeKey INACTIVE_TOKEN_ATTRIBUTE = AttributeKey.valueOf("inactiveToken");
public static Object getAttribute(Channel channel) {
@@ -58,15 +55,6 @@ public static boolean getInactiveToken(Channel channel) {
return channel != null && channel.attr(INACTIVE_TOKEN_ATTRIBUTE).get().getAndSet(false);
}
- public static ChannelId getChannelId(Channel channel) {
- Attribute attr = channel.attr(CHANNEL_ID_ATTRIBUTE);
- return attr != null ? attr.get() : null;
- }
-
- public static void initChannelId(Channel channel) {
- channel.attr(CHANNEL_ID_ATTRIBUTE).set(new DefaultChannelId());
- }
-
public static void silentlyCloseChannel(Channel channel) {
try {
if (channel != null && channel.isActive())
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
index 878db3a290..7ff310e02c 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
@@ -58,10 +58,6 @@ public DefaultChannelPool(AsyncHttpClientConfig config, Timer hashedWheelTimer)
config.getConnectionPoolCleanerPeriod());
}
- private ChannelId channelId(Channel channel) {
- return Channels.getChannelId(channel);
- }
-
public DefaultChannelPool(int maxIdleTime,//
int connectionTtl,//
Timer nettyTimer,//
@@ -136,7 +132,7 @@ private boolean isTtlExpired(Channel channel, long now) {
if (!connectionTtlEnabled)
return false;
- ChannelCreation creation = channelId2Creation.get(channelId(channel));
+ ChannelCreation creation = channelId2Creation.get(channel.id());
return creation != null && now - creation.creationTime >= connectionTtl;
}
@@ -218,7 +214,7 @@ public void run(Timeout timeout) throws Exception {
if (!closedChannels.isEmpty()) {
if (connectionTtlEnabled) {
for (IdleChannel closedChannel : closedChannels)
- channelId2Creation.remove(channelId(closedChannel.channel));
+ channelId2Creation.remove(closedChannel.channel.id());
}
partition.removeAll(closedChannels);
@@ -264,7 +260,7 @@ private boolean offer0(Channel channel, Object partitionKey, long now) {
}
private void registerChannelCreation(Channel channel, Object partitionKey, long now) {
- ChannelId id = channelId(channel);
+ ChannelId id = channel.id();
if (!channelId2Creation.containsKey(id)) {
channelId2Creation.putIfAbsent(id, new ChannelCreation(now, partitionKey));
}
@@ -300,7 +296,7 @@ else if (isRemotelyClosed(idleChannel.channel)) {
* {@inheritDoc}
*/
public boolean removeAll(Channel channel) {
- ChannelCreation creation = connectionTtlEnabled ? channelId2Creation.remove(channelId(channel)) : null;
+ ChannelCreation creation = connectionTtlEnabled ? channelId2Creation.remove(channel.id()) : null;
return !isClosed.get() && creation != null && partitions.get(creation.partitionKey).remove(channel);
}
@@ -328,7 +324,7 @@ private void close(Channel channel) {
// FIXME pity to have to do this here
Channels.setDiscard(channel);
if (connectionTtlEnabled) {
- channelId2Creation.remove(channelId(channel));
+ channelId2Creation.remove(channel.id());
}
Channels.silentlyCloseChannel(channel);
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java b/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java
index 2540eb2fbf..c14453c0ee 100644
--- a/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java
+++ b/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java
@@ -26,7 +26,6 @@
import org.asynchttpclient.AsyncHttpClientState;
import org.asynchttpclient.handler.AsyncHandlerExtensions;
import org.asynchttpclient.netty.SimpleChannelFutureListener;
-import org.asynchttpclient.netty.channel.Channels;
import org.asynchttpclient.netty.channel.NettyConnectListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,7 +38,6 @@ public class NettyChannelConnector {
private final InetSocketAddress localAddress;
private final List remoteAddresses;
private final AsyncHttpClientState clientState;
- private final boolean connectionTtlEnabled;
private volatile int i = 0;
public NettyChannelConnector(InetAddress localAddress,//
@@ -51,7 +49,6 @@ public NettyChannelConnector(InetAddress localAddress,//
this.remoteAddresses = remoteAddresses;
this.asyncHandlerExtensions = toAsyncHandlerExtensions(asyncHandler);
this.clientState = clientState;
- this.connectionTtlEnabled = config.getConnectionTtl() > 0;
}
private boolean pickNextRemoteAddress() {
@@ -86,9 +83,6 @@ public void onSuccess(Channel channel) {
if (asyncHandlerExtensions != null) {
asyncHandlerExtensions.onTcpConnectSuccess(remoteAddress, channel);
}
- if (connectionTtlEnabled) {
- Channels.initChannelId(channel);
- }
connectListener.onSuccess(channel, remoteAddress);
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java
index a0d53b048a..b208308fe8 100755
--- a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java
+++ b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java
@@ -15,6 +15,7 @@
import static org.asynchttpclient.util.Assertions.assertNotNull;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.stream.ChunkedInput;
@@ -30,10 +31,12 @@ public class BodyChunkedInput implements ChunkedInput {
private final Body body;
private final int chunkSize;
private boolean endOfInput;
+ private final long contentLength;
+ private long progress = 0L;
public BodyChunkedInput(Body body) {
this.body = assertNotNull(body, "body");
- long contentLength = body.getContentLength();
+ this.contentLength = body.getContentLength();
if (contentLength <= 0)
chunkSize = DEFAULT_CHUNK_SIZE;
else
@@ -41,12 +44,18 @@ public BodyChunkedInput(Body body) {
}
@Override
- public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
+ @Deprecated
+ public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
+ return readChunk(ctx.alloc());
+ }
+
+ @Override
+ public ByteBuf readChunk(ByteBufAllocator alloc) throws Exception {
if (endOfInput)
return null;
- ByteBuf buffer = ctx.alloc().buffer(chunkSize);
+ ByteBuf buffer = alloc.buffer(chunkSize);
Body.BodyState state = body.transferTo(buffer);
switch (state) {
case STOP:
@@ -72,4 +81,14 @@ public boolean isEndOfInput() throws Exception {
public void close() throws Exception {
body.close();
}
+
+ @Override
+ public long length() {
+ return contentLength;
+ }
+
+ @Override
+ public long progress() {
+ return progress;
+ }
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java
index bd419a6f79..59ef476d03 100755
--- a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java
+++ b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java
@@ -24,6 +24,7 @@
import java.io.IOException;
import java.nio.channels.WritableByteChannel;
+
/**
* Adapts a {@link RandomAccessBody} to Netty's {@link FileRegion}.
*/
@@ -48,9 +49,36 @@ public long count() {
@Override
public long transfered() {
+ return transferred();
+ }
+
+ @Override
+ public long transferred() {
return transferred;
}
+ @Override
+ public FileRegion retain() {
+ super.retain();
+ return this;
+ }
+
+ @Override
+ public FileRegion retain(int arg0) {
+ super.retain(arg0);
+ return this;
+ }
+
+ @Override
+ public FileRegion touch() {
+ return this;
+ }
+
+ @Override
+ public FileRegion touch(Object arg0) {
+ return this;
+ }
+
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
long written = body.transferTo(target);
diff --git a/client/src/test/java/org/asynchttpclient/BasicHttpTest.java b/client/src/test/java/org/asynchttpclient/BasicHttpTest.java
index 7d0132b467..9b22a26cc9 100755
--- a/client/src/test/java/org/asynchttpclient/BasicHttpTest.java
+++ b/client/src/test/java/org/asynchttpclient/BasicHttpTest.java
@@ -925,7 +925,7 @@ public void postUnboundedInputStreamAsBodyStream() throws Throwable {
withClient().run(client -> {
withServer(server).run(server -> {
HttpHeaders h = new DefaultHttpHeaders();
- h.add(CONTENT_TYPE, APPLICATION_JSON);
+ h.add(CONTENT_TYPE, "application/json"); //FIXME
server.enqueue(new AbstractHandler() {
EchoHandler chain = new EchoHandler();
@Override
@@ -959,7 +959,7 @@ public void postInputStreamWithContentLengthAsBodyGenerator() throws Throwable {
withClient().run(client -> {
withServer(server).run(server -> {
HttpHeaders h = new DefaultHttpHeaders();
- h.add(CONTENT_TYPE, APPLICATION_JSON);
+ h.add(CONTENT_TYPE, "application/json"); //FIXME
server.enqueue(new AbstractHandler() {
EchoHandler chain = new EchoHandler();
@Override
diff --git a/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java b/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
index 760ec24238..edb194b0ff 100644
--- a/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
+++ b/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
@@ -51,7 +51,8 @@ public AbstractHandler configureHandler() throws Exception {
@Test(enabled = false)
public void testEolTerminatedResponse() throws Exception {
try (AsyncHttpClient ahc = asyncHttpClient(config().setMaxRequestRetry(0))) {
- ahc.executeRequest(ahc.prepareGet(getTargetUrl()).setHeader(ACCEPT_ENCODING, GZIP_DEFLATE).setHeader(CONNECTION, CLOSE).build()).get();
+ //FIXME
+ ahc.executeRequest(ahc.prepareGet(getTargetUrl()).setHeader(ACCEPT_ENCODING, "gzip, deflate").setHeader(CONNECTION, CLOSE).build()).get();
}
}
}
diff --git a/example/pom.xml b/example/pom.xml
index 10fe7285b1..1e1eacaee5 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 922c22e062..76c56ec764 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index b48bf7c370..1734d2b3d6 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index a59811c5fa..332f93c4bb 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 626243671f..49d0318db4 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 25840422db..2d60b43eb3 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index aa01ec4879..5d4306d00e 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
deleted file mode 100644
index 568e91b75f..0000000000
--- a/netty-bp/codec-dns/pom.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-
-
- 4.0.0
-
- org.asynchttpclient
- netty-bp
- 2.0.25-SNAPSHOT
-
-
- netty-codec-dns
-
- Netty/Codec/DNS
-
-
-
- io.netty
- netty-codec
-
-
-
-
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java
deleted file mode 100644
index 697a33a808..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java
+++ /dev/null
@@ -1,457 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.util.AbstractReferenceCounted;
-import io.netty.util.ReferenceCountUtil;
-import io.netty.util.ReferenceCounted;
-import io.netty.util.ResourceLeak;
-import io.netty.util.ResourceLeakDetector;
-import io.netty.util.internal.StringUtil;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * A skeletal implementation of {@link DnsMessage}.
- */
-public abstract class AbstractDnsMessage extends AbstractReferenceCounted implements DnsMessage {
-
- private static final ResourceLeakDetector leakDetector =
- new ResourceLeakDetector(DnsMessage.class);
-
- private static final int SECTION_QUESTION = DnsSection.QUESTION.ordinal();
- private static final int SECTION_COUNT = 4;
-
- private final ResourceLeak leak = leakDetector.open(this);
- private short id;
- private DnsOpCode opCode;
- private boolean recursionDesired;
- private byte z;
-
- // To reduce the memory footprint of a message,
- // each of the following fields is a single record or a list of records.
- private Object questions;
- private Object answers;
- private Object authorities;
- private Object additionals;
-
- /**
- * Creates a new instance with the specified {@code id} and {@link DnsOpCode#QUERY} opCode.
- */
- protected AbstractDnsMessage(int id) {
- this(id, DnsOpCode.QUERY);
- }
-
- /**
- * Creates a new instance with the specified {@code id} and {@code opCode}.
- */
- protected AbstractDnsMessage(int id, DnsOpCode opCode) {
- setId(id);
- setOpCode(opCode);
- }
-
- @Override
- public int id() {
- return id & 0xFFFF;
- }
-
- @Override
- public DnsMessage setId(int id) {
- this.id = (short) id;
- return this;
- }
-
- @Override
- public DnsOpCode opCode() {
- return opCode;
- }
-
- @Override
- public DnsMessage setOpCode(DnsOpCode opCode) {
- this.opCode = checkNotNull(opCode, "opCode");
- return this;
- }
-
- @Override
- public boolean isRecursionDesired() {
- return recursionDesired;
- }
-
- @Override
- public DnsMessage setRecursionDesired(boolean recursionDesired) {
- this.recursionDesired = recursionDesired;
- return this;
- }
-
- @Override
- public int z() {
- return z;
- }
-
- @Override
- public DnsMessage setZ(int z) {
- this.z = (byte) (z & 7);
- return this;
- }
-
- @Override
- public int count(DnsSection section) {
- return count(sectionOrdinal(section));
- }
-
- private int count(int section) {
- final Object records = sectionAt(section);
- if (records == null) {
- return 0;
- }
- if (records instanceof DnsRecord) {
- return 1;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return recordList.size();
- }
-
- @Override
- public int count() {
- int count = 0;
- for (int i = 0; i < SECTION_COUNT; i ++) {
- count += count(i);
- }
- return count;
- }
-
- @Override
- public T recordAt(DnsSection section) {
- return recordAt(sectionOrdinal(section));
- }
-
- private T recordAt(int section) {
- final Object records = sectionAt(section);
- if (records == null) {
- return null;
- }
-
- if (records instanceof DnsRecord) {
- return castRecord(records);
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- if (recordList.isEmpty()) {
- return null;
- }
-
- return castRecord(recordList.get(0));
- }
-
- @Override
- public T recordAt(DnsSection section, int index) {
- return recordAt(sectionOrdinal(section), index);
- }
-
- private T recordAt(int section, int index) {
- final Object records = sectionAt(section);
- if (records == null) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
- }
-
- if (records instanceof DnsRecord) {
- if (index == 0) {
- return castRecord(records);
- } else {
- throw new IndexOutOfBoundsException("index: " + index + "' (expected: 0)");
- }
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return castRecord(recordList.get(index));
- }
-
- @Override
- public DnsMessage setRecord(DnsSection section, DnsRecord record) {
- setRecord(sectionOrdinal(section), record);
- return this;
- }
-
- private void setRecord(int section, DnsRecord record) {
- clear(section);
- setSection(section, checkQuestion(section, record));
- }
-
- @Override
- public T setRecord(DnsSection section, int index, DnsRecord record) {
- return setRecord(sectionOrdinal(section), index, record);
- }
-
- private T setRecord(int section, int index, DnsRecord record) {
- checkQuestion(section, record);
-
- final Object records = sectionAt(section);
- if (records == null) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
- }
-
- if (records instanceof DnsRecord) {
- if (index == 0) {
- setSection(section, record);
- return castRecord(records);
- } else {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
- }
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return castRecord(recordList.set(index, record));
- }
-
- @Override
- public DnsMessage addRecord(DnsSection section, DnsRecord record) {
- addRecord(sectionOrdinal(section), record);
- return this;
- }
-
- private void addRecord(int section, DnsRecord record) {
- checkQuestion(section, record);
-
- final Object records = sectionAt(section);
- if (records == null) {
- setSection(section, record);
- return;
- }
-
- if (records instanceof DnsRecord) {
- final List recordList = newRecordList();
- recordList.add(castRecord(records));
- recordList.add(record);
- setSection(section, recordList);
- return;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- recordList.add(record);
- }
-
- @Override
- public DnsMessage addRecord(DnsSection section, int index, DnsRecord record) {
- addRecord(sectionOrdinal(section), index, record);
- return this;
- }
-
- private void addRecord(int section, int index, DnsRecord record) {
- checkQuestion(section, record);
-
- final Object records = sectionAt(section);
- if (records == null) {
- if (index != 0) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
- }
-
- setSection(section, record);
- return;
- }
-
- if (records instanceof DnsRecord) {
- final List recordList;
- if (index == 0) {
- recordList = newRecordList();
- recordList.add(record);
- recordList.add(castRecord(records));
- } else if (index == 1) {
- recordList = newRecordList();
- recordList.add(castRecord(records));
- recordList.add(record);
- } else {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0 or 1)");
- }
- setSection(section, recordList);
- return;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- recordList.add(index, record);
- }
-
- @Override
- public T removeRecord(DnsSection section, int index) {
- return removeRecord(sectionOrdinal(section), index);
- }
-
- private T removeRecord(int section, int index) {
- final Object records = sectionAt(section);
- if (records == null) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
- }
-
- if (records instanceof DnsRecord) {
- if (index != 0) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
- }
-
- T record = castRecord(records);
- setSection(section, null);
- return record;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return castRecord(recordList.remove(index));
- }
-
- @Override
- public DnsMessage clear(DnsSection section) {
- clear(sectionOrdinal(section));
- return this;
- }
-
- @Override
- public DnsMessage clear() {
- for (int i = 0; i < SECTION_COUNT; i ++) {
- clear(i);
- }
- return this;
- }
-
- private void clear(int section) {
- final Object recordOrList = sectionAt(section);
- setSection(section, null);
- if (recordOrList instanceof ReferenceCounted) {
- ((ReferenceCounted) recordOrList).release();
- } else if (recordOrList instanceof List) {
- @SuppressWarnings("unchecked")
- List list = (List) recordOrList;
- if (!list.isEmpty()) {
- for (Object r : list) {
- ReferenceCountUtil.release(r);
- }
- }
- }
- }
-
- @Override
- public DnsMessage retain() {
- return (DnsMessage) super.retain();
- }
-
- @Override
- public DnsMessage retain(int increment) {
- return (DnsMessage) super.retain(increment);
- }
-
- @Override
- protected void deallocate() {
- clear();
-
- final ResourceLeak leak = this.leak;
- if (leak != null) {
- leak.close();
- }
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof DnsMessage)) {
- return false;
- }
-
- final DnsMessage that = (DnsMessage) obj;
- if (id() != that.id()) {
- return false;
- }
-
- if (this instanceof DnsQuery) {
- if (!(that instanceof DnsQuery)) {
- return false;
- }
- } else if (that instanceof DnsQuery) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return id() * 31 + (this instanceof DnsQuery? 0 : 1);
- }
-
- private Object sectionAt(int section) {
- switch (section) {
- case 0:
- return questions;
- case 1:
- return answers;
- case 2:
- return authorities;
- case 3:
- return additionals;
- }
-
- throw new Error(); // Should never reach here.
- }
-
- private void setSection(int section, Object value) {
- switch (section) {
- case 0:
- questions = value;
- return;
- case 1:
- answers = value;
- return;
- case 2:
- authorities = value;
- return;
- case 3:
- additionals = value;
- return;
- }
-
- throw new Error(); // Should never reach here.
- }
-
- private static int sectionOrdinal(DnsSection section) {
- return checkNotNull(section, "section").ordinal();
- }
-
- private static DnsRecord checkQuestion(int section, DnsRecord record) {
- if (section == SECTION_QUESTION && !(checkNotNull(record, "record") instanceof DnsQuestion)) {
- throw new IllegalArgumentException(
- "record: " + record + " (expected: " + StringUtil.simpleClassName(DnsQuestion.class) + ')');
- }
- return record;
- }
-
- @SuppressWarnings("unchecked")
- private static T castRecord(Object record) {
- return (T) record;
- }
-
- private static ArrayList newRecordList() {
- return new ArrayList(2);
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsRecord.java
deleted file mode 100644
index bf3cd685bd..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsRecord.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.util.internal.StringUtil;
-
-import java.net.IDN;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * A skeletal implementation of {@link DnsRecord}.
- */
-public abstract class AbstractDnsRecord implements DnsRecord {
-
- private final String name;
- private final DnsRecordType type;
- private final short dnsClass;
- private final long timeToLive;
- private int hashCode;
-
- /**
- * Creates a new {@link #CLASS_IN IN-class} record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param timeToLive the TTL value of the record
- */
- protected AbstractDnsRecord(String name, DnsRecordType type, long timeToLive) {
- this(name, type, CLASS_IN, timeToLive);
- }
-
- /**
- * Creates a new record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- * @param timeToLive the TTL value of the record
- */
- protected AbstractDnsRecord(String name, DnsRecordType type, int dnsClass, long timeToLive) {
- if (timeToLive < 0) {
- throw new IllegalArgumentException("timeToLive: " + timeToLive + " (expected: >= 0)");
- }
- // Convert to ASCII which will also check that the length is not too big.
- // See:
- // - https://github.com/netty/netty/issues/4937
- // - https://github.com/netty/netty/issues/4935
- this.name = appendTrailingDot(IDN.toASCII(checkNotNull(name, "name")));
- this.type = checkNotNull(type, "type");
- this.dnsClass = (short) dnsClass;
- this.timeToLive = timeToLive;
- }
-
- private static String appendTrailingDot(String name) {
- if (name.length() > 0 && name.charAt(name.length() - 1) != '.') {
- return name + '.';
- }
- return name;
- }
-
- @Override
- public String name() {
- return name;
- }
-
- @Override
- public DnsRecordType type() {
- return type;
- }
-
- @Override
- public int dnsClass() {
- return dnsClass & 0xFFFF;
- }
-
- @Override
- public long timeToLive() {
- return timeToLive;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof DnsRecord)) {
- return false;
- }
-
- final DnsRecord that = (DnsRecord) obj;
- final int hashCode = this.hashCode;
- if (hashCode != 0 && hashCode != that.hashCode()) {
- return false;
- }
-
- return type().intValue() == that.type().intValue() &&
- dnsClass() == that.dnsClass() &&
- name().equals(that.name());
- }
-
- @Override
- public int hashCode() {
- final int hashCode = this.hashCode;
- if (hashCode != 0) {
- return hashCode;
- }
-
- return this.hashCode = name.hashCode() * 31 + type().intValue() * 31 + dnsClass();
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder(64);
-
- buf.append(StringUtil.simpleClassName(this))
- .append('(')
- .append(name())
- .append(' ')
- .append(timeToLive())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type().name())
- .append(')');
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQuery.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQuery.java
deleted file mode 100644
index acd4810f6c..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQuery.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.channel.AddressedEnvelope;
-
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-/**
- * A {@link DnsQuery} implementation for UDP/IP.
- */
-public class DatagramDnsQuery extends DefaultDnsQuery
- implements AddressedEnvelope {
-
- private final InetSocketAddress sender;
- private final InetSocketAddress recipient;
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode}.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS query
- */
- public DatagramDnsQuery(
- InetSocketAddress sender, InetSocketAddress recipient, int id) {
- this(sender, recipient, id, DnsOpCode.QUERY);
- }
-
- /**
- * Creates a new instance.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS query
- * @param opCode the {@code opCode} of the DNS query
- */
- public DatagramDnsQuery(
- InetSocketAddress sender, InetSocketAddress recipient, int id, DnsOpCode opCode) {
- super(id, opCode);
-
- if (recipient == null && sender == null) {
- throw new NullPointerException("recipient and sender");
- }
-
- this.sender = sender;
- this.recipient = recipient;
- }
-
- @Override
- public DatagramDnsQuery content() {
- return this;
- }
-
- @Override
- public InetSocketAddress sender() {
- return sender;
- }
-
- @Override
- public InetSocketAddress recipient() {
- return recipient;
- }
-
- @Override
- public DatagramDnsQuery setId(int id) {
- return (DatagramDnsQuery) super.setId(id);
- }
-
- @Override
- public DatagramDnsQuery setOpCode(DnsOpCode opCode) {
- return (DatagramDnsQuery) super.setOpCode(opCode);
- }
-
- @Override
- public DatagramDnsQuery setRecursionDesired(boolean recursionDesired) {
- return (DatagramDnsQuery) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DatagramDnsQuery setZ(int z) {
- return (DatagramDnsQuery) super.setZ(z);
- }
-
- @Override
- public DatagramDnsQuery setRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsQuery) super.setRecord(section, record);
- }
-
- @Override
- public DatagramDnsQuery addRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsQuery) super.addRecord(section, record);
- }
-
- @Override
- public DatagramDnsQuery addRecord(DnsSection section, int index, DnsRecord record) {
- return (DatagramDnsQuery) super.addRecord(section, index, record);
- }
-
- @Override
- public DatagramDnsQuery clear(DnsSection section) {
- return (DatagramDnsQuery) super.clear(section);
- }
-
- @Override
- public DatagramDnsQuery clear() {
- return (DatagramDnsQuery) super.clear();
- }
-
- @Override
- public DatagramDnsQuery retain() {
- return (DatagramDnsQuery) super.retain();
- }
-
- @Override
- public DatagramDnsQuery retain(int increment) {
- return (DatagramDnsQuery) super.retain(increment);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!super.equals(obj)) {
- return false;
- }
-
- if (!(obj instanceof AddressedEnvelope)) {
- return false;
- }
-
- @SuppressWarnings("unchecked")
- final AddressedEnvelope, SocketAddress> that = (AddressedEnvelope, SocketAddress>) obj;
- if (sender() == null) {
- if (that.sender() != null) {
- return false;
- }
- } else if (!sender().equals(that.sender())) {
- return false;
- }
-
- if (recipient() == null) {
- if (that.recipient() != null) {
- return false;
- }
- } else if (!recipient().equals(that.recipient())) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int hashCode = super.hashCode();
- if (sender() != null) {
- hashCode = hashCode * 31 + sender().hashCode();
- }
- if (recipient() != null) {
- hashCode = hashCode * 31 + recipient().hashCode();
- }
- return hashCode;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryDecoder.java
deleted file mode 100644
index c932075572..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryDecoder.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.handler.codec.MessageToMessageDecoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Decodes a {@link DatagramPacket} into a {@link DatagramDnsQuery}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsQueryDecoder extends MessageToMessageDecoder {
-
- private final DnsRecordDecoder recordDecoder;
-
- /**
- * Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}.
- */
- public DatagramDnsQueryDecoder() {
- this(DnsRecordDecoder.DEFAULT);
- }
-
- /**
- * Creates a new decoder with the specified {@code recordDecoder}.
- */
- public DatagramDnsQueryDecoder(DnsRecordDecoder recordDecoder) {
- this.recordDecoder = checkNotNull(recordDecoder, "recordDecoder");
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List out) throws Exception {
- final ByteBuf buf = packet.content();
-
- final DnsQuery query = newQuery(packet, buf);
- boolean success = false;
- try {
- final int questionCount = buf.readUnsignedShort();
- final int answerCount = buf.readUnsignedShort();
- final int authorityRecordCount = buf.readUnsignedShort();
- final int additionalRecordCount = buf.readUnsignedShort();
-
- decodeQuestions(query, buf, questionCount);
- decodeRecords(query, DnsSection.ANSWER, buf, answerCount);
- decodeRecords(query, DnsSection.AUTHORITY, buf, authorityRecordCount);
- decodeRecords(query, DnsSection.ADDITIONAL, buf, additionalRecordCount);
-
- out.add(query);
- success = true;
- } finally {
- if (!success) {
- query.release();
- }
- }
- }
-
- private static DnsQuery newQuery(DatagramPacket packet, ByteBuf buf) {
- final int id = buf.readUnsignedShort();
-
- final int flags = buf.readUnsignedShort();
- if (flags >> 15 == 1) {
- throw new CorruptedFrameException("not a query");
- }
- final DnsQuery query =
- new DatagramDnsQuery(
- packet.sender(),
- packet.recipient(),
- id,
- DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)));
- query.setRecursionDesired((flags >> 8 & 1) == 1);
- query.setZ(flags >> 4 & 0x7);
- return query;
- }
-
- private void decodeQuestions(DnsQuery query, ByteBuf buf, int questionCount) throws Exception {
- for (int i = questionCount; i > 0; i--) {
- query.addRecord(DnsSection.QUESTION, recordDecoder.decodeQuestion(buf));
- }
- }
-
- private void decodeRecords(
- DnsQuery query, DnsSection section, ByteBuf buf, int count) throws Exception {
- for (int i = count; i > 0; i--) {
- final DnsRecord r = recordDecoder.decodeRecord(buf);
- if (r == null) {
- // Truncated response
- break;
- }
-
- query.addRecord(section, r);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryEncoder.java
deleted file mode 100644
index 8344801a45..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryEncoder.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.MessageToMessageEncoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Encodes a {@link DatagramDnsQuery} (or an {@link AddressedEnvelope} of {@link DnsQuery}} into a
- * {@link DatagramPacket}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsQueryEncoder extends MessageToMessageEncoder> {
-
- private final DnsRecordEncoder recordEncoder;
-
- /**
- * Creates a new encoder with {@linkplain DnsRecordEncoder#DEFAULT the default record encoder}.
- */
- public DatagramDnsQueryEncoder() {
- this(DnsRecordEncoder.DEFAULT);
- }
-
- /**
- * Creates a new encoder with the specified {@code recordEncoder}.
- */
- public DatagramDnsQueryEncoder(DnsRecordEncoder recordEncoder) {
- this.recordEncoder = checkNotNull(recordEncoder, "recordEncoder");
- }
-
- @Override
- protected void encode(
- ChannelHandlerContext ctx,
- AddressedEnvelope in, List out) throws Exception {
-
- final InetSocketAddress recipient = in.recipient();
- final DnsQuery query = in.content();
- final ByteBuf buf = allocateBuffer(ctx, in);
-
- boolean success = false;
- try {
- encodeHeader(query, buf);
- encodeQuestions(query, buf);
- encodeRecords(query, DnsSection.ADDITIONAL, buf);
- success = true;
- } finally {
- if (!success) {
- buf.release();
- }
- }
-
- out.add(new DatagramPacket(buf, recipient, null));
- }
-
- /**
- * Allocate a {@link ByteBuf} which will be used for constructing a datagram packet.
- * Sub-classes may override this method to return a {@link ByteBuf} with a perfect matching initial capacity.
- */
- protected ByteBuf allocateBuffer(
- ChannelHandlerContext ctx,
- @SuppressWarnings("unused") AddressedEnvelope msg) throws Exception {
- return ctx.alloc().ioBuffer(1024);
- }
-
- /**
- * Encodes the header that is always 12 bytes long.
- *
- * @param query the query header being encoded
- * @param buf the buffer the encoded data should be written to
- */
- private static void encodeHeader(DnsQuery query, ByteBuf buf) {
- buf.writeShort(query.id());
- int flags = 0;
- flags |= (query.opCode().byteValue() & 0xFF) << 14;
- if (query.isRecursionDesired()) {
- flags |= 1 << 8;
- }
- buf.writeShort(flags);
- buf.writeShort(query.count(DnsSection.QUESTION));
- buf.writeShort(0); // answerCount
- buf.writeShort(0); // authorityResourceCount
- buf.writeShort(query.count(DnsSection.ADDITIONAL));
- }
-
- private void encodeQuestions(DnsQuery query, ByteBuf buf) throws Exception {
- final int count = query.count(DnsSection.QUESTION);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeQuestion((DnsQuestion) query.recordAt(DnsSection.QUESTION, i), buf);
- }
- }
-
- private void encodeRecords(DnsQuery query, DnsSection section, ByteBuf buf) throws Exception {
- final int count = query.count(section);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeRecord(query.recordAt(section, i), buf);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponse.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponse.java
deleted file mode 100644
index 0c01970eda..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponse.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.channel.AddressedEnvelope;
-
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-/**
- * A {@link DnsResponse} implementation for UDP/IP.
- */
-public class DatagramDnsResponse extends DefaultDnsResponse
- implements AddressedEnvelope {
-
- private final InetSocketAddress sender;
- private final InetSocketAddress recipient;
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode} and
- * the {@link DnsResponseCode#NOERROR} {@code RCODE}.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS response
- */
- public DatagramDnsResponse(InetSocketAddress sender, InetSocketAddress recipient, int id) {
- this(sender, recipient, id, DnsOpCode.QUERY, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance with the {@link DnsResponseCode#NOERROR} responseCode.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- */
- public DatagramDnsResponse(InetSocketAddress sender, InetSocketAddress recipient, int id, DnsOpCode opCode) {
- this(sender, recipient, id, opCode, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- * @param responseCode the {@code RCODE} of the DNS response
- */
- public DatagramDnsResponse(
- InetSocketAddress sender, InetSocketAddress recipient,
- int id, DnsOpCode opCode, DnsResponseCode responseCode) {
- super(id, opCode, responseCode);
-
- if (recipient == null && sender == null) {
- throw new NullPointerException("recipient and sender");
- }
-
- this.sender = sender;
- this.recipient = recipient;
- }
-
- @Override
- public DatagramDnsResponse content() {
- return this;
- }
-
- @Override
- public InetSocketAddress sender() {
- return sender;
- }
-
- @Override
- public InetSocketAddress recipient() {
- return recipient;
- }
-
- @Override
- public DatagramDnsResponse setAuthoritativeAnswer(boolean authoritativeAnswer) {
- return (DatagramDnsResponse) super.setAuthoritativeAnswer(authoritativeAnswer);
- }
-
- @Override
- public DatagramDnsResponse setTruncated(boolean truncated) {
- return (DatagramDnsResponse) super.setTruncated(truncated);
- }
-
- @Override
- public DatagramDnsResponse setRecursionAvailable(boolean recursionAvailable) {
- return (DatagramDnsResponse) super.setRecursionAvailable(recursionAvailable);
- }
-
- @Override
- public DatagramDnsResponse setCode(DnsResponseCode code) {
- return (DatagramDnsResponse) super.setCode(code);
- }
-
- @Override
- public DatagramDnsResponse setId(int id) {
- return (DatagramDnsResponse) super.setId(id);
- }
-
- @Override
- public DatagramDnsResponse setOpCode(DnsOpCode opCode) {
- return (DatagramDnsResponse) super.setOpCode(opCode);
- }
-
- @Override
- public DatagramDnsResponse setRecursionDesired(boolean recursionDesired) {
- return (DatagramDnsResponse) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DatagramDnsResponse setZ(int z) {
- return (DatagramDnsResponse) super.setZ(z);
- }
-
- @Override
- public DatagramDnsResponse setRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsResponse) super.setRecord(section, record);
- }
-
- @Override
- public DatagramDnsResponse addRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsResponse) super.addRecord(section, record);
- }
-
- @Override
- public DatagramDnsResponse addRecord(DnsSection section, int index, DnsRecord record) {
- return (DatagramDnsResponse) super.addRecord(section, index, record);
- }
-
- @Override
- public DatagramDnsResponse clear(DnsSection section) {
- return (DatagramDnsResponse) super.clear(section);
- }
-
- @Override
- public DatagramDnsResponse clear() {
- return (DatagramDnsResponse) super.clear();
- }
-
- @Override
- public DatagramDnsResponse retain() {
- return (DatagramDnsResponse) super.retain();
- }
-
- @Override
- public DatagramDnsResponse retain(int increment) {
- return (DatagramDnsResponse) super.retain(increment);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!super.equals(obj)) {
- return false;
- }
-
- if (!(obj instanceof AddressedEnvelope)) {
- return false;
- }
-
- @SuppressWarnings("unchecked")
- final AddressedEnvelope, SocketAddress> that = (AddressedEnvelope, SocketAddress>) obj;
- if (sender() == null) {
- if (that.sender() != null) {
- return false;
- }
- } else if (!sender().equals(that.sender())) {
- return false;
- }
-
- if (recipient() == null) {
- if (that.recipient() != null) {
- return false;
- }
- } else if (!recipient().equals(that.recipient())) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int hashCode = super.hashCode();
- if (sender() != null) {
- hashCode = hashCode * 31 + sender().hashCode();
- }
- if (recipient() != null) {
- hashCode = hashCode * 31 + recipient().hashCode();
- }
- return hashCode;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseDecoder.java
deleted file mode 100644
index c9e879a47f..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseDecoder.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.handler.codec.MessageToMessageDecoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Decodes a {@link DatagramPacket} into a {@link DatagramDnsResponse}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsResponseDecoder extends MessageToMessageDecoder {
-
- private final DnsRecordDecoder recordDecoder;
-
- /**
- * Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}.
- */
- public DatagramDnsResponseDecoder() {
- this(DnsRecordDecoder.DEFAULT);
- }
-
- /**
- * Creates a new decoder with the specified {@code recordDecoder}.
- */
- public DatagramDnsResponseDecoder(DnsRecordDecoder recordDecoder) {
- this.recordDecoder = checkNotNull(recordDecoder, "recordDecoder");
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List out) throws Exception {
- final ByteBuf buf = packet.content();
-
- final DnsResponse response = newResponse(packet, buf);
- boolean success = false;
- try {
- final int questionCount = buf.readUnsignedShort();
- final int answerCount = buf.readUnsignedShort();
- final int authorityRecordCount = buf.readUnsignedShort();
- final int additionalRecordCount = buf.readUnsignedShort();
-
- decodeQuestions(response, buf, questionCount);
- decodeRecords(response, DnsSection.ANSWER, buf, answerCount);
- decodeRecords(response, DnsSection.AUTHORITY, buf, authorityRecordCount);
- decodeRecords(response, DnsSection.ADDITIONAL, buf, additionalRecordCount);
-
- out.add(response);
- success = true;
- } finally {
- if (!success) {
- response.release();
- }
- }
- }
-
- private static DnsResponse newResponse(DatagramPacket packet, ByteBuf buf) {
- final int id = buf.readUnsignedShort();
-
- final int flags = buf.readUnsignedShort();
- if (flags >> 15 == 0) {
- throw new CorruptedFrameException("not a response");
- }
-
- final DnsResponse response = new DatagramDnsResponse(
- packet.sender(),
- packet.recipient(),
- id,
- DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)), DnsResponseCode.valueOf((byte) (flags & 0xf)));
-
- response.setRecursionDesired((flags >> 8 & 1) == 1);
- response.setAuthoritativeAnswer((flags >> 10 & 1) == 1);
- response.setTruncated((flags >> 9 & 1) == 1);
- response.setRecursionAvailable((flags >> 7 & 1) == 1);
- response.setZ(flags >> 4 & 0x7);
- return response;
- }
-
- private void decodeQuestions(DnsResponse response, ByteBuf buf, int questionCount) throws Exception {
- for (int i = questionCount; i > 0; i --) {
- response.addRecord(DnsSection.QUESTION, recordDecoder.decodeQuestion(buf));
- }
- }
-
- private void decodeRecords(
- DnsResponse response, DnsSection section, ByteBuf buf, int count) throws Exception {
- for (int i = count; i > 0; i --) {
- final DnsRecord r = recordDecoder.decodeRecord(buf);
- if (r == null) {
- // Truncated response
- break;
- }
-
- response.addRecord(section, r);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseEncoder.java
deleted file mode 100644
index ac7d909156..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseEncoder.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.MessageToMessageEncoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Encodes a {@link DatagramDnsResponse} (or an {@link AddressedEnvelope} of {@link DnsResponse}} into a
- * {@link DatagramPacket}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsResponseEncoder
- extends MessageToMessageEncoder> {
-
- private final DnsRecordEncoder recordEncoder;
-
- /**
- * Creates a new encoder with {@linkplain DnsRecordEncoder#DEFAULT the default record encoder}.
- */
- public DatagramDnsResponseEncoder() {
- this(DnsRecordEncoder.DEFAULT);
- }
-
- /**
- * Creates a new encoder with the specified {@code recordEncoder}.
- */
- public DatagramDnsResponseEncoder(DnsRecordEncoder recordEncoder) {
- this.recordEncoder = checkNotNull(recordEncoder, "recordEncoder");
- }
-
- @Override
- protected void encode(ChannelHandlerContext ctx,
- AddressedEnvelope in, List out) throws Exception {
-
- final InetSocketAddress recipient = in.recipient();
- final DnsResponse response = in.content();
- final ByteBuf buf = allocateBuffer(ctx, in);
-
- boolean success = false;
- try {
- encodeHeader(response, buf);
- encodeQuestions(response, buf);
- encodeRecords(response, DnsSection.ANSWER, buf);
- encodeRecords(response, DnsSection.AUTHORITY, buf);
- encodeRecords(response, DnsSection.ADDITIONAL, buf);
- success = true;
- } finally {
- if (!success) {
- buf.release();
- }
- }
-
- out.add(new DatagramPacket(buf, recipient, null));
- }
-
- /**
- * Allocate a {@link ByteBuf} which will be used for constructing a datagram packet.
- * Sub-classes may override this method to return a {@link ByteBuf} with a perfect matching initial capacity.
- */
- protected ByteBuf allocateBuffer(
- ChannelHandlerContext ctx,
- @SuppressWarnings("unused") AddressedEnvelope msg) throws Exception {
- return ctx.alloc().ioBuffer(1024);
- }
-
- /**
- * Encodes the header that is always 12 bytes long.
- *
- * @param response the response header being encoded
- * @param buf the buffer the encoded data should be written to
- */
- private static void encodeHeader(DnsResponse response, ByteBuf buf) {
- buf.writeShort(response.id());
- int flags = 32768;
- flags |= (response.opCode().byteValue() & 0xFF) << 11;
- if (response.isAuthoritativeAnswer()) {
- flags |= 1 << 10;
- }
- if (response.isTruncated()) {
- flags |= 1 << 9;
- }
- if (response.isRecursionDesired()) {
- flags |= 1 << 8;
- }
- if (response.isRecursionAvailable()) {
- flags |= 1 << 7;
- }
- flags |= response.z() << 4;
- flags |= response.code().intValue();
- buf.writeShort(flags);
- buf.writeShort(response.count(DnsSection.QUESTION));
- buf.writeShort(response.count(DnsSection.ANSWER));
- buf.writeShort(response.count(DnsSection.AUTHORITY));
- buf.writeShort(response.count(DnsSection.ADDITIONAL));
- }
-
- private void encodeQuestions(DnsResponse response, ByteBuf buf) throws Exception {
- final int count = response.count(DnsSection.QUESTION);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeQuestion((DnsQuestion) response.recordAt(DnsSection.QUESTION, i), buf);
- }
- }
-
- private void encodeRecords(DnsResponse response, DnsSection section, ByteBuf buf) throws Exception {
- final int count = response.count(section);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeRecord(response.recordAt(section, i), buf);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsPtrRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsPtrRecord.java
deleted file mode 100644
index 517c5f9570..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsPtrRecord.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-import io.netty.util.internal.StringUtil;
-
-public class DefaultDnsPtrRecord extends AbstractDnsRecord implements DnsPtrRecord {
-
- private final String hostname;
-
- /**
- * Creates a new PTR record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- * @param timeToLive the TTL value of the record
- * @param hostname the hostname this PTR record resolves to.
- */
- public DefaultDnsPtrRecord(
- String name, int dnsClass, long timeToLive, String hostname) {
- super(name, DnsRecordType.PTR, dnsClass, timeToLive);
- this.hostname = checkNotNull(hostname, "hostname");
- }
-
- @Override
- public String hostname() {
- return hostname;
- }
-
- @Override
- public String toString() {
- final StringBuilder buf = new StringBuilder(64).append(StringUtil.simpleClassName(this)).append('(');
- final DnsRecordType type = type();
- buf.append(name().isEmpty()? "" : name())
- .append(' ')
- .append(timeToLive())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type.name());
-
- buf.append(' ')
- .append(hostname);
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuery.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuery.java
deleted file mode 100644
index 93920ad8f0..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuery.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-/**
- * The default {@link DnsQuery} implementation.
- */
-public class DefaultDnsQuery extends AbstractDnsMessage implements DnsQuery {
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode}.
- *
- * @param id the {@code ID} of the DNS query
- */
- public DefaultDnsQuery(int id) {
- super(id);
- }
-
- /**
- * Creates a new instance.
- *
- * @param id the {@code ID} of the DNS query
- * @param opCode the {@code opCode} of the DNS query
- */
- public DefaultDnsQuery(int id, DnsOpCode opCode) {
- super(id, opCode);
- }
-
- @Override
- public DnsQuery setId(int id) {
- return (DnsQuery) super.setId(id);
- }
-
- @Override
- public DnsQuery setOpCode(DnsOpCode opCode) {
- return (DnsQuery) super.setOpCode(opCode);
- }
-
- @Override
- public DnsQuery setRecursionDesired(boolean recursionDesired) {
- return (DnsQuery) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DnsQuery setZ(int z) {
- return (DnsQuery) super.setZ(z);
- }
-
- @Override
- public DnsQuery setRecord(DnsSection section, DnsRecord record) {
- return (DnsQuery) super.setRecord(section, record);
- }
-
- @Override
- public DnsQuery addRecord(DnsSection section, DnsRecord record) {
- return (DnsQuery) super.addRecord(section, record);
- }
-
- @Override
- public DnsQuery addRecord(DnsSection section, int index, DnsRecord record) {
- return (DnsQuery) super.addRecord(section, index, record);
- }
-
- @Override
- public DnsQuery clear(DnsSection section) {
- return (DnsQuery) super.clear(section);
- }
-
- @Override
- public DnsQuery clear() {
- return (DnsQuery) super.clear();
- }
-
- @Override
- public DnsQuery retain() {
- return (DnsQuery) super.retain();
- }
-
- @Override
- public DnsQuery retain(int increment) {
- return (DnsQuery) super.retain(increment);
- }
-
- @Override
- public String toString() {
- return DnsMessageUtil.appendQuery(new StringBuilder(128), this).toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuestion.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuestion.java
deleted file mode 100644
index 09ceb1e62c..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuestion.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.util.internal.StringUtil;
-
-/**
- * The default {@link DnsQuestion} implementation.
- */
-public class DefaultDnsQuestion extends AbstractDnsRecord implements DnsQuestion {
-
- /**
- * Creates a new {@link #CLASS_IN IN-class} question.
- *
- * @param name the domain name of the DNS question
- * @param type the type of the DNS question
- */
- public DefaultDnsQuestion(String name, DnsRecordType type) {
- super(name, type, 0);
- }
-
- /**
- * Creates a new question.
- *
- * @param name the domain name of the DNS question
- * @param type the type of the DNS question
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- */
- public DefaultDnsQuestion(String name, DnsRecordType type, int dnsClass) {
- super(name, type, dnsClass, 0);
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder(64);
-
- buf.append(StringUtil.simpleClassName(this))
- .append('(')
- .append(name())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type().name())
- .append(')');
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRawRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRawRecord.java
deleted file mode 100644
index f37b7ba880..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRawRecord.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.util.internal.StringUtil;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The default {@code DnsRawRecord} implementation.
- */
-public class DefaultDnsRawRecord extends AbstractDnsRecord implements DnsRawRecord {
-
- private final ByteBuf content;
-
- /**
- * Creates a new {@link #CLASS_IN IN-class} record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param timeToLive the TTL value of the record
- */
- public DefaultDnsRawRecord(String name, DnsRecordType type, long timeToLive, ByteBuf content) {
- this(name, type, DnsRecord.CLASS_IN, timeToLive, content);
- }
-
- /**
- * Creates a new record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- * @param timeToLive the TTL value of the record
- */
- public DefaultDnsRawRecord(
- String name, DnsRecordType type, int dnsClass, long timeToLive, ByteBuf content) {
- super(name, type, dnsClass, timeToLive);
- this.content = checkNotNull(content, "content");
- }
-
- @Override
- public ByteBuf content() {
- return content;
- }
-
- @Override
- public DnsRawRecord copy() {
- return new DefaultDnsRawRecord(name(), type(), dnsClass(), timeToLive(), content().copy());
- }
-
- @Override
- public DnsRawRecord duplicate() {
- return new DefaultDnsRawRecord(name(), type(), dnsClass(), timeToLive(), content().duplicate());
- }
-
- @Override
- public int refCnt() {
- return content().refCnt();
- }
-
- @Override
- public DnsRawRecord retain() {
- content().retain();
- return this;
- }
-
- @Override
- public DnsRawRecord retain(int increment) {
- content().retain(increment);
- return this;
- }
-
- @Override
- public boolean release() {
- return content().release();
- }
-
- @Override
- public boolean release(int decrement) {
- return content().release(decrement);
- }
-
- @Override
- public String toString() {
- final StringBuilder buf = new StringBuilder(64).append(StringUtil.simpleClassName(this)).append('(');
- final DnsRecordType type = type();
- if (type != DnsRecordType.OPT) {
- buf.append(name().isEmpty()? "" : name())
- .append(' ')
- .append(timeToLive())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type.name());
- } else {
- buf.append("OPT flags:")
- .append(timeToLive())
- .append(" udp:")
- .append(dnsClass());
- }
-
- buf.append(' ')
- .append(content().readableBytes())
- .append("B)");
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoder.java
deleted file mode 100644
index 1a733f437d..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoder.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.util.CharsetUtil;
-
-/**
- * The default {@link DnsRecordDecoder} implementation.
- *
- * @see DefaultDnsRecordEncoder
- */
-public class DefaultDnsRecordDecoder implements DnsRecordDecoder {
-
- static final String ROOT = ".";
-
- /**
- * Creates a new instance.
- */
- protected DefaultDnsRecordDecoder() { }
-
- @Override
- public final DnsQuestion decodeQuestion(ByteBuf in) throws Exception {
- String name = decodeName(in);
- DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort());
- int qClass = in.readUnsignedShort();
- return new DefaultDnsQuestion(name, type, qClass);
- }
-
- @Override
- public final T decodeRecord(ByteBuf in) throws Exception {
- final int startOffset = in.readerIndex();
- final String name = decodeName(in);
-
- final int endOffset = in.writerIndex();
- if (endOffset - startOffset < 10) {
- // Not enough data
- in.readerIndex(startOffset);
- return null;
- }
-
- final DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort());
- final int aClass = in.readUnsignedShort();
- final long ttl = in.readUnsignedInt();
- final int length = in.readUnsignedShort();
- final int offset = in.readerIndex();
-
- if (endOffset - offset < length) {
- // Not enough data
- in.readerIndex(startOffset);
- return null;
- }
-
- @SuppressWarnings("unchecked")
- T record = (T) decodeRecord(name, type, aClass, ttl, in, offset, length);
- in.readerIndex(offset + length);
- return record;
- }
-
- /**
- * Decodes a record from the information decoded so far by {@link #decodeRecord(ByteBuf)}.
- *
- * @param name the domain name of the record
- * @param type the type of the record
- * @param dnsClass the class of the record
- * @param timeToLive the TTL of the record
- * @param in the {@link ByteBuf} that contains the RDATA
- * @param offset the start offset of the RDATA in {@code in}
- * @param length the length of the RDATA
- *
- * @return a {@link DnsRawRecord}. Override this method to decode RDATA and return other record implementation.
- */
- protected DnsRecord decodeRecord(
- String name, DnsRecordType type, int dnsClass, long timeToLive,
- ByteBuf in, int offset, int length) throws Exception {
-
- // DNS message compression means that domain names may contain "pointers" to other positions in the packet
- // to build a full message. This means the indexes are meaningful and we need the ability to reference the
- // indexes un-obstructed, and thus we cannot use a slice here.
- // See https://www.ietf.org/rfc/rfc1035 [4.1.4. Message compression]
- if (type == DnsRecordType.PTR) {
- in.setIndex(offset, offset + length);
- return new DefaultDnsPtrRecord(
- name, dnsClass, timeToLive, decodeName0(in.duplicate().setIndex(offset, offset + length)));
- }
- return new DefaultDnsRawRecord(
- name, type, dnsClass, timeToLive, in.duplicate().setIndex(offset, offset + length).retain());
- }
-
- /**
- * Retrieves a domain name given a buffer containing a DNS packet. If the
- * name contains a pointer, the position of the buffer will be set to
- * directly after the pointer's index after the name has been read.
- *
- * @param in the byte buffer containing the DNS packet
- * @return the domain name for an entry
- */
- protected String decodeName0(ByteBuf in) {
- return decodeName(in);
- }
-
- /**
- * Retrieves a domain name given a buffer containing a DNS packet. If the
- * name contains a pointer, the position of the buffer will be set to
- * directly after the pointer's index after the name has been read.
- *
- * @param in the byte buffer containing the DNS packet
- * @return the domain name for an entry
- */
- public static String decodeName(ByteBuf in) {
- int position = -1;
- int checked = 0;
- final int end = in.writerIndex();
- final int readable = in.readableBytes();
-
- // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems
- // some servers do not respect this for empty names. So just workaround this and return an empty name in this
- // case.
- //
- // See:
- // - https://github.com/netty/netty/issues/5014
- // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1
- if (readable == 0) {
- return ROOT;
- }
-
- final StringBuilder name = new StringBuilder(readable << 1);
- while (in.isReadable()) {
- final int len = in.readUnsignedByte();
- final boolean pointer = (len & 0xc0) == 0xc0;
- if (pointer) {
- if (position == -1) {
- position = in.readerIndex() + 1;
- }
-
- if (!in.isReadable()) {
- throw new CorruptedFrameException("truncated pointer in a name");
- }
-
- final int next = (len & 0x3f) << 8 | in.readUnsignedByte();
- if (next >= end) {
- throw new CorruptedFrameException("name has an out-of-range pointer");
- }
- in.readerIndex(next);
-
- // check for loops
- checked += 2;
- if (checked >= end) {
- throw new CorruptedFrameException("name contains a loop.");
- }
- } else if (len != 0) {
- if (!in.isReadable(len)) {
- throw new CorruptedFrameException("truncated label in a name");
- }
- name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
- in.skipBytes(len);
- } else { // len == 0
- break;
- }
- }
-
- if (position != -1) {
- in.readerIndex(position);
- }
-
- if (name.length() == 0) {
- return ROOT;
- }
-
- if (name.charAt(name.length() - 1) != '.') {
- name.append('.');
- }
-
- return name.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
deleted file mode 100644
index 2eb61a4444..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufUtil;
-import io.netty.handler.codec.UnsupportedMessageTypeException;
-import io.netty.util.internal.StringUtil;
-
-import static io.netty.handler.codec.dns.DefaultDnsRecordDecoder.ROOT;
-
-/**
- * The default {@link DnsRecordEncoder} implementation.
- *
- * @see DefaultDnsRecordDecoder
- */
-public class DefaultDnsRecordEncoder implements DnsRecordEncoder {
-
- /**
- * Creates a new instance.
- */
- protected DefaultDnsRecordEncoder() { }
-
- @Override
- public final void encodeQuestion(DnsQuestion question, ByteBuf out) throws Exception {
- encodeName(question.name(), out);
- out.writeShort(question.type().intValue());
- out.writeShort(question.dnsClass());
- }
-
- @Override
- public void encodeRecord(DnsRecord record, ByteBuf out) throws Exception {
- if (record instanceof DnsQuestion) {
- encodeQuestion((DnsQuestion) record, out);
- } else if (record instanceof DnsPtrRecord) {
- encodePtrRecord((DnsPtrRecord) record, out);
- } else if (record instanceof DnsRawRecord) {
- encodeRawRecord((DnsRawRecord) record, out);
- } else {
- throw new UnsupportedMessageTypeException(StringUtil.simpleClassName(record));
- }
- }
-
- private void encodePtrRecord(DnsPtrRecord record, ByteBuf out) throws Exception {
- encodeName(record.name(), out);
-
- out.writeShort(record.type().intValue());
- out.writeShort(record.dnsClass());
- out.writeInt((int) record.timeToLive());
-
- encodeName(record.hostname(), out);
- }
-
- private void encodeRawRecord(DnsRawRecord record, ByteBuf out) throws Exception {
- encodeName(record.name(), out);
-
- out.writeShort(record.type().intValue());
- out.writeShort(record.dnsClass());
- out.writeInt((int) record.timeToLive());
-
- ByteBuf content = record.content();
- int contentLen = content.readableBytes();
-
- out.writeShort(contentLen);
- out.writeBytes(content, content.readerIndex(), contentLen);
- }
-
- protected void encodeName(String name, ByteBuf buf) throws Exception {
- if (ROOT.equals(name)) {
- // Root domain
- buf.writeByte(0);
- return;
- }
-
- final String[] labels = name.split("\\.");
- for (String label : labels) {
- final int labelLen = label.length();
- if (labelLen == 0) {
- // zero-length label means the end of the name.
- break;
- }
-
- buf.writeByte(labelLen);
- ByteBufUtil.writeAscii(buf, label);
- }
-
- buf.writeByte(0); // marks end of name field
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsResponse.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsResponse.java
deleted file mode 100644
index 5832aa755a..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsResponse.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The default {@link DnsResponse} implementation.
- */
-public class DefaultDnsResponse extends AbstractDnsMessage implements DnsResponse {
-
- private boolean authoritativeAnswer;
- private boolean truncated;
- private boolean recursionAvailable;
- private DnsResponseCode code;
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode} and
- * the {@link DnsResponseCode#NOERROR} {@code RCODE}.
- *
- * @param id the {@code ID} of the DNS response
- */
- public DefaultDnsResponse(int id) {
- this(id, DnsOpCode.QUERY, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance with the {@link DnsResponseCode#NOERROR} {@code RCODE}.
- *
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- */
- public DefaultDnsResponse(int id, DnsOpCode opCode) {
- this(id, opCode, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance.
- *
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- * @param code the {@code RCODE} of the DNS response
- */
- public DefaultDnsResponse(int id, DnsOpCode opCode, DnsResponseCode code) {
- super(id, opCode);
- setCode(code);
- }
-
- @Override
- public boolean isAuthoritativeAnswer() {
- return authoritativeAnswer;
- }
-
- @Override
- public DnsResponse setAuthoritativeAnswer(boolean authoritativeAnswer) {
- this.authoritativeAnswer = authoritativeAnswer;
- return this;
- }
-
- @Override
- public boolean isTruncated() {
- return truncated;
- }
-
- @Override
- public DnsResponse setTruncated(boolean truncated) {
- this.truncated = truncated;
- return this;
- }
-
- @Override
- public boolean isRecursionAvailable() {
- return recursionAvailable;
- }
-
- @Override
- public DnsResponse setRecursionAvailable(boolean recursionAvailable) {
- this.recursionAvailable = recursionAvailable;
- return this;
- }
-
- @Override
- public DnsResponseCode code() {
- return code;
- }
-
- @Override
- public DnsResponse setCode(DnsResponseCode code) {
- this.code = checkNotNull(code, "code");
- return this;
- }
-
- @Override
- public DnsResponse setId(int id) {
- return (DnsResponse) super.setId(id);
- }
-
- @Override
- public DnsResponse setOpCode(DnsOpCode opCode) {
- return (DnsResponse) super.setOpCode(opCode);
- }
-
- @Override
- public DnsResponse setRecursionDesired(boolean recursionDesired) {
- return (DnsResponse) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DnsResponse setZ(int z) {
- return (DnsResponse) super.setZ(z);
- }
-
- @Override
- public DnsResponse setRecord(DnsSection section, DnsRecord record) {
- return (DnsResponse) super.setRecord(section, record);
- }
-
- @Override
- public DnsResponse addRecord(DnsSection section, DnsRecord record) {
- return (DnsResponse) super.addRecord(section, record);
- }
-
- @Override
- public DnsResponse addRecord(DnsSection section, int index, DnsRecord record) {
- return (DnsResponse) super.addRecord(section, index, record);
- }
-
- @Override
- public DnsResponse clear(DnsSection section) {
- return (DnsResponse) super.clear(section);
- }
-
- @Override
- public DnsResponse clear() {
- return (DnsResponse) super.clear();
- }
-
- @Override
- public DnsResponse retain() {
- return (DnsResponse) super.retain();
- }
-
- @Override
- public DnsResponse retain(int increment) {
- return (DnsResponse) super.retain(increment);
- }
-
- @Override
- public String toString() {
- return DnsMessageUtil.appendResponse(new StringBuilder(128), this).toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessage.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessage.java
deleted file mode 100644
index 268e56a2b6..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessage.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.util.ReferenceCounted;
-
-/**
- * The superclass which contains core information concerning a {@link DnsQuery} and a {@link DnsResponse}.
- */
-public interface DnsMessage extends ReferenceCounted {
-
- /**
- * Returns the {@code ID} of this DNS message.
- */
- int id();
-
- /**
- * Sets the {@code ID} of this DNS message.
- */
- DnsMessage setId(int id);
-
- /**
- * Returns the {@code opCode} of this DNS message.
- */
- DnsOpCode opCode();
-
- /**
- * Sets the {@code opCode} of this DNS message.
- */
- DnsMessage setOpCode(DnsOpCode opCode);
-
- /**
- * Returns the {@code RD} (recursion desired} field of this DNS message.
- */
- boolean isRecursionDesired();
-
- /**
- * Sets the {@code RD} (recursion desired} field of this DNS message.
- */
- DnsMessage setRecursionDesired(boolean recursionDesired);
-
- /**
- * Returns the {@code Z} (reserved for future use) field of this DNS message.
- */
- int z();
-
- /**
- * Sets the {@code Z} (reserved for future use) field of this DNS message.
- */
- DnsMessage setZ(int z);
-
- /**
- * Returns the number of records in the specified {@code section} of this DNS message.
- */
- int count(DnsSection section);
-
- /**
- * Returns the number of records in this DNS message.
- */
- int count();
-
- /**
- * Returns the first record in the specified {@code section} of this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the type of the returned record is
- * always {@link DnsQuestion}.
- *
- * @return {@code null} if this message doesn't have any records in the specified {@code section}
- */
- T recordAt(DnsSection section);
-
- /**
- * Returns the record at the specified {@code index} of the specified {@code section} of this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the type of the returned record is
- * always {@link DnsQuestion}.
- *
- * @throws IndexOutOfBoundsException if the specified {@code index} is out of bounds
- */
- T recordAt(DnsSection section, int index);
-
- /**
- * Sets the specified {@code section} of this DNS message to the specified {@code record},
- * making it a single-record section. When the specified {@code section} is {@link DnsSection#QUESTION},
- * the specified {@code record} must be a {@link DnsQuestion}.
- */
- DnsMessage setRecord(DnsSection section, DnsRecord record);
-
- /**
- * Sets the specified {@code record} at the specified {@code index} of the specified {@code section}
- * of this DNS message. When the specified {@code section} is {@link DnsSection#QUESTION},
- * the specified {@code record} must be a {@link DnsQuestion}.
- *
- * @return the old record
- * @throws IndexOutOfBoundsException if the specified {@code index} is out of bounds
- */
- T setRecord(DnsSection section, int index, DnsRecord record);
-
- /**
- * Adds the specified {@code record} at the end of the specified {@code section} of this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the specified {@code record}
- * must be a {@link DnsQuestion}.
- */
- DnsMessage addRecord(DnsSection section, DnsRecord record);
-
- /**
- * Adds the specified {@code record} at the specified {@code index} of the specified {@code section}
- * of this DNS message. When the specified {@code section} is {@link DnsSection#QUESTION}, the specified
- * {@code record} must be a {@link DnsQuestion}.
- *
- * @throws IndexOutOfBoundsException if the specified {@code index} is out of bounds
- */
- DnsMessage addRecord(DnsSection section, int index, DnsRecord record);
-
- /**
- * Removes the record at the specified {@code index} of the specified {@code section} from this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the type of the returned record is
- * always {@link DnsQuestion}.
- *
- * @return the removed record
- */
- T removeRecord(DnsSection section, int index);
-
- /**
- * Removes all the records in the specified {@code section} of this DNS message.
- */
- DnsMessage clear(DnsSection section);
-
- /**
- * Removes all the records in this DNS message.
- */
- DnsMessage clear();
-
- @Override
- DnsMessage retain();
-
- @Override
- DnsMessage retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java
deleted file mode 100644
index 8a059949d8..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.channel.AddressedEnvelope;
-import io.netty.util.internal.StringUtil;
-
-import java.net.SocketAddress;
-
-/**
- * Provides some utility methods for DNS message implementations.
- */
-final class DnsMessageUtil {
-
- static StringBuilder appendQuery(StringBuilder buf, DnsQuery query) {
- appendQueryHeader(buf, query);
- appendAllRecords(buf, query);
- return buf;
- }
-
- static StringBuilder appendResponse(StringBuilder buf, DnsResponse response) {
- appendResponseHeader(buf, response);
- appendAllRecords(buf, response);
- return buf;
- }
-
- static StringBuilder appendRecordClass(StringBuilder buf, int dnsClass) {
- final String name;
- switch (dnsClass &= 0xFFFF) {
- case DnsRecord.CLASS_IN:
- name = "IN";
- break;
- case DnsRecord.CLASS_CSNET:
- name = "CSNET";
- break;
- case DnsRecord.CLASS_CHAOS:
- name = "CHAOS";
- break;
- case DnsRecord.CLASS_HESIOD:
- name = "HESIOD";
- break;
- case DnsRecord.CLASS_NONE:
- name = "NONE";
- break;
- case DnsRecord.CLASS_ANY:
- name = "ANY";
- break;
- default:
- name = null;
- break;
- }
-
- if (name != null) {
- buf.append(name);
- } else {
- buf.append("UNKNOWN(").append(dnsClass).append(')');
- }
-
- return buf;
- }
-
- private static void appendQueryHeader(StringBuilder buf, DnsQuery msg) {
- buf.append(StringUtil.simpleClassName(msg))
- .append('(');
-
- appendAddresses(buf, msg)
- .append(msg.id())
- .append(", ")
- .append(msg.opCode());
-
- if (msg.isRecursionDesired()) {
- buf.append(", RD");
- }
- if (msg.z() != 0) {
- buf.append(", Z: ")
- .append(msg.z());
- }
- buf.append(')');
- }
-
- private static void appendResponseHeader(StringBuilder buf, DnsResponse msg) {
- buf.append(StringUtil.simpleClassName(msg))
- .append('(');
-
- appendAddresses(buf, msg)
- .append(msg.id())
- .append(", ")
- .append(msg.opCode())
- .append(", ")
- .append(msg.code())
- .append(',');
-
- boolean hasComma = true;
- if (msg.isRecursionDesired()) {
- hasComma = false;
- buf.append(" RD");
- }
- if (msg.isAuthoritativeAnswer()) {
- hasComma = false;
- buf.append(" AA");
- }
- if (msg.isTruncated()) {
- hasComma = false;
- buf.append(" TC");
- }
- if (msg.isRecursionAvailable()) {
- hasComma = false;
- buf.append(" RA");
- }
- if (msg.z() != 0) {
- if (!hasComma) {
- buf.append(',');
- }
- buf.append(" Z: ")
- .append(msg.z());
- }
-
- if (hasComma) {
- buf.setCharAt(buf.length() - 1, ')');
- } else {
- buf.append(')');
- }
- }
-
- private static StringBuilder appendAddresses(StringBuilder buf, DnsMessage msg) {
-
- if (!(msg instanceof AddressedEnvelope)) {
- return buf;
- }
-
- @SuppressWarnings("unchecked")
- AddressedEnvelope, SocketAddress> envelope = (AddressedEnvelope, SocketAddress>) msg;
-
- SocketAddress addr = envelope.sender();
- if (addr != null) {
- buf.append("from: ")
- .append(addr)
- .append(", ");
- }
-
- addr = envelope.recipient();
- if (addr != null) {
- buf.append("to: ")
- .append(addr)
- .append(", ");
- }
-
- return buf;
- }
-
- private static void appendAllRecords(StringBuilder buf, DnsMessage msg) {
- appendRecords(buf, msg, DnsSection.QUESTION);
- appendRecords(buf, msg, DnsSection.ANSWER);
- appendRecords(buf, msg, DnsSection.AUTHORITY);
- appendRecords(buf, msg, DnsSection.ADDITIONAL);
- }
-
- private static void appendRecords(StringBuilder buf, DnsMessage message, DnsSection section) {
- final int count = message.count(section);
- for (int i = 0; i < count; i ++) {
- buf.append(StringUtil.NEWLINE)
- .append('\t')
- .append(message.recordAt(section, i));
- }
- }
-
- private DnsMessageUtil() { }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsOpCode.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsOpCode.java
deleted file mode 100644
index 4140b2e3ff..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsOpCode.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The DNS {@code OpCode} as defined in RFC2929.
- */
-public class DnsOpCode implements Comparable {
-
- /**
- * The 'Query' DNS OpCode, as defined in RFC1035.
- */
- public static final DnsOpCode QUERY = new DnsOpCode(0x00, "QUERY");
-
- /**
- * The 'IQuery' DNS OpCode, as defined in RFC1035.
- */
- public static final DnsOpCode IQUERY = new DnsOpCode(0x01, "IQUERY");
-
- /**
- * The 'Status' DNS OpCode, as defined in RFC1035.
- */
- public static final DnsOpCode STATUS = new DnsOpCode(0x02, "STATUS");
-
- /**
- * The 'Notify' DNS OpCode, as defined in RFC1996.
- */
- public static final DnsOpCode NOTIFY = new DnsOpCode(0x04, "NOTIFY");
-
- /**
- * The 'Update' DNS OpCode, as defined in RFC2136.
- */
- public static final DnsOpCode UPDATE = new DnsOpCode(0x05, "UPDATE");
-
- /**
- * Returns the {@link DnsOpCode} instance of the specified byte value.
- */
- public static DnsOpCode valueOf(int b) {
- switch (b) {
- case 0x00:
- return QUERY;
- case 0x01:
- return IQUERY;
- case 0x02:
- return STATUS;
- case 0x04:
- return NOTIFY;
- case 0x05:
- return UPDATE;
- }
-
- return new DnsOpCode(b);
- }
-
- private final byte byteValue;
- private final String name;
- private String text;
-
- private DnsOpCode(int byteValue) {
- this(byteValue, "UNKNOWN");
- }
-
- public DnsOpCode(int byteValue, String name) {
- this.byteValue = (byte) byteValue;
- this.name = checkNotNull(name, "name");
- }
-
- public byte byteValue() {
- return byteValue;
- }
-
- @Override
- public int hashCode() {
- return byteValue;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof DnsOpCode)) {
- return false;
- }
-
- return byteValue == ((DnsOpCode) obj).byteValue;
- }
-
- @Override
- public int compareTo(DnsOpCode o) {
- return byteValue - o.byteValue;
- }
-
- @Override
- public String toString() {
- String text = this.text;
- if (text == null) {
- this.text = text = name + '(' + (byteValue & 0xFF) + ')';
- }
- return text;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsPtrRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsPtrRecord.java
deleted file mode 100644
index 53962e1142..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsPtrRecord.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-public interface DnsPtrRecord extends DnsRecord {
-
- /**
- * Returns the hostname this PTR record resolves to.
- */
- String hostname();
-
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuery.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuery.java
deleted file mode 100644
index 28de3d2a86..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuery.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-/**
- * A DNS query message.
- */
-public interface DnsQuery extends DnsMessage {
- @Override
- DnsQuery setId(int id);
-
- @Override
- DnsQuery setOpCode(DnsOpCode opCode);
-
- @Override
- DnsQuery setRecursionDesired(boolean recursionDesired);
-
- @Override
- DnsQuery setZ(int z);
-
- @Override
- DnsQuery setRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsQuery addRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsQuery addRecord(DnsSection section, int index, DnsRecord record);
-
- @Override
- DnsQuery clear(DnsSection section);
-
- @Override
- DnsQuery clear();
-
- @Override
- DnsQuery retain();
-
- @Override
- DnsQuery retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuestion.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuestion.java
deleted file mode 100644
index 082ca3a11b..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuestion.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-/**
- * A DNS question.
- */
-public interface DnsQuestion extends DnsRecord {
- /**
- * An unused property. This method will always return {@code 0}.
- */
- @Override
- long timeToLive();
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRawRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRawRecord.java
deleted file mode 100644
index eb96dee270..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRawRecord.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBufHolder;
-
-/**
- * A generic {@link DnsRecord} that contains an undecoded {@code RDATA}.
- */
-public interface DnsRawRecord extends DnsRecord, ByteBufHolder {
- @Override
- DnsRawRecord copy();
-
- @Override
- DnsRawRecord duplicate();
-
- @Override
- DnsRawRecord retain();
-
- @Override
- DnsRawRecord retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecord.java
deleted file mode 100644
index eb1c060498..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecord.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-/**
- * A DNS resource record.
- */
-public interface DnsRecord {
-
- /**
- * DNS resource record class: {@code IN}
- */
- int CLASS_IN = 0x0001;
-
- /**
- * DNS resource record class: {@code CSNET}
- */
- int CLASS_CSNET = 0x0002;
-
- /**
- * DNS resource record class: {@code CHAOS}
- */
- int CLASS_CHAOS = 0x0003;
-
- /**
- * DNS resource record class: {@code HESIOD}
- */
- int CLASS_HESIOD = 0x0004;
-
- /**
- * DNS resource record class: {@code NONE}
- */
- int CLASS_NONE = 0x00fe;
-
- /**
- * DNS resource record class: {@code ANY}
- */
- int CLASS_ANY = 0x00ff;
-
- /**
- * Returns the name of this resource record.
- */
- String name();
-
- /**
- * Returns the type of this resource record.
- */
- DnsRecordType type();
-
- /**
- * Returns the class of this resource record.
- *
- * @return the class value, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- */
- int dnsClass();
-
- /**
- * Returns the time to live after reading for this resource record.
- */
- long timeToLive();
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordDecoder.java
deleted file mode 100644
index a2b6315acc..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordDecoder.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-
-/**
- * Decodes a DNS record into its object representation.
- *
- * @see DatagramDnsResponseDecoder
- */
-public interface DnsRecordDecoder {
-
- DnsRecordDecoder DEFAULT = new DefaultDnsRecordDecoder();
-
- /**
- * Decodes a DNS question into its object representation.
- *
- * @param in the input buffer which contains a DNS question at its reader index
- */
- DnsQuestion decodeQuestion(ByteBuf in) throws Exception;
-
- /**
- * Decodes a DNS record into its object representation.
- *
- * @param in the input buffer which contains a DNS record at its reader index
- *
- * @return the decoded record, or {@code null} if there are not enough data in the input buffer
- */
- T decodeRecord(ByteBuf in) throws Exception;
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordEncoder.java
deleted file mode 100644
index 56b7fa1a05..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordEncoder.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-
-/**
- * Encodes a {@link DnsRecord} into binary representation.
- *
- * @see DatagramDnsQueryEncoder
- */
-public interface DnsRecordEncoder {
-
- DnsRecordEncoder DEFAULT = new DefaultDnsRecordEncoder();
-
- /**
- * Encodes a {@link DnsQuestion}.
- *
- * @param out the output buffer where the encoded question will be written to
- */
- void encodeQuestion(DnsQuestion question, ByteBuf out) throws Exception;
-
- /**
- * Encodes a {@link DnsRecord}.
- *
- * @param out the output buffer where the encoded record will be written to
- */
- void encodeRecord(DnsRecord record, ByteBuf out) throws Exception;
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordType.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordType.java
deleted file mode 100644
index 77f3d3c5a6..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordType.java
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.util.collection.IntObjectHashMap;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Represents a DNS record type.
- */
-public class DnsRecordType implements Comparable {
-
- /**
- * Address record RFC 1035 Returns a 32-bit IPv4 address, most commonly used
- * to map hostnames to an IP address of the host, but also used for DNSBLs,
- * storing subnet masks in RFC 1101, etc.
- */
- public static final DnsRecordType A = new DnsRecordType(0x0001, "A");
-
- /**
- * Name server record RFC 1035 Delegates a DNS zone to use the given
- * authoritative name servers
- */
- public static final DnsRecordType NS = new DnsRecordType(0x0002, "NS");
-
- /**
- * Canonical name record RFC 1035 Alias of one name to another: the DNS
- * lookup will continue by retrying the lookup with the new name.
- */
- public static final DnsRecordType CNAME = new DnsRecordType(0x0005, "CNAME");
-
- /**
- * Start of [a zone of] authority record RFC 1035 and RFC 2308 Specifies
- * authoritative information about a DNS zone, including the primary name
- * server, the email of the domain administrator, the domain serial number,
- * and several timers relating to refreshing the zone.
- */
- public static final DnsRecordType SOA = new DnsRecordType(0x0006, "SOA");
-
- /**
- * Pointer record RFC 1035 Pointer to a canonical name. Unlike a CNAME, DNS
- * processing does NOT proceed, just the name is returned. The most common
- * use is for implementing reverse DNS lookups, but other uses include such
- * things as DNS-SD.
- */
- public static final DnsRecordType PTR = new DnsRecordType(0x000c, "PTR");
-
- /**
- * Mail exchange record RFC 1035 Maps a domain name to a list of message
- * transfer agents for that domain.
- */
- public static final DnsRecordType MX = new DnsRecordType(0x000f, "MX");
-
- /**
- * Text record RFC 1035 Originally for arbitrary human-readable text in a
- * DNS record. Since the early 1990s, however, this record more often
- * carries machine-readable data, such as specified by RFC 1464,
- * opportunistic encryption, Sender Policy Framework, DKIM, DMARC DNS-SD,
- * etc.
- */
- public static final DnsRecordType TXT = new DnsRecordType(0x0010, "TXT");
-
- /**
- * Responsible person record RFC 1183 Information about the responsible
- * person(s) for the domain. Usually an email address with the @ replaced by
- * a .
- */
- public static final DnsRecordType RP = new DnsRecordType(0x0011, "RP");
-
- /**
- * AFS database record RFC 1183 Location of database servers of an AFS cell.
- * This record is commonly used by AFS clients to contact AFS cells outside
- * their local domain. A subtype of this record is used by the obsolete
- * DCE/DFS file system.
- */
- public static final DnsRecordType AFSDB = new DnsRecordType(0x0012, "AFSDB");
-
- /**
- * Signature record RFC 2535 Signature record used in SIG(0) (RFC 2931) and
- * TKEY (RFC 2930). RFC 3755 designated RRSIG as the replacement for SIG for
- * use within DNSSEC.
- */
- public static final DnsRecordType SIG = new DnsRecordType(0x0018, "SIG");
-
- /**
- * key record RFC 2535 and RFC 2930 Used only for SIG(0) (RFC 2931) and TKEY
- * (RFC 2930). RFC 3445 eliminated their use for application keys and
- * limited their use to DNSSEC. RFC 3755 designates DNSKEY as the
- * replacement within DNSSEC. RFC 4025 designates IPSECKEY as the
- * replacement for use with IPsec.
- */
- public static final DnsRecordType KEY = new DnsRecordType(0x0019, "KEY");
-
- /**
- * IPv6 address record RFC 3596 Returns a 128-bit IPv6 address, most
- * commonly used to map hostnames to an IP address of the host.
- */
- public static final DnsRecordType AAAA = new DnsRecordType(0x001c, "AAAA");
-
- /**
- * Location record RFC 1876 Specifies a geographical location associated
- * with a domain name.
- */
- public static final DnsRecordType LOC = new DnsRecordType(0x001d, "LOC");
-
- /**
- * Service locator RFC 2782 Generalized service location record, used for
- * newer protocols instead of creating protocol-specific records such as MX.
- */
- public static final DnsRecordType SRV = new DnsRecordType(0x0021, "SRV");
-
- /**
- * Naming Authority Pointer record RFC 3403 Allows regular expression based
- * rewriting of domain names which can then be used as URIs, further domain
- * names to lookups, etc.
- */
- public static final DnsRecordType NAPTR = new DnsRecordType(0x0023, "NAPTR");
-
- /**
- * Key eXchanger record RFC 2230 Used with some cryptographic systems (not
- * including DNSSEC) to identify a key management agent for the associated
- * domain-name. Note that this has nothing to do with DNS Security. It is
- * Informational status, rather than being on the IETF standards-track. It
- * has always had limited deployment, but is still in use.
- */
- public static final DnsRecordType KX = new DnsRecordType(0x0024, "KX");
-
- /**
- * Certificate record RFC 4398 Stores PKIX, SPKI, PGP, etc.
- */
- public static final DnsRecordType CERT = new DnsRecordType(0x0025, "CERT");
-
- /**
- * Delegation name record RFC 2672 DNAME creates an alias for a name and all
- * its subnames, unlike CNAME, which aliases only the exact name in its
- * label. Like the CNAME record, the DNS lookup will continue by retrying
- * the lookup with the new name.
- */
- public static final DnsRecordType DNAME = new DnsRecordType(0x0027, "DNAME");
-
- /**
- * Option record RFC 2671 This is a pseudo DNS record type needed to support
- * EDNS.
- */
- public static final DnsRecordType OPT = new DnsRecordType(0x0029, "OPT");
-
- /**
- * Address Prefix List record RFC 3123 Specify lists of address ranges, e.g.
- * in CIDR format, for various address families. Experimental.
- */
- public static final DnsRecordType APL = new DnsRecordType(0x002a, "APL");
-
- /**
- * Delegation signer record RFC 4034 The record used to identify the DNSSEC
- * signing key of a delegated zone.
- */
- public static final DnsRecordType DS = new DnsRecordType(0x002b, "DS");
-
- /**
- * SSH Public Key Fingerprint record RFC 4255 Resource record for publishing
- * SSH public host key fingerprints in the DNS System, in order to aid in
- * verifying the authenticity of the host. RFC 6594 defines ECC SSH keys and
- * SHA-256 hashes. See the IANA SSHFP RR parameters registry for details.
- */
- public static final DnsRecordType SSHFP = new DnsRecordType(0x002c, "SSHFP");
-
- /**
- * IPsec Key record RFC 4025 Key record that can be used with IPsec.
- */
- public static final DnsRecordType IPSECKEY = new DnsRecordType(0x002d, "IPSECKEY");
-
- /**
- * DNSSEC signature record RFC 4034 Signature for a DNSSEC-secured record
- * set. Uses the same format as the SIG record.
- */
- public static final DnsRecordType RRSIG = new DnsRecordType(0x002e, "RRSIG");
-
- /**
- * Next-Secure record RFC 4034 Part of DNSSEC, used to prove a name does not
- * exist. Uses the same format as the (obsolete) NXT record.
- */
- public static final DnsRecordType NSEC = new DnsRecordType(0x002f, "NSEC");
-
- /**
- * DNS Key record RFC 4034 The key record used in DNSSEC. Uses the same
- * format as the KEY record.
- */
- public static final DnsRecordType DNSKEY = new DnsRecordType(0x0030, "DNSKEY");
-
- /**
- * DHCP identifier record RFC 4701 Used in conjunction with the FQDN option
- * to DHCP.
- */
- public static final DnsRecordType DHCID = new DnsRecordType(0x0031, "DHCID");
-
- /**
- * NSEC record version 3 RFC 5155 An extension to DNSSEC that allows proof
- * of nonexistence for a name without permitting zonewalking.
- */
- public static final DnsRecordType NSEC3 = new DnsRecordType(0x0032, "NSEC3");
-
- /**
- * NSEC3 parameters record RFC 5155 Parameter record for use with NSEC3.
- */
- public static final DnsRecordType NSEC3PARAM = new DnsRecordType(0x0033, "NSEC3PARAM");
-
- /**
- * TLSA certificate association record RFC 6698 A record for DNS-based
- * Authentication of Named Entities (DANE). RFC 6698 defines The TLSA DNS
- * resource record is used to associate a TLS server certificate or public
- * key with the domain name where the record is found, thus forming a 'TLSA
- * certificate association'.
- */
- public static final DnsRecordType TLSA = new DnsRecordType(0x0034, "TLSA");
-
- /**
- * Host Identity Protocol record RFC 5205 Method of separating the end-point
- * identifier and locator roles of IP addresses.
- */
- public static final DnsRecordType HIP = new DnsRecordType(0x0037, "HIP");
-
- /**
- * Sender Policy Framework record RFC 4408 Specified as part of the SPF
- * protocol as an alternative to of storing SPF data in TXT records. Uses
- * the same format as the earlier TXT record.
- */
- public static final DnsRecordType SPF = new DnsRecordType(0x0063, "SPF");
-
- /**
- * Secret key record RFC 2930 A method of providing keying material to be
- * used with TSIG that is encrypted under the public key in an accompanying
- * KEY RR..
- */
- public static final DnsRecordType TKEY = new DnsRecordType(0x00f9, "TKEY");
-
- /**
- * Transaction Signature record RFC 2845 Can be used to authenticate dynamic
- * updates as coming from an approved client, or to authenticate responses
- * as coming from an approved recursive name server similar to DNSSEC.
- */
- public static final DnsRecordType TSIG = new DnsRecordType(0x00fa, "TSIG");
-
- /**
- * Incremental Zone Transfer record RFC 1996 Requests a zone transfer of the
- * given zone but only differences from a previous serial number. This
- * request may be ignored and a full (AXFR) sent in response if the
- * authoritative server is unable to fulfill the request due to
- * configuration or lack of required deltas.
- */
- public static final DnsRecordType IXFR = new DnsRecordType(0x00fb, "IXFR");
-
- /**
- * Authoritative Zone Transfer record RFC 1035 Transfer entire zone file
- * from the master name server to secondary name servers.
- */
- public static final DnsRecordType AXFR = new DnsRecordType(0x00fc, "AXFR");
-
- /**
- * All cached records RFC 1035 Returns all records of all types known to the
- * name server. If the name server does not have any information on the
- * name, the request will be forwarded on. The records returned may not be
- * complete. For example, if there is both an A and an MX for a name, but
- * the name server has only the A record cached, only the A record will be
- * returned. Sometimes referred to as ANY, for example in Windows nslookup
- * and Wireshark.
- */
- public static final DnsRecordType ANY = new DnsRecordType(0x00ff, "ANY");
-
- /**
- * Certification Authority Authorization record RFC 6844 CA pinning,
- * constraining acceptable CAs for a host/domain.
- */
- public static final DnsRecordType CAA = new DnsRecordType(0x0101, "CAA");
-
- /**
- * DNSSEC Trust Authorities record N/A Part of a deployment proposal for
- * DNSSEC without a signed DNS root. See the IANA database and Weiler Spec
- * for details. Uses the same format as the DS record.
- */
- public static final DnsRecordType TA = new DnsRecordType(0x8000, "TA");
-
- /**
- * DNSSEC Lookaside Validation record RFC 4431 For publishing DNSSEC trust
- * anchors outside of the DNS delegation chain. Uses the same format as the
- * DS record. RFC 5074 describes a way of using these records.
- */
- public static final DnsRecordType DLV = new DnsRecordType(0x8001, "DLV");
-
- private static final Map BY_NAME = new HashMap();
- private static final IntObjectHashMap BY_TYPE = new IntObjectHashMap();
- private static final String EXPECTED;
-
- static {
- DnsRecordType[] all = {
- A, NS, CNAME, SOA, PTR, MX, TXT, RP, AFSDB, SIG, KEY, AAAA, LOC, SRV, NAPTR, KX, CERT, DNAME, OPT, APL,
- DS, SSHFP, IPSECKEY, RRSIG, NSEC, DNSKEY, DHCID, NSEC3, NSEC3PARAM, TLSA, HIP, SPF, TKEY, TSIG, IXFR,
- AXFR, ANY, CAA, TA, DLV
- };
-
- final StringBuilder expected = new StringBuilder(512);
-
- expected.append(" (expected: ");
- for (DnsRecordType type: all) {
- BY_NAME.put(type.name(), type);
- BY_TYPE.put(type.intValue(), type);
-
- expected.append(type.name())
- .append('(')
- .append(type.intValue())
- .append("), ");
- }
-
- expected.setLength(expected.length() - 2);
- expected.append(')');
- EXPECTED = expected.toString();
- }
-
- public static DnsRecordType valueOf(int intValue) {
- DnsRecordType result = BY_TYPE.get(intValue);
- if (result == null) {
- return new DnsRecordType(intValue);
- }
- return result;
- }
-
- public static DnsRecordType valueOf(String name) {
- DnsRecordType result = BY_NAME.get(name);
- if (result == null) {
- throw new IllegalArgumentException("name: " + name + EXPECTED);
- }
- return result;
- }
-
- private final int intValue;
- private final String name;
- private String text;
-
- private DnsRecordType(int intValue) {
- this(intValue, "UNKNOWN");
- }
-
- public DnsRecordType(int intValue, String name) {
- if ((intValue & 0xffff) != intValue) {
- throw new IllegalArgumentException("intValue: " + intValue + " (expected: 0 ~ 65535)");
- }
- this.intValue = intValue;
- this.name = name;
- }
-
- /**
- * Returns the name of this type, as seen in bind config files
- */
- public String name() {
- return name;
- }
-
- /**
- * Returns the value of this DnsType as it appears in DNS protocol
- */
- public int intValue() {
- return intValue;
- }
-
- @Override
- public int hashCode() {
- return intValue;
- }
-
- @Override
- public boolean equals(Object o) {
- return o instanceof DnsRecordType && ((DnsRecordType) o).intValue == intValue;
- }
-
- @Override
- public int compareTo(DnsRecordType o) {
- return intValue() - o.intValue();
- }
-
- @Override
- public String toString() {
- String text = this.text;
- if (text == null) {
- this.text = text = name + '(' + intValue() + ')';
- }
- return text;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponse.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponse.java
deleted file mode 100644
index bf85fdee8b..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponse.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-/**
- * A DNS response message.
- */
-public interface DnsResponse extends DnsMessage {
-
- /**
- * Returns {@code true} if responding server is authoritative for the domain
- * name in the query message.
- */
- boolean isAuthoritativeAnswer();
-
- /**
- * Set to {@code true} if responding server is authoritative for the domain
- * name in the query message.
- *
- * @param authoritativeAnswer flag for authoritative answer
- */
- DnsResponse setAuthoritativeAnswer(boolean authoritativeAnswer);
-
- /**
- * Returns {@code true} if response has been truncated, usually if it is
- * over 512 bytes.
- */
- boolean isTruncated();
-
- /**
- * Set to {@code true} if response has been truncated (usually happens for
- * responses over 512 bytes).
- *
- * @param truncated flag for truncation
- */
- DnsResponse setTruncated(boolean truncated);
-
- /**
- * Returns {@code true} if DNS server can handle recursive queries.
- */
- boolean isRecursionAvailable();
-
- /**
- * Set to {@code true} if DNS server can handle recursive queries.
- *
- * @param recursionAvailable flag for recursion availability
- */
- DnsResponse setRecursionAvailable(boolean recursionAvailable);
-
- /**
- * Returns the 4 bit return code.
- */
- DnsResponseCode code();
-
- /**
- * Sets the response code for this message.
- *
- * @param code the response code
- */
- DnsResponse setCode(DnsResponseCode code);
-
- @Override
- DnsResponse setId(int id);
-
- @Override
- DnsResponse setOpCode(DnsOpCode opCode);
-
- @Override
- DnsResponse setRecursionDesired(boolean recursionDesired);
-
- @Override
- DnsResponse setZ(int z);
-
- @Override
- DnsResponse setRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsResponse addRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsResponse addRecord(DnsSection section, int index, DnsRecord record);
-
- @Override
- DnsResponse clear(DnsSection section);
-
- @Override
- DnsResponse clear();
-
- @Override
- DnsResponse retain();
-
- @Override
- DnsResponse retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseCode.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseCode.java
deleted file mode 100644
index dcd4c945aa..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseCode.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The DNS {@code RCODE}, as defined in RFC2929.
- */
-public class DnsResponseCode implements Comparable {
-
- /**
- * The 'NoError' DNS RCODE (0), as defined in RFC1035.
- */
- public static final DnsResponseCode NOERROR = new DnsResponseCode(0, "NoError");
-
- /**
- * The 'FormErr' DNS RCODE (1), as defined in RFC1035.
- */
- public static final DnsResponseCode FORMERR = new DnsResponseCode(1, "FormErr");
-
- /**
- * The 'ServFail' DNS RCODE (2), as defined in RFC1035.
- */
- public static final DnsResponseCode SERVFAIL = new DnsResponseCode(2, "ServFail");
-
- /**
- * The 'NXDomain' DNS RCODE (3), as defined in RFC1035.
- */
- public static final DnsResponseCode NXDOMAIN = new DnsResponseCode(3, "NXDomain");
-
- /**
- * The 'NotImp' DNS RCODE (4), as defined in RFC1035.
- */
- public static final DnsResponseCode NOTIMP = new DnsResponseCode(4, "NotImp");
-
- /**
- * The 'Refused' DNS RCODE (5), as defined in RFC1035.
- */
- public static final DnsResponseCode REFUSED = new DnsResponseCode(5, "Refused");
-
- /**
- * The 'YXDomain' DNS RCODE (6), as defined in RFC2136.
- */
- public static final DnsResponseCode YXDOMAIN = new DnsResponseCode(6, "YXDomain");
-
- /**
- * The 'YXRRSet' DNS RCODE (7), as defined in RFC2136.
- */
- public static final DnsResponseCode YXRRSET = new DnsResponseCode(7, "YXRRSet");
-
- /**
- * The 'NXRRSet' DNS RCODE (8), as defined in RFC2136.
- */
- public static final DnsResponseCode NXRRSET = new DnsResponseCode(8, "NXRRSet");
-
- /**
- * The 'NotAuth' DNS RCODE (9), as defined in RFC2136.
- */
- public static final DnsResponseCode NOTAUTH = new DnsResponseCode(9, "NotAuth");
-
- /**
- * The 'NotZone' DNS RCODE (10), as defined in RFC2136.
- */
- public static final DnsResponseCode NOTZONE = new DnsResponseCode(10, "NotZone");
-
- /**
- * The 'BADVERS' or 'BADSIG' DNS RCODE (16), as defined in RFC2671
- * and RFC2845.
- */
- public static final DnsResponseCode BADVERS_OR_BADSIG = new DnsResponseCode(16, "BADVERS_OR_BADSIG");
-
- /**
- * The 'BADKEY' DNS RCODE (17), as defined in RFC2845.
- */
- public static final DnsResponseCode BADKEY = new DnsResponseCode(17, "BADKEY");
-
- /**
- * The 'BADTIME' DNS RCODE (18), as defined in RFC2845.
- */
- public static final DnsResponseCode BADTIME = new DnsResponseCode(18, "BADTIME");
-
- /**
- * The 'BADMODE' DNS RCODE (19), as defined in RFC2930.
- */
- public static final DnsResponseCode BADMODE = new DnsResponseCode(19, "BADMODE");
-
- /**
- * The 'BADNAME' DNS RCODE (20), as defined in RFC2930.
- */
- public static final DnsResponseCode BADNAME = new DnsResponseCode(20, "BADNAME");
-
- /**
- * The 'BADALG' DNS RCODE (21), as defined in RFC2930.
- */
- public static final DnsResponseCode BADALG = new DnsResponseCode(21, "BADALG");
-
- /**
- * Returns the {@link DnsResponseCode} that corresponds with the given {@code responseCode}.
- *
- * @param responseCode the DNS RCODE
- *
- * @return the corresponding {@link DnsResponseCode}
- */
- public static DnsResponseCode valueOf(int responseCode) {
- switch (responseCode) {
- case 0:
- return NOERROR;
- case 1:
- return FORMERR;
- case 2:
- return SERVFAIL;
- case 3:
- return NXDOMAIN;
- case 4:
- return NOTIMP;
- case 5:
- return REFUSED;
- case 6:
- return YXDOMAIN;
- case 7:
- return YXRRSET;
- case 8:
- return NXRRSET;
- case 9:
- return NOTAUTH;
- case 10:
- return NOTZONE;
- case 16:
- return BADVERS_OR_BADSIG;
- case 17:
- return BADKEY;
- case 18:
- return BADTIME;
- case 19:
- return BADMODE;
- case 20:
- return BADNAME;
- case 21:
- return BADALG;
- default:
- return new DnsResponseCode(responseCode);
- }
- }
-
- private final int code;
- private final String name;
- private String text;
-
- private DnsResponseCode(int code) {
- this(code, "UNKNOWN");
- }
-
- public DnsResponseCode(int code, String name) {
- if (code < 0 || code > 65535) {
- throw new IllegalArgumentException("code: " + code + " (expected: 0 ~ 65535)");
- }
-
- this.code = code;
- this.name = checkNotNull(name, "name");
- }
-
- /**
- * Returns the error code for this {@link DnsResponseCode}.
- */
- public int intValue() {
- return code;
- }
-
- @Override
- public int compareTo(DnsResponseCode o) {
- return intValue() - o.intValue();
- }
-
- @Override
- public int hashCode() {
- return intValue();
- }
-
- /**
- * Equality of {@link DnsResponseCode} only depends on {@link #intValue()}.
- */
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof DnsResponseCode)) {
- return false;
- }
-
- return intValue() == ((DnsResponseCode) o).intValue();
- }
-
- /**
- * Returns a formatted error message for this {@link DnsResponseCode}.
- */
- @Override
- public String toString() {
- String text = this.text;
- if (text == null) {
- this.text = text = name + '(' + intValue() + ')';
- }
- return text;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsSection.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsSection.java
deleted file mode 100644
index 1d0c842d1b..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsSection.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-/**
- * Represents a section of a {@link DnsMessage}.
- */
-public enum DnsSection {
- /**
- * The section that contains {@link DnsQuestion}s.
- */
- QUESTION,
- /**
- * The section that contains the answer {@link DnsRecord}s.
- */
- ANSWER,
- /**
- * The section that contains the authority {@link DnsRecord}s.
- */
- AUTHORITY,
- /**
- * The section that contains the additional {@link DnsRecord}s.
- */
- ADDITIONAL
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/package-info.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/package-info.java
deleted file mode 100644
index e45c7dfcac..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/package-info.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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.
- */
-
-/**
- * DNS codec.
- */
-package io.netty.handler.codec.dns;
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/AbstractDnsRecordTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/AbstractDnsRecordTest.java
deleted file mode 100644
index d55a0b1354..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/AbstractDnsRecordTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class AbstractDnsRecordTest {
-
- @Test
- public void testValidDomainName() {
- String name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals(name + '.', record.name());
- }
-
- @Test
- public void testValidDomainNameUmlaut() {
- String name = "ä";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals("xn--4ca.", record.name());
- }
-
- @Test
- public void testValidDomainNameTrailingDot() {
- String name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals(name, record.name());
- }
-
- @Test
- public void testValidDomainNameUmlautTrailingDot() {
- String name = "ä.";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals("xn--4ca.", record.name());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testValidDomainNameLength() {
- String name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
- new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testValidDomainNameUmlautLength() {
- String name = "äaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
- new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoderTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoderTest.java
deleted file mode 100644
index 244422fcdb..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoderTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class DefaultDnsRecordDecoderTest {
-
- @Test
- public void testDecodeName() {
- testDecodeName("netty.io.", Unpooled.wrappedBuffer(new byte[] {
- 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0
- }));
- }
-
- @Test
- public void testDecodeNameWithoutTerminator() {
- testDecodeName("netty.io.", Unpooled.wrappedBuffer(new byte[] {
- 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o'
- }));
- }
-
- @Test
- public void testDecodeNameWithExtraTerminator() {
- // Should not be decoded as 'netty.io..'
- testDecodeName("netty.io.", Unpooled.wrappedBuffer(new byte[] {
- 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0, 0
- }));
- }
-
- @Test
- public void testDecodeEmptyName() {
- testDecodeName(".", Unpooled.buffer().writeByte(0));
- }
-
- @Test
- public void testDecodeEmptyNameFromEmptyBuffer() {
- testDecodeName(".", Unpooled.EMPTY_BUFFER);
- }
-
- @Test
- public void testDecodeEmptyNameFromExtraZeroes() {
- testDecodeName(".", Unpooled.wrappedBuffer(new byte[] { 0, 0 }));
- }
-
- private static void testDecodeName(String expected, ByteBuf buffer) {
- try {
- DefaultDnsRecordDecoder decoder = new DefaultDnsRecordDecoder();
- assertEquals(expected, decoder.decodeName0(buffer));
- } finally {
- buffer.release();
- }
- }
-
- @Test
- public void testDecodePtrRecord() throws Exception {
- DefaultDnsRecordDecoder decoder = new DefaultDnsRecordDecoder();
- ByteBuf buffer = Unpooled.buffer().writeByte(0);
- int readerIndex = buffer.readerIndex();
- int writerIndex = buffer.writerIndex();
- try {
- DnsPtrRecord record = (DnsPtrRecord) decoder.decodeRecord(
- "netty.io", DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 0, 1);
- assertEquals("netty.io.", record.name());
- assertEquals(DnsRecord.CLASS_IN, record.dnsClass());
- assertEquals(60, record.timeToLive());
- assertEquals(DnsRecordType.PTR, record.type());
- assertEquals(readerIndex, buffer.readerIndex());
- assertEquals(writerIndex, buffer.writerIndex());
- } finally {
- buffer.release();
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoderTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoderTest.java
deleted file mode 100644
index ac8b5b65eb..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoderTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.util.internal.StringUtil;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class DefaultDnsRecordEncoderTest {
-
- @Test
- public void testEncodeName() throws Exception {
- testEncodeName(new byte[] { 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0 }, "netty.io.");
- }
-
- @Test
- public void testEncodeNameWithoutTerminator() throws Exception {
- testEncodeName(new byte[] { 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0 }, "netty.io");
- }
-
- @Test
- public void testEncodeNameWithExtraTerminator() throws Exception {
- testEncodeName(new byte[] { 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0 }, "netty.io..");
- }
-
- // Test for https://github.com/netty/netty/issues/5014
- @Test
- public void testEncodeEmptyName() throws Exception {
- testEncodeName(new byte[] { 0 }, StringUtil.EMPTY_STRING);
- }
-
- @Test
- public void testEncodeRootName() throws Exception {
- testEncodeName(new byte[] { 0 }, ".");
- }
-
- private static void testEncodeName(byte[] expected, String name) throws Exception {
- DefaultDnsRecordEncoder encoder = new DefaultDnsRecordEncoder();
- ByteBuf out = Unpooled.buffer();
- ByteBuf expectedBuf = Unpooled.wrappedBuffer(expected);
- try {
- encoder.encodeName(name, out);
- assertEquals(expectedBuf, out);
- } finally {
- out.release();
- expectedBuf.release();
- }
- }
-
- @Test
- public void testDecodeMessageCompression() throws Exception {
- // See https://www.ietf.org/rfc/rfc1035 [4.1.4. Message compression]
- DefaultDnsRecordDecoder decoder = new DefaultDnsRecordDecoder();
- byte[] rfcExample = new byte[] { 1, 'F', 3, 'I', 'S', 'I', 4, 'A', 'R', 'P', 'A',
- 0, 3, 'F', 'O', 'O',
- (byte) 0xC0, 0, // this is 20 in the example
- (byte) 0xC0, 6, // this is 26 in the example
- };
- DefaultDnsRawRecord rawPlainRecord = null;
- DefaultDnsRawRecord rawUncompressedRecord = null;
- DefaultDnsRawRecord rawUncompressedIndexedRecord = null;
- ByteBuf buffer = Unpooled.wrappedBuffer(rfcExample);
- try {
- // First lets test that our utility funciton can correctly handle index references and decompression.
- String plainName = DefaultDnsRecordDecoder.decodeName(buffer.duplicate());
- assertEquals("F.ISI.ARPA.", plainName);
- String uncompressedPlainName = DefaultDnsRecordDecoder.decodeName(buffer.duplicate().setIndex(16, 20));
- assertEquals(plainName, uncompressedPlainName);
- String uncompressedIndexedName = DefaultDnsRecordDecoder.decodeName(buffer.duplicate().setIndex(12, 20));
- assertEquals("FOO." + plainName, uncompressedIndexedName);
-
- // Now lets make sure out object parsing produces the same results for non PTR type (just use CNAME).
- rawPlainRecord = (DefaultDnsRawRecord) decoder.decodeRecord(
- plainName, DnsRecordType.CNAME, DnsRecord.CLASS_IN, 60, buffer, 0, 11);
- assertEquals(plainName, rawPlainRecord.name());
- assertEquals(plainName, DefaultDnsRecordDecoder.decodeName(rawPlainRecord.content()));
-
- rawUncompressedRecord = (DefaultDnsRawRecord) decoder.decodeRecord(
- uncompressedPlainName, DnsRecordType.CNAME, DnsRecord.CLASS_IN, 60, buffer, 16, 4);
- assertEquals(uncompressedPlainName, rawUncompressedRecord.name());
- assertEquals(uncompressedPlainName, DefaultDnsRecordDecoder.decodeName(rawUncompressedRecord.content()));
-
- rawUncompressedIndexedRecord = (DefaultDnsRawRecord) decoder.decodeRecord(
- uncompressedIndexedName, DnsRecordType.CNAME, DnsRecord.CLASS_IN, 60, buffer, 12, 8);
- assertEquals(uncompressedIndexedName, rawUncompressedIndexedRecord.name());
- assertEquals(uncompressedIndexedName,
- DefaultDnsRecordDecoder.decodeName(rawUncompressedIndexedRecord.content()));
-
- // Now lets make sure out object parsing produces the same results for PTR type.
- DnsPtrRecord ptrRecord = (DnsPtrRecord) decoder.decodeRecord(
- plainName, DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 0, 11);
- assertEquals(plainName, ptrRecord.name());
- assertEquals(plainName, ptrRecord.hostname());
-
- ptrRecord = (DnsPtrRecord) decoder.decodeRecord(
- uncompressedPlainName, DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 16, 4);
- assertEquals(uncompressedPlainName, ptrRecord.name());
- assertEquals(uncompressedPlainName, ptrRecord.hostname());
-
- ptrRecord = (DnsPtrRecord) decoder.decodeRecord(
- uncompressedIndexedName, DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 12, 8);
- assertEquals(uncompressedIndexedName, ptrRecord.name());
- assertEquals(uncompressedIndexedName, ptrRecord.hostname());
- } finally {
- if (rawPlainRecord != null) {
- rawPlainRecord.release();
- }
- if (rawUncompressedRecord != null) {
- rawUncompressedRecord.release();
- }
- if (rawUncompressedIndexedRecord != null) {
- rawUncompressedIndexedRecord.release();
- }
- buffer.release();
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java
deleted file mode 100644
index 48cb948f45..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.channel.embedded.EmbeddedChannel;
-
-import io.netty.channel.socket.DatagramPacket;
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-
-public class DnsQueryTest {
-
- @Test
- public void writeQueryTest() throws Exception {
- InetSocketAddress addr = new InetSocketAddress("8.8.8.8", 53);
- EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsQueryEncoder());
- List queries = new ArrayList(5);
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("1.0.0.127.in-addr.arpa", DnsRecordType.PTR)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("www.example.com", DnsRecordType.A)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("example.com", DnsRecordType.AAAA)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("example.com", DnsRecordType.MX)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("example.com", DnsRecordType.CNAME)));
-
- for (DnsQuery query: queries) {
- assertThat(query.count(DnsSection.QUESTION), is(1));
- assertThat(query.count(DnsSection.ANSWER), is(0));
- assertThat(query.count(DnsSection.AUTHORITY), is(0));
- assertThat(query.count(DnsSection.ADDITIONAL), is(0));
-
- embedder.writeOutbound(query);
-
- DatagramPacket packet = (DatagramPacket) embedder.readOutbound();
- Assert.assertTrue(packet.content().isReadable());
- packet.release();
- Assert.assertNull(embedder.readOutbound());
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsRecordTypeTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsRecordTypeTest.java
deleted file mode 100644
index aeeab95b04..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsRecordTypeTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import org.junit.Test;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-
-import static org.junit.Assert.*;
-
-public class DnsRecordTypeTest {
-
- private static List allTypes() throws Exception {
- List result = new ArrayList();
- for (Field field : DnsRecordType.class.getFields()) {
- if ((field.getModifiers() & Modifier.STATIC) != 0 && field.getType() == DnsRecordType.class) {
- result.add((DnsRecordType) field.get(null));
- }
- }
- assertFalse(result.isEmpty());
- return result;
- }
-
- @Test
- public void testSanity() throws Exception {
- assertEquals("More than one type has the same int value",
- allTypes().size(), new HashSet(allTypes()).size());
- }
-
- /**
- * Test of hashCode method, of class DnsRecordType.
- */
- @Test
- public void testHashCode() throws Exception {
- for (DnsRecordType t : allTypes()) {
- assertEquals(t.intValue(), t.hashCode());
- }
- }
-
- /**
- * Test of equals method, of class DnsRecordType.
- */
- @Test
- public void testEquals() throws Exception {
- for (DnsRecordType t1 : allTypes()) {
- for (DnsRecordType t2 : allTypes()) {
- if (t1 != t2) {
- assertNotEquals(t1, t2);
- }
- }
- }
- }
-
- /**
- * Test of find method, of class DnsRecordType.
- */
- @Test
- public void testFind() throws Exception {
- for (DnsRecordType t : allTypes()) {
- DnsRecordType found = DnsRecordType.valueOf(t.intValue());
- assertSame(t, found);
- found = DnsRecordType.valueOf(t.name());
- assertSame(t.name(), t, found);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java
deleted file mode 100644
index e0d1ec1a3f..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project 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 io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.embedded.EmbeddedChannel;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.CorruptedFrameException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-
-import java.net.InetSocketAddress;
-
-import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
-
-public class DnsResponseTest {
-
- private static final byte[][] packets = {
- {
- 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 1, 0, 1, -64, 12, 0, 1, 0, 1, 0, 0, 16, -113, 0, 4, -64, 0, 43, 10
- },
- {
- 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 28, 0, 1, -64, 12, 0, 28, 0, 1, 0, 0, 69, -8, 0, 16, 32, 1, 5, 0, 0, -120, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 16
- },
- {
- 0, 2, -127, -128, 0, 1, 0, 0, 0, 1, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 15, 0, 1, -64, 16, 0, 6, 0, 1, 0, 0, 3, -43, 0, 45, 3, 115, 110, 115, 3, 100,
- 110, 115, 5, 105, 99, 97, 110, 110, 3, 111, 114, 103, 0, 3, 110, 111, 99, -64, 49, 119, -4, 39,
- 112, 0, 0, 28, 32, 0, 0, 14, 16, 0, 18, 117, 0, 0, 0, 14, 16
- },
- {
- 0, 3, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 16, 0, 1, -64, 12, 0, 16, 0, 1, 0, 0, 84, 75, 0, 12, 11, 118, 61, 115, 112,
- 102, 49, 32, 45, 97, 108, 108
- },
- {
- -105, 19, -127, 0, 0, 1, 0, 0, 0, 13, 0, 0, 2, 104, 112, 11, 116, 105, 109, 98, 111, 117, 100, 114,
- 101, 97, 117, 3, 111, 114, 103, 0, 0, 1, 0, 1, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 20, 1, 68, 12, 82,
- 79, 79, 84, 45, 83, 69, 82, 86, 69, 82, 83, 3, 78, 69, 84, 0, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1,
- 70, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 69, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4,
- 1, 75, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 67, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0,
- 4, 1, 76, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 71, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0,
- 0, 4, 1, 73, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 66, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23,
- 0, 0, 4, 1, 77, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 65, -64, 49, 0, 0, 2, 0, 1, 0, 7,
- -23, 0, 0, 4, 1, 72, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 74, -64, 49
- }
- };
-
- private static final byte[] malformedLoopPacket = {
- 0, 4, -127, -128, 0, 1, 0, 0, 0, 0, 0, 0, -64, 12, 0, 1, 0, 1
- };
-
- @Test
- public void readResponseTest() throws Exception {
- EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
- for (byte[] p: packets) {
- ByteBuf packet = embedder.alloc().buffer(512).writeBytes(p);
- embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
- AddressedEnvelope envelope = (AddressedEnvelope) embedder.readInbound();
- assertThat(envelope, is(instanceOf(DatagramDnsResponse.class)));
- DnsResponse response = envelope.content();
- assertThat(response, is(sameInstance((Object) envelope)));
-
- ByteBuf raw = Unpooled.wrappedBuffer(p);
- assertThat(response.id(), is(raw.getUnsignedShort(0)));
- assertThat(response.count(DnsSection.QUESTION), is(raw.getUnsignedShort(4)));
- assertThat(response.count(DnsSection.ANSWER), is(raw.getUnsignedShort(6)));
- assertThat(response.count(DnsSection.AUTHORITY), is(raw.getUnsignedShort(8)));
- assertThat(response.count(DnsSection.ADDITIONAL), is(raw.getUnsignedShort(10)));
-
- envelope.release();
- }
- }
-
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
- @Test
- public void readMalormedResponseTest() throws Exception {
- EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
- ByteBuf packet = embedder.alloc().buffer(512).writeBytes(malformedLoopPacket);
- exception.expect(CorruptedFrameException.class);
- embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
- }
-}
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
deleted file mode 100644
index 660bf5d912..0000000000
--- a/netty-bp/pom.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
- org.asynchttpclient
- async-http-client-project
- 2.0.25-SNAPSHOT
-
- 4.0.0
- netty-bp
- Asynchronous Http Client Extras Parent
- pom
-
- The Async Http Client Netty Backport parent.
-
-
-
- codec-dns
- resolver
- resolver-dns
-
-
-
-
- org.apache.directory.server
- apacheds-protocol-dns
- 1.5.7
- test
-
-
- junit
- junit
- 4.12
- test
-
-
- org.hamcrest
- hamcrest-library
- 1.3
- test
-
-
-
-
-
-
- maven-javadoc-plugin
-
- -Xdoclint:none
-
-
-
-
-
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
deleted file mode 100644
index e2d839865d..0000000000
--- a/netty-bp/resolver-dns/pom.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
- 4.0.0
-
- org.asynchttpclient
- netty-bp
- 2.0.25-SNAPSHOT
-
-
- netty-resolver-dns
-
- Netty/Resolver/DNS
-
-
-
- ${project.groupId}
- netty-resolver
- ${project.version}
-
-
- ${project.groupId}
- netty-codec-dns
- ${project.version}
-
-
- io.netty
- netty-transport
-
-
-
-
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/channel/ReflectiveChannelFactory.java b/netty-bp/resolver-dns/src/main/java/io/netty/channel/ReflectiveChannelFactory.java
deleted file mode 100644
index 18c0ab762c..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/channel/ReflectiveChannelFactory.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project 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 io.netty.channel;
-
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.util.internal.StringUtil;
-
-/**
- * A {@link ChannelFactory} that instantiates a new {@link Channel} by invoking its default constructor reflectively.
- */
-public class ReflectiveChannelFactory implements ChannelFactory {
-
- private final Class extends T> clazz;
-
- public ReflectiveChannelFactory(Class extends T> clazz) {
- if (clazz == null) {
- throw new NullPointerException("clazz");
- }
- this.clazz = clazz;
- }
-
- @Override
- public T newChannel() {
- try {
- return clazz.newInstance();
- } catch (Throwable t) {
- throw new ChannelException("Unable to create Channel from class " + clazz, t);
- }
- }
-
- @Override
- public String toString() {
- return StringUtil.simpleClassName(clazz) + ".class";
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java
deleted file mode 100644
index 9a28e2ef7e..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.channel.EventLoop;
-import io.netty.util.internal.PlatformDependent;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.TimeUnit;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-import static io.netty.util.internal.ObjectUtil2.checkPositiveOrZero;
-
-/**
- * Default implementation of {@link DnsCache}, backed by a {@link ConcurrentMap}.
- */
-public class DefaultDnsCache implements DnsCache {
-
- private final ConcurrentMap> resolveCache = PlatformDependent.newConcurrentHashMap();
- private final int minTtl;
- private final int maxTtl;
- private final int negativeTtl;
-
- /**
- * Create a cache that respects the TTL returned by the DNS server
- * and doesn't cache negative responses.
- */
- public DefaultDnsCache() {
- this(0, Integer.MAX_VALUE, 0);
- }
-
- /**
- * Create a cache.
- * @param minTtl the minimum TTL
- * @param maxTtl the maximum TTL
- * @param negativeTtl the TTL for failed queries
- */
- public DefaultDnsCache(int minTtl, int maxTtl, int negativeTtl) {
- this.minTtl = checkPositiveOrZero(minTtl, "minTtl");
- this.maxTtl = checkPositiveOrZero(maxTtl, "maxTtl");
- if (minTtl > maxTtl) {
- throw new IllegalArgumentException(
- "minTtl: " + minTtl + ", maxTtl: " + maxTtl + " (expected: 0 <= minTtl <= maxTtl)");
- }
- this.negativeTtl = checkPositiveOrZero(negativeTtl, "negativeTtl");
- }
-
- /**
- * Returns the minimum TTL of the cached DNS resource records (in seconds).
- *
- * @see #maxTtl()
- */
- public int minTtl() {
- return minTtl;
- }
-
- /**
- * Returns the maximum TTL of the cached DNS resource records (in seconds).
- *
- * @see #minTtl()
- */
- public int maxTtl() {
- return maxTtl;
- }
-
- /**
- * Returns the TTL of the cache for the failed DNS queries (in seconds). The default value is {@code 0}, which
- * disables the cache for negative results.
- */
- public int negativeTtl() {
- return negativeTtl;
- }
-
- @Override
- public void clear() {
- for (Iterator>> i = resolveCache.entrySet().iterator(); i.hasNext();) {
- final Map.Entry> e = i.next();
- i.remove();
- cancelExpiration(e.getValue());
- }
- }
-
- @Override
- public boolean clear(String hostname) {
- checkNotNull(hostname, "hostname");
- boolean removed = false;
- for (Iterator>> i = resolveCache.entrySet().iterator(); i.hasNext();) {
- final Map.Entry> e = i.next();
- if (e.getKey().equals(hostname)) {
- i.remove();
- cancelExpiration(e.getValue());
- removed = true;
- }
- }
- return removed;
- }
-
- @Override
- public List get(String hostname) {
- checkNotNull(hostname, "hostname");
- return resolveCache.get(hostname);
- }
-
- private List cachedEntries(String hostname) {
- List oldEntries = resolveCache.get(hostname);
- final List entries;
- if (oldEntries == null) {
- List newEntries = new ArrayList(8);
- oldEntries = resolveCache.putIfAbsent(hostname, newEntries);
- entries = oldEntries != null? oldEntries : newEntries;
- } else {
- entries = oldEntries;
- }
- return entries;
- }
-
- @Override
- public void cache(String hostname, InetAddress address, long originalTtl, EventLoop loop) {
- if (maxTtl == 0) {
- return;
- }
- checkNotNull(hostname, "hostname");
- checkNotNull(address, "address");
- checkNotNull(loop, "loop");
-
- final int ttl = Math.max(minTtl, (int) Math.min(maxTtl, originalTtl));
- final List entries = cachedEntries(hostname);
- final DnsCacheEntry e = new DnsCacheEntry(hostname, address);
-
- synchronized (entries) {
- if (!entries.isEmpty()) {
- final DnsCacheEntry firstEntry = entries.get(0);
- if (firstEntry.cause() != null) {
- assert entries.size() == 1;
- firstEntry.cancelExpiration();
- entries.clear();
- }
- }
- entries.add(e);
- }
-
- scheduleCacheExpiration(entries, e, ttl, loop);
- }
-
- @Override
- public void cache(String hostname, Throwable cause, EventLoop loop) {
- if (negativeTtl == 0) {
- return;
- }
- checkNotNull(hostname, "hostname");
- checkNotNull(cause, "cause");
- checkNotNull(loop, "loop");
-
- final List entries = cachedEntries(hostname);
- final DnsCacheEntry e = new DnsCacheEntry(hostname, cause);
-
- synchronized (entries) {
- final int numEntries = entries.size();
- for (int i = 0; i < numEntries; i ++) {
- entries.get(i).cancelExpiration();
- }
- entries.clear();
- entries.add(e);
- }
-
- scheduleCacheExpiration(entries, e, negativeTtl, loop);
- }
-
- private static void cancelExpiration(List entries) {
- final int numEntries = entries.size();
- for (int i = 0; i < numEntries; i++) {
- entries.get(i).cancelExpiration();
- }
- }
-
- private void scheduleCacheExpiration(final List entries,
- final DnsCacheEntry e,
- int ttl,
- EventLoop loop) {
- e.scheduleExpiration(loop, new Runnable() {
- @Override
- public void run() {
- synchronized (entries) {
- entries.remove(e);
- if (entries.isEmpty()) {
- resolveCache.remove(e.hostname());
- }
- }
- }
- }, ttl, TimeUnit.SECONDS);
- }
-
- @Override
- public String toString() {
- return new StringBuilder()
- .append("DefaultDnsCache(minTtl=")
- .append(minTtl).append(", maxTtl=")
- .append(maxTtl).append(", negativeTtl=")
- .append(negativeTtl).append(", cached resolved hostname=")
- .append(resolveCache.size()).append(")")
- .toString();
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsServerAddresses.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsServerAddresses.java
deleted file mode 100644
index 0efd244915..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsServerAddresses.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import java.net.InetSocketAddress;
-
-abstract class DefaultDnsServerAddresses extends DnsServerAddresses {
-
- protected final InetSocketAddress[] addresses;
- private final String strVal;
-
- DefaultDnsServerAddresses(String type, InetSocketAddress[] addresses) {
- this.addresses = addresses;
-
- final StringBuilder buf = new StringBuilder(type.length() + 2 + addresses.length * 16);
- buf.append(type).append('(');
-
- for (InetSocketAddress a: addresses) {
- buf.append(a).append(", ");
- }
-
- buf.setLength(buf.length() - 2);
- buf.append(')');
-
- strVal = buf.toString();
- }
-
- @Override
- public String toString() {
- return strVal;
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java
deleted file mode 100644
index 24a45b5f2e..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.channel.EventLoop;
-import io.netty.channel.ReflectiveChannelFactory;
-import io.netty.channel.socket.DatagramChannel;
-import io.netty.resolver.AddressResolver;
-import io.netty.resolver.AddressResolverGroup;
-import io.netty.resolver.InetSocketAddressResolver;
-import io.netty.resolver.NameResolver;
-import io.netty.util.concurrent.EventExecutor;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.internal.StringUtil;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.List;
-import java.util.concurrent.ConcurrentMap;
-
-import static io.netty.util.internal.PlatformDependent.newConcurrentHashMap;
-
-/**
- * A {@link AddressResolverGroup} of {@link DnsNameResolver}s.
- */
-public class DnsAddressResolverGroup extends AddressResolverGroup {
-
- private final ChannelFactory extends DatagramChannel> channelFactory;
- private final DnsServerAddresses nameServerAddresses;
-
- private final ConcurrentMap> resolvesInProgress = newConcurrentHashMap();
- private final ConcurrentMap>> resolveAllsInProgress = newConcurrentHashMap();
-
- public DnsAddressResolverGroup(
- Class extends DatagramChannel> channelType,
- DnsServerAddresses nameServerAddresses) {
- this(new ReflectiveChannelFactory(channelType), nameServerAddresses);
- }
-
- public DnsAddressResolverGroup(
- ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses) {
- this.channelFactory = channelFactory;
- this.nameServerAddresses = nameServerAddresses;
- }
-
- @SuppressWarnings("deprecation")
- @Override
- protected final AddressResolver newResolver(EventExecutor executor) throws Exception {
- if (!(executor instanceof EventLoop)) {
- throw new IllegalStateException(
- "unsupported executor type: " + StringUtil.simpleClassName(executor) +
- " (expected: " + StringUtil.simpleClassName(EventLoop.class));
- }
-
- return newResolver((EventLoop) executor, channelFactory, nameServerAddresses);
- }
-
- /**
- * @deprecated Override {@link #newNameResolver(EventLoop, ChannelFactory, DnsServerAddresses)}.
- */
- @Deprecated
- protected AddressResolver newResolver(
- EventLoop eventLoop, ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses) throws Exception {
-
- final NameResolver resolver = new InflightNameResolver(
- eventLoop,
- newNameResolver(eventLoop, channelFactory, nameServerAddresses),
- resolvesInProgress,
- resolveAllsInProgress);
-
- return new InetSocketAddressResolver(eventLoop, resolver);
- }
-
- /**
- * Creates a new {@link NameResolver}. Override this method to create an alternative {@link NameResolver}
- * implementation or override the default configuration.
- */
- protected NameResolver newNameResolver(EventLoop eventLoop,
- ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses) throws Exception {
- return new DnsNameResolverBuilder(eventLoop)
- .channelFactory(channelFactory)
- .nameServerAddresses(nameServerAddresses)
- .build();
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCache.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCache.java
deleted file mode 100644
index 79ea3876d5..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCache.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.channel.EventLoop;
-
-import java.net.InetAddress;
-import java.util.List;
-
-/**
- * A cache for DNS resolution entries.
- */
-public interface DnsCache {
-
- /**
- * Clears all the resolved addresses cached by this resolver.
- *
- * @see #clear(String)
- */
- void clear();
-
- /**
- * Clears the resolved addresses of the specified host name from the cache of this resolver.
- *
- * @return {@code true} if and only if there was an entry for the specified host name in the cache and
- * it has been removed by this method
- */
- boolean clear(String hostname);
-
- /**
- * Return the cached entries for the given hostname.
- * @param hostname the hostname
- * @return the cached entries
- */
- List get(String hostname);
-
- /**
- * Cache a resolved address for a given hostname.
- * @param hostname the hostname
- * @param address the resolved adresse
- * @param originalTtl the TLL as returned by the DNS server
- * @param loop the {@link EventLoop} used to register the TTL timeout
- */
- void cache(String hostname, InetAddress address, long originalTtl, EventLoop loop);
-
- /**
- * Cache the resolution failure for a given hostname.
- * @param hostname the hostname
- * @param cause the resolution failure
- * @param loop the {@link EventLoop} used to register the TTL timeout
- */
- void cache(String hostname, Throwable cause, EventLoop loop);
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCacheEntry.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCacheEntry.java
deleted file mode 100644
index 789ef7ab84..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCacheEntry.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-import io.netty.channel.EventLoop;
-import io.netty.util.concurrent.ScheduledFuture;
-
-import java.net.InetAddress;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Entry in {@link DnsCache}.
- */
-public final class DnsCacheEntry {
-
- private final String hostname;
- private final InetAddress address;
- private final Throwable cause;
- private volatile ScheduledFuture> expirationFuture;
-
- public DnsCacheEntry(String hostname, InetAddress address) {
- this.hostname = checkNotNull(hostname, "hostname");
- this.address = checkNotNull(address, "address");
- cause = null;
- }
-
- public DnsCacheEntry(String hostname, Throwable cause) {
- this.hostname = checkNotNull(hostname, "hostname");
- this.cause = checkNotNull(cause, "cause");
- address = null;
- }
-
- public String hostname() {
- return hostname;
- }
-
- public InetAddress address() {
- return address;
- }
-
- public Throwable cause() {
- return cause;
- }
-
- void scheduleExpiration(EventLoop loop, Runnable task, long delay, TimeUnit unit) {
- assert expirationFuture == null: "expiration task scheduled already";
- expirationFuture = loop.schedule(task, delay, unit);
- }
-
- void cancelExpiration() {
- ScheduledFuture> expirationFuture = this.expirationFuture;
- if (expirationFuture != null) {
- expirationFuture.cancel(false);
- }
- }
-
- @Override
- public String toString() {
- if (cause != null) {
- return hostname + '/' + cause;
- } else {
- return address.toString();
- }
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java
deleted file mode 100644
index 27520555ae..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java
+++ /dev/null
@@ -1,709 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.bootstrap.Bootstrap;
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelFutureListener;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.EventLoop;
-import io.netty.channel.FixedRecvByteBufAllocator;
-import io.netty.channel.socket.DatagramChannel;
-import io.netty.channel.socket.InternetProtocolFamily;
-import io.netty.handler.codec.dns.DatagramDnsQueryEncoder;
-import io.netty.handler.codec.dns.DatagramDnsResponse;
-import io.netty.handler.codec.dns.DnsRecord;
-import io.netty.handler.codec.dns.DatagramDnsResponseDecoder;
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.handler.codec.dns.DnsResponse;
-import io.netty.resolver.HostsFileEntriesResolver;
-import io.netty.resolver.InetNameResolver;
-import io.netty.util.NetUtil;
-import io.netty.util.ReferenceCountUtil;
-import io.netty.util.concurrent.FastThreadLocal;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.internal.EmptyArrays;
-import io.netty.util.internal.PlatformDependent;
-import io.netty.util.internal.StringUtil2;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.lang.reflect.Method;
-import java.net.IDN;
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil2.*;
-
-/**
- * A DNS-based {@link InetNameResolver}.
- */
-public class DnsNameResolver extends InetNameResolver {
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsNameResolver.class);
- private static final String LOCALHOST = "localhost";
- private static final InetAddress LOCALHOST_ADDRESS;
-
- static final InternetProtocolFamily[] DEFAULT_RESOLVE_ADDRESS_TYPES = new InternetProtocolFamily[2];
- static final String[] DEFAULT_SEACH_DOMAINS;
-
- static {
- // Note that we did not use SystemPropertyUtil.getBoolean() here to emulate the behavior of JDK.
- if (Boolean.getBoolean("java.net.preferIPv6Addresses")) {
- DEFAULT_RESOLVE_ADDRESS_TYPES[0] = InternetProtocolFamily.IPv6;
- DEFAULT_RESOLVE_ADDRESS_TYPES[1] = InternetProtocolFamily.IPv4;
- LOCALHOST_ADDRESS = NetUtil.LOCALHOST6;
- logger.debug("-Djava.net.preferIPv6Addresses: true");
- } else {
- DEFAULT_RESOLVE_ADDRESS_TYPES[0] = InternetProtocolFamily.IPv4;
- DEFAULT_RESOLVE_ADDRESS_TYPES[1] = InternetProtocolFamily.IPv6;
- LOCALHOST_ADDRESS = NetUtil.LOCALHOST4;
- logger.debug("-Djava.net.preferIPv6Addresses: false");
- }
- }
-
- static {
- String[] searchDomains;
- try {
- Class> configClass = Class.forName("sun.net.dns.ResolverConfiguration");
- Method open = configClass.getMethod("open");
- Method nameservers = configClass.getMethod("searchlist");
- Object instance = open.invoke(null);
-
- @SuppressWarnings("unchecked")
- List list = (List) nameservers.invoke(instance);
- searchDomains = list.toArray(new String[list.size()]);
- } catch (Exception ignore) {
- // Failed to get the system name search domain list.
- searchDomains = EmptyArrays.EMPTY_STRINGS;
- }
- DEFAULT_SEACH_DOMAINS = searchDomains;
- }
-
- private static final DatagramDnsResponseDecoder DECODER = new DatagramDnsResponseDecoder();
- private static final DatagramDnsQueryEncoder ENCODER = new DatagramDnsQueryEncoder();
-
- final DnsServerAddresses nameServerAddresses;
- final Future channelFuture;
- final DatagramChannel ch;
-
- /**
- * Manages the {@link DnsQueryContext}s in progress and their query IDs.
- */
- final DnsQueryContextManager queryContextManager = new DnsQueryContextManager();
-
- /**
- * Cache for {@link #doResolve(String, Promise)} and {@link #doResolveAll(String, Promise)}.
- */
- private final DnsCache resolveCache;
-
- private final FastThreadLocal nameServerAddrStream =
- new FastThreadLocal() {
- @Override
- protected DnsServerAddressStream initialValue() throws Exception {
- return nameServerAddresses.stream();
- }
- };
-
- private final long queryTimeoutMillis;
- private final int maxQueriesPerResolve;
- private final boolean traceEnabled;
- private final InternetProtocolFamily[] resolvedAddressTypes;
- private final boolean recursionDesired;
- private final int maxPayloadSize;
- private final boolean optResourceEnabled;
- private final HostsFileEntriesResolver hostsFileEntriesResolver;
- private final String[] searchDomains;
- private final int ndots;
-
- /**
- * Creates a new DNS-based name resolver that communicates with the specified list of DNS servers.
- *
- * @param eventLoop the {@link EventLoop} which will perform the communication with the DNS servers
- * @param channelFactory the {@link ChannelFactory} that will create a {@link DatagramChannel}
- * @param nameServerAddresses the addresses of the DNS server. For each DNS query, a new stream is created from
- * this to determine which DNS server should be contacted for the next retry in case
- * of failure.
- * @param resolveCache the DNS resolved entries cache
- * @param queryTimeoutMillis timeout of each DNS query in millis
- * @param resolvedAddressTypes list of the protocol families
- * @param recursionDesired if recursion desired flag must be set
- * @param maxQueriesPerResolve the maximum allowed number of DNS queries for a given name resolution
- * @param traceEnabled if trace is enabled
- * @param maxPayloadSize the capacity of the datagram packet buffer
- * @param optResourceEnabled if automatic inclusion of a optional records is enabled
- * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to check for local aliases
- * @param searchDomains the list of search domain
- * @param ndots the ndots value
- */
- public DnsNameResolver(
- EventLoop eventLoop,
- ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses,
- final DnsCache resolveCache,
- long queryTimeoutMillis,
- InternetProtocolFamily[] resolvedAddressTypes,
- boolean recursionDesired,
- int maxQueriesPerResolve,
- boolean traceEnabled,
- int maxPayloadSize,
- boolean optResourceEnabled,
- HostsFileEntriesResolver hostsFileEntriesResolver,
- String[] searchDomains,
- int ndots) {
-
- super(eventLoop);
- checkNotNull(channelFactory, "channelFactory");
- this.nameServerAddresses = checkNotNull(nameServerAddresses, "nameServerAddresses");
- this.queryTimeoutMillis = checkPositive(queryTimeoutMillis, "queryTimeoutMillis");
- this.resolvedAddressTypes = checkNonEmpty(resolvedAddressTypes, "resolvedAddressTypes");
- this.recursionDesired = recursionDesired;
- this.maxQueriesPerResolve = checkPositive(maxQueriesPerResolve, "maxQueriesPerResolve");
- this.traceEnabled = traceEnabled;
- this.maxPayloadSize = checkPositive(maxPayloadSize, "maxPayloadSize");
- this.optResourceEnabled = optResourceEnabled;
- this.hostsFileEntriesResolver = checkNotNull(hostsFileEntriesResolver, "hostsFileEntriesResolver");
- this.resolveCache = resolveCache;
- this.searchDomains = checkNotNull(searchDomains, "searchDomains").clone();
- this.ndots = checkPositiveOrZero(ndots, "ndots");
-
- Bootstrap b = new Bootstrap();
- b.group(executor());
- b.channelFactory(channelFactory);
- b.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
- final DnsResponseHandler responseHandler = new DnsResponseHandler(executor().newPromise());
- b.handler(new ChannelInitializer() {
- @Override
- protected void initChannel(DatagramChannel ch) throws Exception {
- ch.pipeline().addLast(DECODER, ENCODER, responseHandler);
- }
- });
-
- channelFuture = responseHandler.channelActivePromise;
- ch = (DatagramChannel) b.register().channel();
- ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(maxPayloadSize));
-
- ch.closeFuture().addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture future) throws Exception {
- resolveCache.clear();
- }
- });
- }
-
- /**
- * Returns the resolution cache.
- */
- public DnsCache resolveCache() {
- return resolveCache;
- }
-
- /**
- * Returns the timeout of each DNS query performed by this resolver (in milliseconds).
- * The default value is 5 seconds.
- */
- public long queryTimeoutMillis() {
- return queryTimeoutMillis;
- }
-
- /**
- * Returns the list of the protocol families of the address resolved by {@link #resolve(String)}
- * in the order of preference.
- * The default value depends on the value of the system property {@code "java.net.preferIPv6Addresses"}.
- */
- public List resolvedAddressTypes() {
- return Arrays.asList(resolvedAddressTypes);
- }
-
- InternetProtocolFamily[] resolveAddressTypesUnsafe() {
- return resolvedAddressTypes;
- }
-
- final String[] searchDomains() {
- return searchDomains;
- }
-
- final int ndots() {
- return ndots;
- }
-
- /**
- * Returns {@code true} if and only if this resolver sends a DNS query with the RD (recursion desired) flag set.
- * The default value is {@code true}.
- */
- public boolean isRecursionDesired() {
- return recursionDesired;
- }
-
- /**
- * Returns the maximum allowed number of DNS queries to send when resolving a host name.
- * The default value is {@code 8}.
- */
- public int maxQueriesPerResolve() {
- return maxQueriesPerResolve;
- }
-
- /**
- * Returns if this resolver should generate the detailed trace information in an exception message so that
- * it is easier to understand the cause of resolution failure. The default value if {@code true}.
- */
- public boolean isTraceEnabled() {
- return traceEnabled;
- }
-
- /**
- * Returns the capacity of the datagram packet buffer (in bytes). The default value is {@code 4096} bytes.
- */
- public int maxPayloadSize() {
- return maxPayloadSize;
- }
-
- /**
- * Returns the automatic inclusion of a optional records that tries to give the remote DNS server a hint about how
- * much data the resolver can read per response is enabled.
- */
- public boolean isOptResourceEnabled() {
- return optResourceEnabled;
- }
-
- /**
- * Returns the component that tries to resolve hostnames against the hosts file prior to asking to
- * remotes DNS servers.
- */
- public HostsFileEntriesResolver hostsFileEntriesResolver() {
- return hostsFileEntriesResolver;
- }
-
- /**
- * Closes the internal datagram channel used for sending and receiving DNS messages, and clears all DNS resource
- * records from the cache. Attempting to send a DNS query or to resolve a domain name will fail once this method
- * has been called.
- */
- @Override
- public void close() {
- ch.close();
- }
-
- @Override
- protected EventLoop executor() {
- return (EventLoop) super.executor();
- }
-
- private InetAddress resolveHostsFileEntry(String hostname) {
- if (hostsFileEntriesResolver == null) {
- return null;
- } else {
- InetAddress address = hostsFileEntriesResolver.address(hostname);
- if (address == null && PlatformDependent.isWindows() && LOCALHOST.equalsIgnoreCase(hostname)) {
- // If we tried to resolve localhost we need workaround that windows removed localhost from its
- // hostfile in later versions.
- // See https://github.com/netty/netty/issues/5386
- return LOCALHOST_ADDRESS;
- }
- return address;
- }
- }
-
- @Override
- protected void doResolve(String inetHost, Promise promise) throws Exception {
- doResolve(inetHost, promise, resolveCache);
- }
-
- /**
- * Hook designed for extensibility so one can pass a different cache on each resolution attempt
- * instead of using the global one.
- */
- protected void doResolve(String inetHost,
- Promise promise,
- DnsCache resolveCache) throws Exception {
- final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost);
- if (bytes != null) {
- // The inetHost is actually an ipaddress.
- promise.setSuccess(InetAddress.getByAddress(bytes));
- return;
- }
-
- final String hostname = hostname(inetHost);
-
- InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
- if (hostsFileEntry != null) {
- promise.setSuccess(hostsFileEntry);
- return;
- }
-
- if (!doResolveCached(hostname, promise, resolveCache)) {
- doResolveUncached(hostname, promise, resolveCache);
- }
- }
-
- private boolean doResolveCached(String hostname,
- Promise promise,
- DnsCache resolveCache) {
- final List cachedEntries = resolveCache.get(hostname);
- if (cachedEntries == null || cachedEntries.isEmpty()) {
- return false;
- }
-
- InetAddress address = null;
- Throwable cause = null;
- synchronized (cachedEntries) {
- final int numEntries = cachedEntries.size();
- assert numEntries > 0;
-
- if (cachedEntries.get(0).cause() != null) {
- cause = cachedEntries.get(0).cause();
- } else {
- // Find the first entry with the preferred address type.
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- for (int i = 0; i < numEntries; i++) {
- final DnsCacheEntry e = cachedEntries.get(i);
- if (addressMatchFamily(e.address(), f)) {
- address = e.address();
- break;
- }
- }
- }
- }
- }
-
- if (address != null) {
- setSuccess(promise, address);
- } else if (cause != null) {
- if (!promise.tryFailure(cause)) {
- logger.warn("Failed to notify failure to a promise: {}", promise, cause);
- }
- } else {
- return false;
- }
-
- return true;
- }
-
- private static void setSuccess(Promise promise, InetAddress result) {
- if (!promise.trySuccess(result)) {
- logger.warn("Failed to notify success ({}) to a promise: {}", result, promise);
- }
- }
-
- private void doResolveUncached(String hostname,
- Promise promise,
- DnsCache resolveCache) {
- SingleResolverContext ctx = new SingleResolverContext(this, hostname, resolveCache);
- ctx.resolve(promise);
- }
-
- final class SingleResolverContext extends DnsNameResolverContext {
-
- SingleResolverContext(DnsNameResolver parent, String hostname, DnsCache resolveCache) {
- super(parent, hostname, resolveCache);
- }
-
- @Override
- DnsNameResolverContext newResolverContext(DnsNameResolver parent,
- String hostname, DnsCache resolveCache) {
- return new SingleResolverContext(parent, hostname, resolveCache);
- }
-
- @Override
- boolean finishResolve(
- InternetProtocolFamily f, List resolvedEntries,
- Promise promise) {
-
- final int numEntries = resolvedEntries.size();
- for (int i = 0; i < numEntries; i++) {
- final InetAddress a = resolvedEntries.get(i).address();
- if (addressMatchFamily(a, f)) {
- setSuccess(promise, a);
- return true;
- }
- }
- return false;
- }
- }
-
- @Override
- protected void doResolveAll(String inetHost, Promise> promise) throws Exception {
- doResolveAll(inetHost, promise, resolveCache);
- }
-
- /**
- * Hook designed for extensibility so one can pass a different cache on each resolution attempt
- * instead of using the global one.
- */
- protected void doResolveAll(String inetHost,
- Promise> promise,
- DnsCache resolveCache) throws Exception {
-
- final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost);
- if (bytes != null) {
- // The unresolvedAddress was created via a String that contains an ipaddress.
- promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes)));
- return;
- }
-
- final String hostname = hostname(inetHost);
-
- InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
- if (hostsFileEntry != null) {
- promise.setSuccess(Collections.singletonList(hostsFileEntry));
- return;
- }
-
- if (!doResolveAllCached(hostname, promise, resolveCache)) {
- doResolveAllUncached(hostname, promise, resolveCache);
- }
- }
-
- private boolean doResolveAllCached(String hostname,
- Promise> promise,
- DnsCache resolveCache) {
- final List cachedEntries = resolveCache.get(hostname);
- if (cachedEntries == null || cachedEntries.isEmpty()) {
- return false;
- }
-
- List result = null;
- Throwable cause = null;
- synchronized (cachedEntries) {
- final int numEntries = cachedEntries.size();
- assert numEntries > 0;
-
- if (cachedEntries.get(0).cause() != null) {
- cause = cachedEntries.get(0).cause();
- } else {
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- for (int i = 0; i < numEntries; i++) {
- final DnsCacheEntry e = cachedEntries.get(i);
- if (addressMatchFamily(e.address(), f)) {
- if (result == null) {
- result = new ArrayList(numEntries);
- }
- result.add(e.address());
- }
- }
- }
- }
- }
-
- if (result != null) {
- promise.trySuccess(result);
- } else if (cause != null) {
- promise.tryFailure(cause);
- } else {
- return false;
- }
-
- return true;
- }
-
- final class ListResolverContext extends DnsNameResolverContext> {
- ListResolverContext(DnsNameResolver parent, String hostname, DnsCache resolveCache) {
- super(parent, hostname, resolveCache);
- }
-
- @Override
- DnsNameResolverContext> newResolverContext(DnsNameResolver parent, String hostname,
- DnsCache resolveCache) {
- return new ListResolverContext(parent, hostname, resolveCache);
- }
-
- @Override
- boolean finishResolve(
- InternetProtocolFamily f, List resolvedEntries,
- Promise> promise) {
-
- List result = null;
- final int numEntries = resolvedEntries.size();
- for (int i = 0; i < numEntries; i++) {
- final InetAddress a = resolvedEntries.get(i).address();
- if (addressMatchFamily(a, f)) {
- if (result == null) {
- result = new ArrayList(numEntries);
- }
- result.add(a);
- }
- }
-
- if (result != null) {
- promise.trySuccess(result);
- return true;
- }
- return false;
- }
- }
-
- private void doResolveAllUncached(String hostname,
- Promise> promise,
- DnsCache resolveCache) {
- DnsNameResolverContext> ctx = new ListResolverContext(this, hostname, resolveCache);
- ctx.resolve(promise);
- }
-
- private static String hostname(String inetHost) {
- String hostname = IDN.toASCII(inetHost);
- // Check for http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6894622
- if (StringUtil2.endsWith(inetHost, '.') && !StringUtil2.endsWith(hostname, '.')) {
- hostname += ".";
- }
- return hostname;
- }
-
- /**
- * Sends a DNS query with the specified question.
- */
- public Future> query(DnsQuestion question) {
- return query(nextNameServerAddress(), question);
- }
-
- /**
- * Sends a DNS query with the specified question with additional records.
- */
- public Future> query(
- DnsQuestion question, Iterable additional) {
- return query(nextNameServerAddress(), question, additional);
- }
-
- /**
- * Sends a DNS query with the specified question.
- */
- public Future> query(
- DnsQuestion question, Promise> promise) {
- return query(nextNameServerAddress(), question, Collections.emptyList(), promise);
- }
-
- private InetSocketAddress nextNameServerAddress() {
- return nameServerAddrStream.get().next();
- }
-
- /**
- * Sends a DNS query with the specified question using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question) {
-
- return query0(nameServerAddr, question, Collections.emptyList(),
- ch.eventLoop().>newPromise());
- }
-
- /**
- * Sends a DNS query with the specified question with additional records using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question, Iterable additional) {
-
- return query0(nameServerAddr, question, additional,
- ch.eventLoop().>newPromise());
- }
-
- /**
- * Sends a DNS query with the specified question using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question,
- Promise> promise) {
-
- return query0(nameServerAddr, question, Collections.emptyList(), promise);
- }
-
- /**
- * Sends a DNS query with the specified question with additional records using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question,
- Iterable additional,
- Promise> promise) {
-
- return query0(nameServerAddr, question, additional, promise);
- }
-
- private Future> query0(
- InetSocketAddress nameServerAddr, DnsQuestion question,
- Iterable additional,
- Promise> promise) {
-
- final Promise> castPromise = cast(
- checkNotNull(promise, "promise"));
- try {
- new DnsQueryContext(this, nameServerAddr, question, additional, castPromise).query();
- return castPromise;
- } catch (Exception e) {
- return castPromise.setFailure(e);
- }
- }
-
- @SuppressWarnings("unchecked")
- private static Promise> cast(Promise> promise) {
- return (Promise>) promise;
- }
-
- private final class DnsResponseHandler extends ChannelInboundHandlerAdapter {
-
- private final Promise channelActivePromise;
-
- DnsResponseHandler(Promise channelActivePromise) {
- this.channelActivePromise = channelActivePromise;
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- try {
- final DatagramDnsResponse res = (DatagramDnsResponse) msg;
- final int queryId = res.id();
-
- if (logger.isDebugEnabled()) {
- logger.debug("{} RECEIVED: [{}: {}], {}", ch, queryId, res.sender(), res);
- }
-
- final DnsQueryContext qCtx = queryContextManager.get(res.sender(), queryId);
- if (qCtx == null) {
- logger.warn("{} Received a DNS response with an unknown ID: {}", ch, queryId);
- return;
- }
-
- qCtx.finish(res);
- } finally {
- ReferenceCountUtil.safeRelease(msg);
- }
- }
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- super.channelActive(ctx);
- channelActivePromise.setSuccess(ctx.channel());
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- logger.warn("{} Unexpected exception: ", ch, cause);
- }
- }
-
- static boolean addressMatchFamily(InetAddress a, InternetProtocolFamily f) {
- return (f == InternetProtocolFamily.IPv4 && a instanceof Inet4Address) || f == InternetProtocolFamily.IPv6;
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java
deleted file mode 100644
index 3386624800..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import static io.netty.util.internal.ObjectUtil2.intValue;
-
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.channel.EventLoop;
-import io.netty.channel.ReflectiveChannelFactory;
-import io.netty.channel.socket.DatagramChannel;
-import io.netty.channel.socket.InternetProtocolFamily;
-import io.netty.resolver.HostsFileEntriesResolver;
-import io.netty.util.internal.InternalThreadLocalMap;
-
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * A {@link DnsNameResolver} builder.
- */
-public final class DnsNameResolverBuilder {
-
- private final EventLoop eventLoop;
- private ChannelFactory extends DatagramChannel> channelFactory;
- private DnsServerAddresses nameServerAddresses = DnsServerAddresses.defaultAddresses();
- private DnsCache resolveCache;
- private Integer minTtl;
- private Integer maxTtl;
- private Integer negativeTtl;
- private long queryTimeoutMillis = 5000;
- private InternetProtocolFamily[] resolvedAddressTypes = DnsNameResolver.DEFAULT_RESOLVE_ADDRESS_TYPES;
- private boolean recursionDesired = true;
- private int maxQueriesPerResolve = 16;
- private boolean traceEnabled;
- private int maxPayloadSize = 4096;
- private boolean optResourceEnabled = true;
- private HostsFileEntriesResolver hostsFileEntriesResolver = HostsFileEntriesResolver.DEFAULT;
- private String[] searchDomains = DnsNameResolver.DEFAULT_SEACH_DOMAINS;
- private int ndots = 1;
-
- /**
- * Creates a new builder.
- *
- * @param eventLoop the {@link EventLoop} the {@link EventLoop} which will perform the communication with the DNS
- * servers.
- */
- public DnsNameResolverBuilder(EventLoop eventLoop) {
- this.eventLoop = eventLoop;
- }
-
- /**
- * Sets the {@link ChannelFactory} that will create a {@link DatagramChannel}.
- *
- * @param channelFactory the {@link ChannelFactory}
- * @return {@code this}
- */
- public DnsNameResolverBuilder channelFactory(ChannelFactory extends DatagramChannel> channelFactory) {
- this.channelFactory = channelFactory;
- return this;
- }
-
- /**
- * Sets the {@link ChannelFactory} as a {@link ReflectiveChannelFactory} of this type.
- * Use as an alternative to {@link #channelFactory(ChannelFactory)}.
- *
- * @param channelType the type
- * @return {@code this}
- */
- public DnsNameResolverBuilder channelType(Class extends DatagramChannel> channelType) {
- return channelFactory(new ReflectiveChannelFactory(channelType));
- }
-
- /**
- * Sets the addresses of the DNS server.
- *
- * @param nameServerAddresses the DNS server addresses
- * @return {@code this}
- */
- public DnsNameResolverBuilder nameServerAddresses(DnsServerAddresses nameServerAddresses) {
- this.nameServerAddresses = nameServerAddresses;
- return this;
- }
-
- /**
- * Sets the cache for resolution results.
- *
- * @param resolveCache the DNS resolution results cache
- * @return {@code this}
- */
- public DnsNameResolverBuilder resolveCache(DnsCache resolveCache) {
- this.resolveCache = resolveCache;
- return this;
- }
-
- /**
- * Sets the minimum and maximum TTL of the cached DNS resource records (in seconds). If the TTL of the DNS
- * resource record returned by the DNS server is less than the minimum TTL or greater than the maximum TTL,
- * this resolver will ignore the TTL from the DNS server and use the minimum TTL or the maximum TTL instead
- * respectively.
- * The default value is {@code 0} and {@link Integer#MAX_VALUE}, which practically tells this resolver to
- * respect the TTL from the DNS server.
- *
- * @param minTtl the minimum TTL
- * @param maxTtl the maximum TTL
- * @return {@code this}
- */
- public DnsNameResolverBuilder ttl(int minTtl, int maxTtl) {
- this.maxTtl = maxTtl;
- this.minTtl = minTtl;
- return this;
- }
-
- /**
- * Sets the TTL of the cache for the failed DNS queries (in seconds).
- *
- * @param negativeTtl the TTL for failed cached queries
- * @return {@code this}
- */
- public DnsNameResolverBuilder negativeTtl(int negativeTtl) {
- this.negativeTtl = negativeTtl;
- return this;
- }
-
- /**
- * Sets the timeout of each DNS query performed by this resolver (in milliseconds).
- *
- * @param queryTimeoutMillis the query timeout
- * @return {@code this}
- */
- public DnsNameResolverBuilder queryTimeoutMillis(long queryTimeoutMillis) {
- this.queryTimeoutMillis = queryTimeoutMillis;
- return this;
- }
-
- /**
- * Sets the list of the protocol families of the address resolved.
- * Usually, both {@link InternetProtocolFamily#IPv4} and {@link InternetProtocolFamily#IPv6} are specified in
- * the order of preference. To enforce the resolve to retrieve the address of a specific protocol family,
- * specify only a single {@link InternetProtocolFamily}.
- *
- * @param resolvedAddressTypes the address types
- * @return {@code this}
- */
- public DnsNameResolverBuilder resolvedAddressTypes(InternetProtocolFamily... resolvedAddressTypes) {
- checkNotNull(resolvedAddressTypes, "resolvedAddressTypes");
-
- final List list =
- InternalThreadLocalMap.get().arrayList(InternetProtocolFamily.values().length);
-
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- if (f == null) {
- break;
- }
-
- // Avoid duplicate entries.
- if (list.contains(f)) {
- continue;
- }
-
- list.add(f);
- }
-
- if (list.isEmpty()) {
- throw new IllegalArgumentException("no protocol family specified");
- }
-
- this.resolvedAddressTypes = list.toArray(new InternetProtocolFamily[list.size()]);
-
- return this;
- }
-
- /**
- * Sets the list of the protocol families of the address resolved.
- * Usually, both {@link InternetProtocolFamily#IPv4} and {@link InternetProtocolFamily#IPv6} are specified in
- * the order of preference. To enforce the resolve to retrieve the address of a specific protocol family,
- * specify only a single {@link InternetProtocolFamily}.
- *
- * @param resolvedAddressTypes the address types
- * @return {@code this}
- */
- public DnsNameResolverBuilder resolvedAddressTypes(Iterable resolvedAddressTypes) {
- checkNotNull(resolvedAddressTypes, "resolveAddressTypes");
-
- final List list =
- InternalThreadLocalMap.get().arrayList(InternetProtocolFamily.values().length);
-
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- if (f == null) {
- break;
- }
-
- // Avoid duplicate entries.
- if (list.contains(f)) {
- continue;
- }
-
- list.add(f);
- }
-
- if (list.isEmpty()) {
- throw new IllegalArgumentException("no protocol family specified");
- }
-
- this.resolvedAddressTypes = list.toArray(new InternetProtocolFamily[list.size()]);
-
- return this;
- }
-
- /**
- * Sets if this resolver has to send a DNS query with the RD (recursion desired) flag set.
- *
- * @param recursionDesired true if recursion is desired
- * @return {@code this}
- */
- public DnsNameResolverBuilder recursionDesired(boolean recursionDesired) {
- this.recursionDesired = recursionDesired;
- return this;
- }
-
- /**
- * Sets the maximum allowed number of DNS queries to send when resolving a host name.
- *
- * @param maxQueriesPerResolve the max number of queries
- * @return {@code this}
- */
- public DnsNameResolverBuilder maxQueriesPerResolve(int maxQueriesPerResolve) {
- this.maxQueriesPerResolve = maxQueriesPerResolve;
- return this;
- }
-
- /**
- * Sets if this resolver should generate the detailed trace information in an exception message so that
- * it is easier to understand the cause of resolution failure.
- *
- * @param traceEnabled true if trace is enabled
- * @return {@code this}
- */
- public DnsNameResolverBuilder traceEnabled(boolean traceEnabled) {
- this.traceEnabled = traceEnabled;
- return this;
- }
-
- /**
- * Sets the capacity of the datagram packet buffer (in bytes). The default value is {@code 4096} bytes.
- *
- * @param maxPayloadSize the capacity of the datagram packet buffer
- * @return {@code this}
- */
- public DnsNameResolverBuilder maxPayloadSize(int maxPayloadSize) {
- this.maxPayloadSize = maxPayloadSize;
- return this;
- }
-
- /**
- * Enable the automatic inclusion of a optional records that tries to give the remote DNS server a hint about
- * how much data the resolver can read per response. Some DNSServer may not support this and so fail to answer
- * queries. If you find problems you may want to disable this.
- *
- * @param optResourceEnabled if optional records inclusion is enabled
- * @return {@code this}
- */
- public DnsNameResolverBuilder optResourceEnabled(boolean optResourceEnabled) {
- this.optResourceEnabled = optResourceEnabled;
- return this;
- }
-
- /**
- * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to first check
- * if the hostname is locally aliased.
- * @return {@code this}
- */
- public DnsNameResolverBuilder hostsFileEntriesResolver(HostsFileEntriesResolver hostsFileEntriesResolver) {
- this.hostsFileEntriesResolver = hostsFileEntriesResolver;
- return this;
- }
-
- /**
- * Set the list of search domains of the resolver.
- *
- * @param searchDomains the search domains
- * @return {@code this}
- */
- public DnsNameResolverBuilder searchDomains(Iterable searchDomains) {
- checkNotNull(searchDomains, "searchDomains");
-
- final List list =
- InternalThreadLocalMap.get().arrayList(4);
-
- for (String f : searchDomains) {
- if (f == null) {
- break;
- }
-
- // Avoid duplicate entries.
- if (list.contains(f)) {
- continue;
- }
-
- list.add(f);
- }
-
- this.searchDomains = list.toArray(new String[list.size()]);
- return this;
- }
-
- /**
- * Set the number of dots which must appear in a name before an initial absolute query is made.
- * The default value is {@code 1}.
- *
- * @param ndots the ndots value
- * @return {@code this}
- */
- public DnsNameResolverBuilder ndots(int ndots) {
- this.ndots = ndots;
- return this;
- }
-
- /**
- * Returns a new {@link DnsNameResolver} instance.
- *
- * @return a {@link DnsNameResolver}
- */
- public DnsNameResolver build() {
-
- if (resolveCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) {
- throw new IllegalStateException("resolveCache and TTLs are mutually exclusive");
- }
-
- DnsCache cache = resolveCache != null ? resolveCache :
- new DefaultDnsCache(intValue(minTtl, 0), intValue(maxTtl, Integer.MAX_VALUE), intValue(negativeTtl, 0));
-
- return new DnsNameResolver(
- eventLoop,
- channelFactory,
- nameServerAddresses,
- cache,
- queryTimeoutMillis,
- resolvedAddressTypes,
- recursionDesired,
- maxQueriesPerResolve,
- traceEnabled,
- maxPayloadSize,
- optResourceEnabled,
- hostsFileEntriesResolver,
- searchDomains,
- ndots);
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java
deleted file mode 100644
index 7c663f7ae8..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java
+++ /dev/null
@@ -1,547 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufHolder;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.socket.InternetProtocolFamily;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.handler.codec.dns.DefaultDnsQuestion;
-import io.netty.handler.codec.dns.DefaultDnsRecordDecoder;
-import io.netty.handler.codec.dns.DnsResponseCode;
-import io.netty.handler.codec.dns.DnsSection;
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.handler.codec.dns.DnsRawRecord;
-import io.netty.handler.codec.dns.DnsRecord;
-import io.netty.handler.codec.dns.DnsRecordType;
-import io.netty.handler.codec.dns.DnsResponse;
-import io.netty.util.ReferenceCountUtil;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.internal.StringUtil;
-import io.netty.util.internal.StringUtil2;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-abstract class DnsNameResolverContext {
-
- private static final int INADDRSZ4 = 4;
- private static final int INADDRSZ6 = 16;
-
- private static final FutureListener> RELEASE_RESPONSE =
- new FutureListener>() {
- @Override
- public void operationComplete(Future> future) {
- if (future.isSuccess()) {
- future.getNow().release();
- }
- }
- };
-
- private final DnsNameResolver parent;
- private final DnsServerAddressStream nameServerAddrs;
- private final String hostname;
- protected String pristineHostname;
- private final DnsCache resolveCache;
- private final boolean traceEnabled;
- private final int maxAllowedQueries;
- private final InternetProtocolFamily[] resolveAddressTypes;
-
- private final Set>> queriesInProgress =
- Collections.newSetFromMap(
- new IdentityHashMap>, Boolean>());
-
- private List resolvedEntries;
- private StringBuilder trace;
- private int allowedQueries;
- private boolean triedCNAME;
-
- protected DnsNameResolverContext(DnsNameResolver parent,
- String hostname,
- DnsCache resolveCache) {
- this.parent = parent;
- this.hostname = hostname;
- this.resolveCache = resolveCache;
-
- nameServerAddrs = parent.nameServerAddresses.stream();
- maxAllowedQueries = parent.maxQueriesPerResolve();
- resolveAddressTypes = parent.resolveAddressTypesUnsafe();
- traceEnabled = parent.isTraceEnabled();
- allowedQueries = maxAllowedQueries;
- }
-
- void resolve(Promise promise) {
- boolean directSearch = parent.searchDomains().length == 0 || StringUtil2.endsWith(hostname, '.');
- if (directSearch) {
- internalResolve(promise);
- } else {
- final Promise original = promise;
- promise = parent.executor().newPromise();
- promise.addListener(new FutureListener() {
- int count;
- @Override
- public void operationComplete(Future future) throws Exception {
- if (future.isSuccess()) {
- original.trySuccess(future.getNow());
- } else if (count < parent.searchDomains().length) {
- String searchDomain = parent.searchDomains()[count++];
- Promise nextPromise = parent.executor().newPromise();
- String nextHostname = DnsNameResolverContext.this.hostname + "." + searchDomain;
- DnsNameResolverContext nextContext = newResolverContext(parent,
- nextHostname, resolveCache);
- nextContext.pristineHostname = hostname;
- nextContext.internalResolve(nextPromise);
- nextPromise.addListener(this);
- } else {
- original.tryFailure(future.cause());
- }
- }
- });
- if (parent.ndots() == 0) {
- internalResolve(promise);
- } else {
- int dots = 0;
- for (int idx = hostname.length() - 1; idx >= 0; idx--) {
- if (hostname.charAt(idx) == '.' && ++dots >= parent.ndots()) {
- internalResolve(promise);
- return;
- }
- }
- promise.tryFailure(new UnknownHostException(hostname));
- }
- }
- }
-
- private void internalResolve(Promise promise) {
- InetSocketAddress nameServerAddrToTry = nameServerAddrs.next();
- for (InternetProtocolFamily f: resolveAddressTypes) {
- final DnsRecordType type;
- switch (f) {
- case IPv4:
- type = DnsRecordType.A;
- break;
- case IPv6:
- type = DnsRecordType.AAAA;
- break;
- default:
- throw new Error();
- }
-
- query(nameServerAddrToTry, new DefaultDnsQuestion(hostname, type), promise);
- }
- }
-
- private void query(InetSocketAddress nameServerAddr, final DnsQuestion question, final Promise promise) {
- if (allowedQueries == 0 || promise.isCancelled()) {
- tryToFinishResolve(promise);
- return;
- }
-
- allowedQueries --;
-
- final Future> f = parent.query(nameServerAddr, question);
- queriesInProgress.add(f);
-
- f.addListener(new FutureListener>() {
- @Override
- public void operationComplete(Future> future) {
- queriesInProgress.remove(future);
-
- if (promise.isDone() || future.isCancelled()) {
- return;
- }
-
- try {
- if (future.isSuccess()) {
- onResponse(question, future.getNow(), promise);
- } else {
- // Server did not respond or I/O error occurred; try again.
- if (traceEnabled) {
- addTrace(future.cause());
- }
- query(nameServerAddrs.next(), question, promise);
- }
- } finally {
- tryToFinishResolve(promise);
- }
- }
- });
- }
-
- void onResponse(final DnsQuestion question, AddressedEnvelope envelope,
- Promise promise) {
- try {
- final DnsResponse res = envelope.content();
- final DnsResponseCode code = res.code();
- if (code == DnsResponseCode.NOERROR) {
- final DnsRecordType type = question.type();
- if (type == DnsRecordType.A || type == DnsRecordType.AAAA) {
- onResponseAorAAAA(type, question, envelope, promise);
- } else if (type == DnsRecordType.CNAME) {
- onResponseCNAME(question, envelope, promise);
- }
- return;
- }
-
- if (traceEnabled) {
- addTrace(envelope.sender(),
- "response code: " + code + " with " + res.count(DnsSection.ANSWER) + " answer(s) and " +
- res.count(DnsSection.AUTHORITY) + " authority resource(s)");
- }
-
- // Retry with the next server if the server did not tell us that the domain does not exist.
- if (code != DnsResponseCode.NXDOMAIN) {
- query(nameServerAddrs.next(), question, promise);
- }
- } finally {
- ReferenceCountUtil.safeRelease(envelope);
- }
- }
-
- private void onResponseAorAAAA(
- DnsRecordType qType, DnsQuestion question, AddressedEnvelope envelope,
- Promise promise) {
-
- // We often get a bunch of CNAMES as well when we asked for A/AAAA.
- final DnsResponse response = envelope.content();
- final Map cnames = buildAliasMap(response);
- final int answerCount = response.count(DnsSection.ANSWER);
-
- boolean found = false;
- for (int i = 0; i < answerCount; i ++) {
- final DnsRecord r = response.recordAt(DnsSection.ANSWER, i);
- final DnsRecordType type = r.type();
- if (type != DnsRecordType.A && type != DnsRecordType.AAAA) {
- continue;
- }
-
- final String qName = question.name().toLowerCase(Locale.US);
- final String rName = r.name().toLowerCase(Locale.US);
-
- // Make sure the record is for the questioned domain.
- if (!rName.equals(qName)) {
- // Even if the record's name is not exactly same, it might be an alias defined in the CNAME records.
- String resolved = qName;
- do {
- resolved = cnames.get(resolved);
- if (rName.equals(resolved)) {
- break;
- }
- } while (resolved != null);
-
- if (resolved == null) {
- continue;
- }
- }
-
- if (!(r instanceof DnsRawRecord)) {
- continue;
- }
-
- final ByteBuf content = ((ByteBufHolder) r).content();
- final int contentLen = content.readableBytes();
- if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) {
- continue;
- }
-
- final byte[] addrBytes = new byte[contentLen];
- content.getBytes(content.readerIndex(), addrBytes);
-
- final InetAddress resolved;
- try {
- resolved = InetAddress.getByAddress(hostname, addrBytes);
- } catch (UnknownHostException e) {
- // Should never reach here.
- throw new Error(e);
- }
-
- if (resolvedEntries == null) {
- resolvedEntries = new ArrayList(8);
- }
-
- final DnsCacheEntry e = new DnsCacheEntry(hostname, resolved);
- resolveCache.cache(hostname, resolved, r.timeToLive(), parent.ch.eventLoop());
- resolvedEntries.add(e);
- found = true;
-
- // Note that we do not break from the loop here, so we decode/cache all A/AAAA records.
- }
-
- if (found) {
- return;
- }
-
- if (traceEnabled) {
- addTrace(envelope.sender(), "no matching " + qType + " record found");
- }
-
- // We aked for A/AAAA but we got only CNAME.
- if (!cnames.isEmpty()) {
- onResponseCNAME(question, envelope, cnames, false, promise);
- }
- }
-
- private void onResponseCNAME(DnsQuestion question, AddressedEnvelope envelope,
- Promise promise) {
- onResponseCNAME(question, envelope, buildAliasMap(envelope.content()), true, promise);
- }
-
- private void onResponseCNAME(
- DnsQuestion question, AddressedEnvelope response,
- Map cnames, boolean trace, Promise promise) {
-
- // Resolve the host name in the question into the real host name.
- final String name = question.name().toLowerCase(Locale.US);
- String resolved = name;
- boolean found = false;
- while (!cnames.isEmpty()) { // Do not attempt to call Map.remove() when the Map is empty
- // because it can be Collections.emptyMap()
- // whose remove() throws a UnsupportedOperationException.
- final String next = cnames.remove(resolved);
- if (next != null) {
- found = true;
- resolved = next;
- } else {
- break;
- }
- }
-
- if (found) {
- followCname(response.sender(), name, resolved, promise);
- } else if (trace && traceEnabled) {
- addTrace(response.sender(), "no matching CNAME record found");
- }
- }
-
- private static Map buildAliasMap(DnsResponse response) {
- final int answerCount = response.count(DnsSection.ANSWER);
- Map cnames = null;
- for (int i = 0; i < answerCount; i ++) {
- final DnsRecord r = response.recordAt(DnsSection.ANSWER, i);
- final DnsRecordType type = r.type();
- if (type != DnsRecordType.CNAME) {
- continue;
- }
-
- if (!(r instanceof DnsRawRecord)) {
- continue;
- }
-
- final ByteBuf recordContent = ((ByteBufHolder) r).content();
- final String domainName = decodeDomainName(recordContent);
- if (domainName == null) {
- continue;
- }
-
- if (cnames == null) {
- cnames = new HashMap();
- }
-
- cnames.put(r.name().toLowerCase(Locale.US), domainName.toLowerCase(Locale.US));
- }
-
- return cnames != null? cnames : Collections.emptyMap();
- }
-
- void tryToFinishResolve(Promise promise) {
- if (!queriesInProgress.isEmpty()) {
- // There are still some queries we did not receive responses for.
- if (gotPreferredAddress()) {
- // But it's OK to finish the resolution process if we got a resolved address of the preferred type.
- finishResolve(promise);
- }
-
- // We did not get any resolved address of the preferred type, so we can't finish the resolution process.
- return;
- }
-
- // There are no queries left to try.
- if (resolvedEntries == null) {
- // .. and we could not find any A/AAAA records.
- if (!triedCNAME) {
- // As the last resort, try to query CNAME, just in case the name server has it.
- triedCNAME = true;
- query(nameServerAddrs.next(), new DefaultDnsQuestion(hostname, DnsRecordType.CNAME), promise);
- return;
- }
- }
-
- // We have at least one resolved address or tried CNAME as the last resort..
- finishResolve(promise);
- }
-
- private boolean gotPreferredAddress() {
- if (resolvedEntries == null) {
- return false;
- }
-
- final int size = resolvedEntries.size();
- switch (resolveAddressTypes[0]) {
- case IPv4:
- for (int i = 0; i < size; i ++) {
- if (resolvedEntries.get(i).address() instanceof Inet4Address) {
- return true;
- }
- }
- break;
- case IPv6:
- for (int i = 0; i < size; i ++) {
- if (resolvedEntries.get(i).address() instanceof Inet6Address) {
- return true;
- }
- }
- break;
- }
-
- return false;
- }
-
- private void finishResolve(Promise promise) {
- if (!queriesInProgress.isEmpty()) {
- // If there are queries in progress, we should cancel it because we already finished the resolution.
- for (Iterator>> i = queriesInProgress.iterator();
- i.hasNext();) {
- Future> f = i.next();
- i.remove();
-
- if (!f.cancel(false)) {
- f.addListener(RELEASE_RESPONSE);
- }
- }
- }
-
- if (resolvedEntries != null) {
- // Found at least one resolved address.
- for (InternetProtocolFamily f: resolveAddressTypes) {
- if (finishResolve(f, resolvedEntries, promise)) {
- return;
- }
- }
- }
-
- // No resolved address found.
- final int tries = maxAllowedQueries - allowedQueries;
- final StringBuilder buf = new StringBuilder(64);
-
- buf.append("failed to resolve '");
- if (pristineHostname != null) {
- buf.append(pristineHostname);
- } else {
- buf.append(hostname);
- }
- buf.append('\'');
- if (tries > 1) {
- if (tries < maxAllowedQueries) {
- buf.append(" after ")
- .append(tries)
- .append(" queries ");
- } else {
- buf.append(". Exceeded max queries per resolve ")
- .append(maxAllowedQueries)
- .append(' ');
- }
- }
- if (trace != null) {
- buf.append(':')
- .append(trace);
- }
- final UnknownHostException cause = new UnknownHostException(buf.toString());
-
- resolveCache.cache(hostname, cause, parent.ch.eventLoop());
- promise.tryFailure(cause);
- }
-
- abstract boolean finishResolve(InternetProtocolFamily f, List resolvedEntries,
- Promise promise);
-
- abstract DnsNameResolverContext newResolverContext(DnsNameResolver parent, String hostname,
- DnsCache resolveCache);
-
- static String decodeDomainName(ByteBuf in) {
- in.markReaderIndex();
- try {
- return DefaultDnsRecordDecoder.decodeName(in);
- } catch (CorruptedFrameException e) {
- // In this case we just return null.
- return null;
- } finally {
- in.resetReaderIndex();
- }
- }
-
- private void followCname(InetSocketAddress nameServerAddr, String name, String cname, Promise promise) {
-
- if (traceEnabled) {
- if (trace == null) {
- trace = new StringBuilder(128);
- }
-
- trace.append(StringUtil.NEWLINE);
- trace.append("\tfrom ");
- trace.append(nameServerAddr);
- trace.append(": ");
- trace.append(name);
- trace.append(" CNAME ");
- trace.append(cname);
- }
-
- final InetSocketAddress nextAddr = nameServerAddrs.next();
- query(nextAddr, new DefaultDnsQuestion(cname, DnsRecordType.A), promise);
- query(nextAddr, new DefaultDnsQuestion(cname, DnsRecordType.AAAA), promise);
- }
-
- private void addTrace(InetSocketAddress nameServerAddr, String msg) {
- assert traceEnabled;
-
- if (trace == null) {
- trace = new StringBuilder(128);
- }
-
- trace.append(StringUtil.NEWLINE);
- trace.append("\tfrom ");
- trace.append(nameServerAddr);
- trace.append(": ");
- trace.append(msg);
- }
-
- private void addTrace(Throwable cause) {
- assert traceEnabled;
-
- if (trace == null) {
- trace = new StringBuilder(128);
- }
-
- trace.append(StringUtil.NEWLINE);
- trace.append("Caused by: ");
- trace.append(cause);
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverException.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverException.java
deleted file mode 100644
index 05eb8757bd..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverException.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.util.internal.EmptyArrays;
-import io.netty.util.internal.ObjectUtil;
-
-import java.net.InetSocketAddress;
-
-/**
- * A {@link RuntimeException} raised when {@link DnsNameResolver} failed to perform a successful query.
- */
-public final class DnsNameResolverException extends RuntimeException {
-
- private static final long serialVersionUID = -8826717909627131850L;
-
- private final InetSocketAddress remoteAddress;
- private final DnsQuestion question;
-
- public DnsNameResolverException(InetSocketAddress remoteAddress, DnsQuestion question, String message) {
- super(message);
- this.remoteAddress = validateRemoteAddress(remoteAddress);
- this.question = validateQuestion(question);
- }
-
- public DnsNameResolverException(
- InetSocketAddress remoteAddress, DnsQuestion question, String message, Throwable cause) {
- super(message, cause);
- this.remoteAddress = validateRemoteAddress(remoteAddress);
- this.question = validateQuestion(question);
- }
-
- private static InetSocketAddress validateRemoteAddress(InetSocketAddress remoteAddress) {
- return ObjectUtil.checkNotNull(remoteAddress, "remoteAddress");
- }
-
- private static DnsQuestion validateQuestion(DnsQuestion question) {
- return ObjectUtil.checkNotNull(question, "question");
- }
-
- /**
- * Returns the {@link InetSocketAddress} of the DNS query that has failed.
- */
- public InetSocketAddress remoteAddress() {
- return remoteAddress;
- }
-
- /**
- * Returns the {@link DnsQuestion} of the DNS query that has failed.
- */
- public DnsQuestion question() {
- return question;
- }
-
- @Override
- public Throwable fillInStackTrace() {
- setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
- return this;
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java
deleted file mode 100644
index 897d2f3b40..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.buffer.Unpooled;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelFutureListener;
-import io.netty.handler.codec.dns.DatagramDnsQuery;
-import io.netty.handler.codec.dns.DefaultDnsRawRecord;
-import io.netty.handler.codec.dns.DnsQuery;
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.handler.codec.dns.DnsRecord;
-import io.netty.handler.codec.dns.DnsRecordType;
-import io.netty.handler.codec.dns.DnsResponse;
-import io.netty.handler.codec.dns.DnsSection;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.GenericFutureListener;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.concurrent.ScheduledFuture;
-import io.netty.util.internal.StringUtil;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.net.InetSocketAddress;
-import java.util.concurrent.TimeUnit;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-final class DnsQueryContext {
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsQueryContext.class);
-
- private final DnsNameResolver parent;
- private final Promise> promise;
- private final int id;
- private final DnsQuestion question;
- private final Iterable additional;
- private final DnsRecord optResource;
- private final InetSocketAddress nameServerAddr;
-
- private final boolean recursionDesired;
- private volatile ScheduledFuture> timeoutFuture;
-
- DnsQueryContext(DnsNameResolver parent,
- InetSocketAddress nameServerAddr,
- DnsQuestion question,
- Iterable additional,
- Promise> promise) {
-
- this.parent = checkNotNull(parent, "parent");
- this.nameServerAddr = checkNotNull(nameServerAddr, "nameServerAddr");
- this.question = checkNotNull(question, "question");
- this.additional = checkNotNull(additional, "additional");
- this.promise = checkNotNull(promise, "promise");
- recursionDesired = parent.isRecursionDesired();
- id = parent.queryContextManager.add(this);
-
- if (parent.isOptResourceEnabled()) {
- optResource = new DefaultDnsRawRecord(
- StringUtil.EMPTY_STRING, DnsRecordType.OPT, parent.maxPayloadSize(), 0, Unpooled.EMPTY_BUFFER);
- } else {
- optResource = null;
- }
- }
-
- InetSocketAddress nameServerAddr() {
- return nameServerAddr;
- }
-
- DnsQuestion question() {
- return question;
- }
-
- void query() {
- final DnsQuestion question = question();
- final InetSocketAddress nameServerAddr = nameServerAddr();
- final DatagramDnsQuery query = new DatagramDnsQuery(null, nameServerAddr, id);
-
- query.setRecursionDesired(recursionDesired);
-
- query.addRecord(DnsSection.QUESTION, question);
-
- for (DnsRecord record:additional) {
- query.addRecord(DnsSection.ADDITIONAL, record);
- }
- if (optResource != null) {
- query.addRecord(DnsSection.ADDITIONAL, optResource);
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("{} WRITE: [{}: {}], {}", parent.ch, id, nameServerAddr, question);
- }
-
- sendQuery(query);
- }
-
- private void sendQuery(final DnsQuery query) {
- if (parent.channelFuture.isDone()) {
- writeQuery(query);
- } else {
- parent.channelFuture.addListener(new GenericFutureListener>() {
- @Override
- public void operationComplete(Future super Channel> future) throws Exception {
- if (future.isSuccess()) {
- writeQuery(query);
- } else {
- promise.tryFailure(future.cause());
- }
- }
- });
- }
- }
-
- private void writeQuery(final DnsQuery query) {
- final ChannelFuture writeFuture = parent.ch.writeAndFlush(query);
- if (writeFuture.isDone()) {
- onQueryWriteCompletion(writeFuture);
- } else {
- writeFuture.addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture future) throws Exception {
- onQueryWriteCompletion(writeFuture);
- }
- });
- }
- }
-
- private void onQueryWriteCompletion(ChannelFuture writeFuture) {
- if (!writeFuture.isSuccess()) {
- setFailure("failed to send a query", writeFuture.cause());
- return;
- }
-
- // Schedule a query timeout task if necessary.
- final long queryTimeoutMillis = parent.queryTimeoutMillis();
- if (queryTimeoutMillis > 0) {
- timeoutFuture = parent.ch.eventLoop().schedule(new Runnable() {
- @Override
- public void run() {
- if (promise.isDone()) {
- // Received a response before the query times out.
- return;
- }
-
- setFailure("query timed out after " + queryTimeoutMillis + " milliseconds", null);
- }
- }, queryTimeoutMillis, TimeUnit.MILLISECONDS);
- }
- }
-
- void finish(AddressedEnvelope extends DnsResponse, InetSocketAddress> envelope) {
- final DnsResponse res = envelope.content();
- if (res.count(DnsSection.QUESTION) != 1) {
- logger.warn("Received a DNS response with invalid number of questions: {}", envelope);
- return;
- }
-
- if (!question().equals(res.recordAt(DnsSection.QUESTION))) {
- logger.warn("Received a mismatching DNS response: {}", envelope);
- return;
- }
-
- setSuccess(envelope);
- }
-
- private void setSuccess(AddressedEnvelope extends DnsResponse, InetSocketAddress> envelope) {
- parent.queryContextManager.remove(nameServerAddr(), id);
-
- // Cancel the timeout task.
- final ScheduledFuture> timeoutFuture = this.timeoutFuture;
- if (timeoutFuture != null) {
- timeoutFuture.cancel(false);
- }
-
- Promise> promise = this.promise;
- if (promise.setUncancellable()) {
- @SuppressWarnings("unchecked")
- AddressedEnvelope castResponse =
- (AddressedEnvelope) envelope.retain();
- promise.setSuccess(castResponse);
- }
- }
-
- private void setFailure(String message, Throwable cause) {
- final InetSocketAddress nameServerAddr = nameServerAddr();
- parent.queryContextManager.remove(nameServerAddr, id);
-
- final StringBuilder buf = new StringBuilder(message.length() + 64);
- buf.append('[')
- .append(nameServerAddr)
- .append("] ")
- .append(message)
- .append(" (no stack trace available)");
-
- final DnsNameResolverException e;
- if (cause != null) {
- e = new DnsNameResolverException(nameServerAddr, question(), buf.toString(), cause);
- } else {
- e = new DnsNameResolverException(nameServerAddr, question(), buf.toString());
- }
-
- promise.tryFailure(e);
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContextManager.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContextManager.java
deleted file mode 100644
index 9c3946c72f..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContextManager.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.util.NetUtil;
-import io.netty.util.collection.IntObjectHashMap;
-import io.netty.util.collection.IntObjectMap;
-import io.netty.util.internal.ThreadLocalRandom;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.HashMap;
-import java.util.Map;
-
-final class DnsQueryContextManager {
-
- /**
- * A map whose key is the DNS server address and value is the map of the DNS query ID and its corresponding
- * {@link DnsQueryContext}.
- */
- final Map> map =
- new HashMap>();
-
- int add(DnsQueryContext qCtx) {
- final IntObjectMap contexts = getOrCreateContextMap(qCtx.nameServerAddr());
-
- int id = ThreadLocalRandom.current().nextInt(1, 65536);
- final int maxTries = 65535 << 1;
- int tries = 0;
-
- synchronized (contexts) {
- for (;;) {
- if (!contexts.containsKey(id)) {
- contexts.put(id, qCtx);
- return id;
- }
-
- id = id + 1 & 0xFFFF;
-
- if (++tries >= maxTries) {
- throw new IllegalStateException("query ID space exhausted: " + qCtx.question());
- }
- }
- }
- }
-
- DnsQueryContext get(InetSocketAddress nameServerAddr, int id) {
- final IntObjectMap contexts = getContextMap(nameServerAddr);
- final DnsQueryContext qCtx;
- if (contexts != null) {
- synchronized (contexts) {
- qCtx = contexts.get(id);
- }
- } else {
- qCtx = null;
- }
-
- return qCtx;
- }
-
- DnsQueryContext remove(InetSocketAddress nameServerAddr, int id) {
- final IntObjectMap contexts = getContextMap(nameServerAddr);
- if (contexts == null) {
- return null;
- }
-
- synchronized (contexts) {
- return contexts.remove(id);
- }
- }
-
- private IntObjectMap getContextMap(InetSocketAddress nameServerAddr) {
- synchronized (map) {
- return map.get(nameServerAddr);
- }
- }
-
- private IntObjectMap getOrCreateContextMap(InetSocketAddress nameServerAddr) {
- synchronized (map) {
- final IntObjectMap contexts = map.get(nameServerAddr);
- if (contexts != null) {
- return contexts;
- }
-
- final IntObjectMap newContexts = new IntObjectHashMap();
- final InetAddress a = nameServerAddr.getAddress();
- final int port = nameServerAddr.getPort();
- map.put(nameServerAddr, newContexts);
-
- if (a instanceof Inet4Address) {
- // Also add the mapping for the IPv4-compatible IPv6 address.
- final Inet4Address a4 = (Inet4Address) a;
- if (a4.isLoopbackAddress()) {
- map.put(new InetSocketAddress(NetUtil.LOCALHOST6, port), newContexts);
- } else {
- map.put(new InetSocketAddress(toCompatAddress(a4), port), newContexts);
- }
- } else if (a instanceof Inet6Address) {
- // Also add the mapping for the IPv4 address if this IPv6 address is compatible.
- final Inet6Address a6 = (Inet6Address) a;
- if (a6.isLoopbackAddress()) {
- map.put(new InetSocketAddress(NetUtil.LOCALHOST4, port), newContexts);
- } else if (a6.isIPv4CompatibleAddress()) {
- map.put(new InetSocketAddress(toIPv4Address(a6), port), newContexts);
- }
- }
-
- return newContexts;
- }
- }
-
- private static Inet6Address toCompatAddress(Inet4Address a4) {
- byte[] b4 = a4.getAddress();
- byte[] b6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b4[0], b4[1], b4[2], b4[3] };
- try {
- return (Inet6Address) InetAddress.getByAddress(b6);
- } catch (UnknownHostException e) {
- throw new Error(e);
- }
- }
-
- private static Inet4Address toIPv4Address(Inet6Address a6) {
- byte[] b6 = a6.getAddress();
- byte[] b4 = { b6[12], b6[13], b6[14], b6[15] };
- try {
- return (Inet4Address) InetAddress.getByAddress(b4);
- } catch (UnknownHostException e) {
- throw new Error(e);
- }
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStream.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStream.java
deleted file mode 100644
index 2e806ef787..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStream.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import java.net.InetSocketAddress;
-
-/**
- * An infinite stream of DNS server addresses.
- */
-public interface DnsServerAddressStream {
- /**
- * Retrieves the next DNS server address from the stream.
- */
- InetSocketAddress next();
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddresses.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddresses.java
deleted file mode 100644
index 0d83fd9eff..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddresses.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project 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 io.netty.resolver.dns;
-
-import io.netty.util.internal.InternalThreadLocalMap;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.lang.reflect.Method;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Provides an infinite sequence of DNS server addresses to {@link DnsNameResolver}.
- */
-@SuppressWarnings("IteratorNextCanNotThrowNoSuchElementException")
-public abstract class DnsServerAddresses {
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsServerAddresses.class);
-
- private static final List DEFAULT_NAME_SERVER_LIST;
- private static final InetSocketAddress[] DEFAULT_NAME_SERVER_ARRAY;
- private static final DnsServerAddresses DEFAULT_NAME_SERVERS;
-
- static {
- final int DNS_PORT = 53;
- final List defaultNameServers = new ArrayList(2);
- try {
- Class> configClass = Class.forName("sun.net.dns.ResolverConfiguration");
- Method open = configClass.getMethod("open");
- Method nameservers = configClass.getMethod("nameservers");
- Object instance = open.invoke(null);
-
- @SuppressWarnings("unchecked")
- final List list = (List) nameservers.invoke(instance);
- for (String a: list) {
- if (a != null) {
- defaultNameServers.add(new InetSocketAddress(InetAddress.getByName(a), DNS_PORT));
- }
- }
- } catch (Exception ignore) {
- // Failed to get the system name server list.
- // Will add the default name servers afterwards.
- }
-
- if (!defaultNameServers.isEmpty()) {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "Default DNS servers: {} (sun.net.dns.ResolverConfiguration)", defaultNameServers);
- }
- } else {
- Collections.addAll(
- defaultNameServers,
- new InetSocketAddress("8.8.8.8", DNS_PORT),
- new InetSocketAddress("8.8.4.4", DNS_PORT));
-
- if (logger.isWarnEnabled()) {
- logger.warn(
- "Default DNS servers: {} (Google Public DNS as a fallback)", defaultNameServers);
- }
- }
-
- DEFAULT_NAME_SERVER_LIST = Collections.unmodifiableList(defaultNameServers);
- DEFAULT_NAME_SERVER_ARRAY = defaultNameServers.toArray(new InetSocketAddress[defaultNameServers.size()]);
- DEFAULT_NAME_SERVERS = sequential(DEFAULT_NAME_SERVER_ARRAY);
- }
-
- /**
- * Returns the list of the system DNS server addresses. If it failed to retrieve the list of the system DNS server
- * addresses from the environment, it will return {@code "8.8.8.8"} and {@code "8.8.4.4"}, the addresses of the
- * Google public DNS servers.
- */
- public static List defaultAddressList() {
- return DEFAULT_NAME_SERVER_LIST;
- }
-
- /**
- * Returns the {@link DnsServerAddresses} that yields the system DNS server addresses sequentially. If it failed to
- * retrieve the list of the system DNS server addresses from the environment, it will use {@code "8.8.8.8"} and
- * {@code "8.8.4.4"}, the addresses of the Google public DNS servers.
- *
- * This method has the same effect with the following code:
- *