converter) {
diff --git a/src/main/java/io/cdap/http/internal/ImmutablePair.java b/src/main/java/io/cdap/http/internal/ImmutablePair.java
index 51c798a..4d4249d 100644
--- a/src/main/java/io/cdap/http/internal/ImmutablePair.java
+++ b/src/main/java/io/cdap/http/internal/ImmutablePair.java
@@ -16,15 +16,14 @@
package io.cdap.http.internal;
-import java.util.Objects;
+import java.util.Arrays;
/**
- * An {@link ImmutablePair} consists of two elements within. The elements once set
- * in the ImmutablePair cannot be modified. The class itself is final, so that it
- * cannot be subclassed. This is general norm for creating Immutable classes.
- * Please note that the {@link ImmutablePair} cannot be modified once set, but the
- * objects within them can be, so in general it means that if there are mutable objects
- * within the pair then the pair itself is effectively mutable.
+ * An {@link ImmutablePair} consists of two elements within. The elements once set in the ImmutablePair cannot
+ * be modified. The class itself is final, so that it cannot be subclassed. This is general norm for creating
+ * Immutable classes. Please note that the {@link ImmutablePair} cannot be modified once set, but the objects
+ * within them can be, so in general it means that if there are mutable objects within the pair then the pair
+ * itself is effectively mutable.
*
*
* ImmutablePair tupleStreamPair= new
@@ -40,74 +39,100 @@
* @param type B
*/
final class ImmutablePair {
- private final A first;
- private final B second;
+ private final A first;
+ private final B second;
- public static ImmutablePair of(A first, B second) {
- return new ImmutablePair<>(first, second);
- }
+ public static ImmutablePair of(A first, B second) {
+ return new ImmutablePair(first, second);
+ }
- /**
- * Constructs a Immutable Pair.
- * @param first object in pair
- * @param second object in pair
- */
- private ImmutablePair(A first, B second) {
- this.first = first;
- this.second = second;
- }
+ /**
+ * Constructs a Immutable Pair.
+ *
+ * @param first object in pair
+ * @param second object in pair
+ */
+ private ImmutablePair(A first, B second) {
+ this.first = first;
+ this.second = second;
+ }
- /**
- * Returns first object from pair.
- * @return first object from pair.
- */
- public A getFirst() {
- return first;
- }
+ /**
+ * Returns first object from pair.
+ *
+ * @return first object from pair.
+ */
+ public A getFirst() {
+ return first;
+ }
- /**
- * Return second object from pair.
- * @return second object from pair.
- */
- public B getSecond() {
- return second;
- }
+ /**
+ * Return second object from pair.
+ *
+ * @return second object from pair.
+ */
+ public B getSecond() {
+ return second;
+ }
- /**
- * Returns a string representation of {@link ImmutablePair} object.
- * @return string representation of this object.
- */
- @Override
- public String toString() {
- return "ImmutablePair{" +
- "first=" + first +
- ", second=" + second +
- '}';
- }
+ /**
+ * Returns a string representation of {@link ImmutablePair} object.
+ *
+ * @return string representation of this object.
+ */
+ @Override
+ public String toString() {
+ return "ImmutablePair{" + "first=" + first + ", second=" + second + '}';
+ }
- /**
- * Returns a hash code value for this object.
- * @return hash code value of this object.
- */
- @Override
- public int hashCode() {
- return Objects.hash(first, second);
- }
+ /**
+ * Returns a hash code value for this object.
+ *
+ * @return hash code value of this object.
+ */
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(new Object[] { first, second });
+ }
- /**
- * Returns whether some other object "is equal" to this object.
- * @param o reference object with which to compare
- * @return true if object is the same as the obj argument; false otherwise.
- */
- @Override
- public boolean equals(Object o) {
- if (o == null) {
- return false;
+ /**
+ * Helper method that replaces Objects.equals(first, second)
+ *
+ * @param first
+ * @param otherFirst
+ * @return True if equals
+ */
+ private boolean equals(Object first, Object otherFirst) {
+ boolean fst;
+ if (first == null) {
+ if (otherFirst == null) {
+ fst = true;
+ } else {
+ return false;
+ }
+ } else if (otherFirst == null) {
+ return false;
+ } else {
+ fst = first.equals(otherFirst);
+ }
+ return fst;
}
- if (!(o instanceof ImmutablePair)) {
- return false;
+
+ /**
+ * Returns whether some other object "is equal" to this object.
+ *
+ * @param o reference object with which to compare
+ * @return true if object is the same as the obj argument; false otherwise.
+ */
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) {
+ return false;
+ }
+ if (!(o instanceof ImmutablePair)) {
+ return false;
+ }
+ ImmutablePair, ?> other = (ImmutablePair, ?>) o;
+ return equals(first, other.first) && equals(second, other.second);
}
- ImmutablePair, ?> other = (ImmutablePair, ?>) o;
- return Objects.equals(first, other.first) && Objects.equals(second, other.second);
- }
}
diff --git a/src/main/java/io/cdap/http/internal/InternalUtil.java b/src/main/java/io/cdap/http/internal/InternalUtil.java
new file mode 100644
index 0000000..c15d1cc
--- /dev/null
+++ b/src/main/java/io/cdap/http/internal/InternalUtil.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright © 2017-2019 Cask Data, Inc.
+ *
+ * Licensed 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.cdap.http.internal;
+
+import java.nio.charset.Charset;
+
+/**
+ * Some utilities
+ *
+ */
+public class InternalUtil {
+ private InternalUtil() {
+ // Empty
+ }
+ /**
+ * Java 6 compatibility
+ */
+ public static final Charset UTF_8 = Charset.forName("UTF-8");
+
+}
diff --git a/src/main/java/io/cdap/http/internal/NonStickyEventExecutorGroup.java b/src/main/java/io/cdap/http/internal/NonStickyEventExecutorGroup.java
index 8959e27..c0645fc 100644
--- a/src/main/java/io/cdap/http/internal/NonStickyEventExecutorGroup.java
+++ b/src/main/java/io/cdap/http/internal/NonStickyEventExecutorGroup.java
@@ -283,7 +283,7 @@ public void run() {
//
// The above cases can be distinguished by performing a
// compareAndSet(NONE, RUNNING). If it returns "false", it is case 1; otherwise it is case 2.
- if (tasks.peek() == null || !state.compareAndSet(NONE, RUNNING)) {
+ if (tasks.isEmpty() || !state.compareAndSet(NONE, RUNNING)) {
return; // done
}
}
diff --git a/src/main/java/io/cdap/http/internal/ParamConvertUtils.java b/src/main/java/io/cdap/http/internal/ParamConvertUtils.java
index feab865..b061d53 100644
--- a/src/main/java/io/cdap/http/internal/ParamConvertUtils.java
+++ b/src/main/java/io/cdap/http/internal/ParamConvertUtils.java
@@ -50,7 +50,7 @@ public final class ParamConvertUtils {
private static final Map, Object> PRIMITIVE_DEFAULTS;
static {
- Map, Object> defaults = new IdentityHashMap<>();
+ Map, Object> defaults = new IdentityHashMap, Object>();
defaults.put(Boolean.TYPE, false);
defaults.put(Character.TYPE, '\0');
defaults.put(Byte.TYPE, (byte) 0);
@@ -276,11 +276,11 @@ private static Converter, Object> createCollectionConverter(Type re
public Object convert(List values) throws Exception {
Collection extends Comparable> collection;
if (rawType == List.class) {
- collection = new ArrayList<>();
+ collection = new ArrayList();
} else if (rawType == Set.class) {
- collection = new LinkedHashSet<>();
+ collection = new LinkedHashSet();
} else {
- collection = new TreeSet<>();
+ collection = new TreeSet();
}
for (String value : values) {
diff --git a/src/main/java/io/cdap/http/internal/PatternPathRouterWithGroups.java b/src/main/java/io/cdap/http/internal/PatternPathRouterWithGroups.java
index f1b63e9..48fc309 100644
--- a/src/main/java/io/cdap/http/internal/PatternPathRouterWithGroups.java
+++ b/src/main/java/io/cdap/http/internal/PatternPathRouterWithGroups.java
@@ -42,7 +42,7 @@ public final class PatternPathRouterWithGroups {
private final List> patternRouteList;
public static PatternPathRouterWithGroups create(int maxPathParts) {
- return new PatternPathRouterWithGroups<>(maxPathParts);
+ return new PatternPathRouterWithGroups(maxPathParts);
}
/**
@@ -50,7 +50,7 @@ public static PatternPathRouterWithGroups create(int maxPathParts) {
*/
public PatternPathRouterWithGroups(int maxPathParts) {
this.maxPathParts = maxPathParts;
- this.patternRouteList = new ArrayList<>();
+ this.patternRouteList = new ArrayList>();
}
/**
@@ -74,7 +74,7 @@ public void add(final String source, final T destination) {
source, maxPathParts));
}
StringBuilder sb = new StringBuilder();
- List groupNames = new ArrayList<>();
+ List groupNames = new ArrayList();
for (String part : parts) {
Matcher groupMatcher = GROUP_PATTERN.matcher(part);
@@ -108,10 +108,10 @@ public List> getDestinations(String path) {
String cleanPath = (path.endsWith("/") && path.length() > 1)
? path.substring(0, path.length() - 1) : path;
- List> result = new ArrayList<>();
+ List> result = new ArrayList>();
for (ImmutablePair patternRoute : patternRouteList) {
- Map groupNameValuesBuilder = new HashMap<>();
+ Map groupNameValuesBuilder = new HashMap();
Matcher matcher = patternRoute.getFirst().matcher(cleanPath);
if (matcher.matches()) {
int matchIndex = 1;
@@ -120,7 +120,7 @@ public List> getDestinations(String path) {
groupNameValuesBuilder.put(name, value);
matchIndex++;
}
- result.add(new RoutableDestination<>(patternRoute.getSecond().getDestination(), groupNameValuesBuilder));
+ result.add(new RoutableDestination(patternRoute.getSecond().getDestination(), groupNameValuesBuilder));
}
}
return result;
diff --git a/src/main/java/io/cdap/http/internal/WrappedHttpResponder.java b/src/main/java/io/cdap/http/internal/WrappedHttpResponder.java
index cf5fab4..f0c687d 100644
--- a/src/main/java/io/cdap/http/internal/WrappedHttpResponder.java
+++ b/src/main/java/io/cdap/http/internal/WrappedHttpResponder.java
@@ -80,7 +80,7 @@ public void sendContent(HttpResponseStatus status, ByteBuf content, HttpHeaders
}
@Override
- public void sendFile(File file, HttpHeaders headers) throws IOException {
+ public void sendFile(File file, HttpHeaders headers) throws Throwable {
delegate.sendFile(file, headers);
runHook(HttpResponseStatus.OK);
}
diff --git a/src/test/java/io/cdap/http/FileUtils.java b/src/test/java/io/cdap/http/FileUtils.java
new file mode 100644
index 0000000..0467672
--- /dev/null
+++ b/src/test/java/io/cdap/http/FileUtils.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright © 2018 Waarp SAS
+ *
+ * Licensed 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.cdap.http;
+
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * A set a file manipulation methods used for testing purposes.
+ */
+public class FileUtils {
+
+ /** Buffer size used for reading and writing. */
+ private static final int BUFFER_SIZE = 8192;
+
+ /**
+ * Reads all bytes from an input stream and writes them to an output stream.
+ * @param in The input stream of the source file.
+ * @param out The output stream of the destination file.
+ * @throws IOException Thrown if the program could not read the input stream or write in the output stream.
+ */
+ private static void copy(InputStream in, OutputStream out) throws IOException {
+ byte[] buf = new byte[BUFFER_SIZE];
+ int n;
+
+ while ((n = in.read(buf)) > 0) {
+ out.write(buf, 0, n);
+ }
+ }
+
+ /**
+ * Copies all bytes from a file to an output stream.
+ * @param source The path of the source file.
+ * @param out The output stream of the destination file.
+ * @throws IOException Thrown if the program could not read the input stream or write in the output stream.
+ */
+ public static void copy(String source, OutputStream out) throws IOException {
+ InputStream in = null;
+ try {
+ in = new FileInputStream(source);
+ copy(in, out);
+ } finally {
+ if (in != null) {
+ in.close();
+ }
+ }
+ }
+
+ /**
+ * Copies all bytes from an input stream to a file.
+ * @param in The input stream of the source file.
+ * @param output The path of the destination file.
+ * @throws IOException Thrown if the program could not read the input stream or write in the output stream.
+ */
+ public static void copy(InputStream in, String output) throws IOException {
+ OutputStream out = null;
+ try {
+ out = new FileOutputStream(output);
+ copy(in, out);
+ } finally {
+ if (out != null) {
+ out.close();
+ }
+ }
+ }
+}
diff --git a/src/test/java/io/cdap/http/HandlerHookTest.java b/src/test/java/io/cdap/http/HandlerHookTest.java
index b198675..bcabb12 100644
--- a/src/test/java/io/cdap/http/HandlerHookTest.java
+++ b/src/test/java/io/cdap/http/HandlerHookTest.java
@@ -50,7 +50,7 @@ public class HandlerHookTest {
private static final TestHandlerHook handlerHook2 = new TestHandlerHook();
@BeforeClass
- public static void setup() throws Exception {
+ public static void setup() throws Throwable {
NettyHttpService.Builder builder = NettyHttpService.builder("test-hook");
builder.setHttpHandlers(new TestHandler());
@@ -155,7 +155,7 @@ public void testUnknownPath() throws Exception {
}
@AfterClass
- public static void teardown() throws Exception {
+ public static void teardown() throws Throwable {
service.stop();
}
@@ -227,7 +227,7 @@ private static int doGet(String resource) throws Exception {
}
private static int doGet(String resource, String key, String value, String...keyValues) throws Exception {
- Map headerMap = new HashMap<>();
+ Map headerMap = new HashMap();
headerMap.put(key, value);
for (int i = 0; i < keyValues.length; i += 2) {
diff --git a/src/test/java/io/cdap/http/HttpServerTest.java b/src/test/java/io/cdap/http/HttpServerTest.java
index 3b6cde1..23c5982 100644
--- a/src/test/java/io/cdap/http/HttpServerTest.java
+++ b/src/test/java/io/cdap/http/HttpServerTest.java
@@ -65,8 +65,7 @@
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
+import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
@@ -128,13 +127,13 @@ public void modify(ChannelPipeline pipeline) {
public static TemporaryFolder tmpFolder = new TemporaryFolder();
@BeforeClass
- public static void setup() throws Exception {
+ public static void setup() throws Throwable {
service = createBaseNettyHttpServiceBuilder().build();
service.start();
}
@AfterClass
- public static void teardown() throws Exception {
+ public static void teardown() throws Throwable {
String serviceName = service.getServiceName();
service.stop();
@@ -172,7 +171,9 @@ public void testUploadDisconnect() throws Exception {
File filePath = new File(tmpFolder.newFolder(), "test.txt");
URI uri = getBaseURI().resolve("/test/v1/stream/upload/file");
- try (Socket socket = createRawSocket(uri.toURL())) {
+ Socket socket = null;
+ try {
+ socket = createRawSocket(uri.toURL());
// Make a PUT call through socket, so that we can close it prematurely
PrintStream printer = new PrintStream(socket.getOutputStream(), true, "UTF-8");
@@ -193,6 +194,10 @@ public void testUploadDisconnect() throws Exception {
}
Assert.assertTrue(counter < 100);
// close the socket prematurely
+ } finally {
+ if (socket != null) {
+ socket.close();
+ }
}
// The file should get removed because of incomplete request due to connection closed
@@ -209,7 +214,7 @@ public void testSendFile() throws IOException {
File filePath = new File(tmpFolder.newFolder(), "test.txt");
HttpURLConnection urlConn = request("/test/v1/stream/file", HttpMethod.POST);
urlConn.setRequestProperty("File-Path", filePath.getAbsolutePath());
- urlConn.getOutputStream().write("content".getBytes(StandardCharsets.UTF_8));
+ urlConn.getOutputStream().write("content".getBytes(Charset.forName("UTF-8")));
Assert.assertEquals(200, urlConn.getResponseCode());
String result = getContent(urlConn);
Assert.assertEquals("content", result);
@@ -256,7 +261,7 @@ private void testStreamUpload(int size) throws IOException {
//test stream upload
HttpURLConnection urlConn = request("/test/v1/stream/upload", HttpMethod.PUT);
- Files.copy(fname.toPath(), urlConn.getOutputStream());
+ FileUtils.copy(fname.getPath(), urlConn.getOutputStream());
Assert.assertEquals(200, urlConn.getResponseCode());
urlConn.disconnect();
}
@@ -271,7 +276,7 @@ public void testStreamUploadFailure() throws IOException {
randf.close();
HttpURLConnection urlConn = request("/test/v1/stream/upload/fail", HttpMethod.PUT);
- Files.copy(fname.toPath(), urlConn.getOutputStream());
+ FileUtils.copy(fname.getPath(), urlConn.getOutputStream());
Assert.assertEquals(500, urlConn.getResponseCode());
urlConn.disconnect();
}
@@ -288,7 +293,7 @@ public void testChunkAggregatedUpload() throws IOException {
//test chunked upload
HttpURLConnection urlConn = request("/test/v1/aggregate/upload", HttpMethod.PUT);
urlConn.setChunkedStreamingMode(1024);
- Files.copy(fname.toPath(), urlConn.getOutputStream());
+ FileUtils.copy(fname.getPath(), urlConn.getOutputStream());
Assert.assertEquals(200, urlConn.getResponseCode());
Assert.assertEquals(size, Integer.parseInt(getContent(urlConn).split(":")[1].trim()));
@@ -307,7 +312,7 @@ public void testChunkAggregatedUploadFailure() throws IOException {
//test chunked upload
HttpURLConnection urlConn = request("/test/v1/aggregate/upload", HttpMethod.PUT);
urlConn.setChunkedStreamingMode(1024);
- Files.copy(fname.toPath(), urlConn.getOutputStream());
+ FileUtils.copy(fname.getPath(), urlConn.getOutputStream());
Assert.assertEquals(413, urlConn.getResponseCode());
urlConn.disconnect();
}
@@ -393,7 +398,7 @@ public Thread newThread(Runnable r) {
}
};
- final BlockingQueue queue = new ArrayBlockingQueue<>(1);
+ final BlockingQueue queue = new ArrayBlockingQueue(1);
Bootstrap bootstrap = new Bootstrap()
.channel(NioSocketChannel.class)
.remoteAddress(url.getHost(), url.getPort())
@@ -420,7 +425,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
// Make one request, expects the connection to remain active.
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, url.getPath(),
- Unpooled.copiedBuffer("data", StandardCharsets.UTF_8));
+ Unpooled.copiedBuffer("data", Charset.forName("UTF-8")));
HttpUtil.setContentLength(request, 4);
channel.writeAndFlush(request);
HttpResponse response = queue.poll(10, TimeUnit.SECONDS);
@@ -434,7 +439,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
// Make one more request, the connection should remain open.
// This request is make with connection: closed
request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, url.getPath(),
- Unpooled.copiedBuffer("data", StandardCharsets.UTF_8));
+ Unpooled.copiedBuffer("data", Charset.forName("UTF-8")));
HttpUtil.setContentLength(request, 4);
HttpUtil.setKeepAlive(request, false);
channel.writeAndFlush(request);
@@ -594,7 +599,7 @@ public void testPrimitiveQueryParam() throws IOException {
@Test
public void testSortedSetQueryParam() throws IOException {
// For collection, if missing parameter, should get defaulted to empty collection
- SortedSet expected = new TreeSet<>();
+ SortedSet expected = new TreeSet();
testContent("/test/v1/sortedSetQueryParam", GSON.toJson(expected), HttpMethod.GET);
expected.add(10);
@@ -645,7 +650,9 @@ public void testConnectionClose() throws Exception {
// Fire http request using raw socket so that we can verify the connection get closed by the server
// after the response.
- try (Socket socket = createRawSocket(url)) {
+ Socket socket = null;
+ try {
+ socket = createRawSocket(url);
PrintStream printer = new PrintStream(socket.getOutputStream(), false, "UTF-8");
printer.printf("GET %s HTTP/1.1\r\n", url.getPath());
printer.printf("Host: %s:%d\r\n", url.getHost(), url.getPort());
@@ -656,6 +663,10 @@ public void testConnectionClose() throws Exception {
// end with an EOF. Otherwise there will be timeout of this test case
String response = getContent(socket.getInputStream());
Assert.assertTrue(response.startsWith("HTTP/1.1 200 OK"));
+ } finally {
+ if (socket != null) {
+ socket.close();
+ }
}
}
@@ -664,7 +675,7 @@ public void testUploadReject() throws Exception {
HttpURLConnection urlConn = request("/test/v1/uploadReject", HttpMethod.POST, true);
try {
urlConn.setChunkedStreamingMode(1024);
- urlConn.getOutputStream().write("Rejected Content".getBytes(StandardCharsets.UTF_8));
+ urlConn.getOutputStream().write("Rejected Content".getBytes(Charset.forName("UTF-8")));
try {
urlConn.getInputStream();
Assert.fail();
@@ -718,21 +729,21 @@ public void testExceptionHandler() throws IOException {
// exception in body consumer's chunk
urlConn = request("/test/v1/stream/customException", HttpMethod.POST);
urlConn.setRequestProperty("failOn", "chunk");
- Files.copy(fname.toPath(), urlConn.getOutputStream());
+ FileUtils.copy(fname.getPath(), urlConn.getOutputStream());
Assert.assertEquals(TestHandler.CustomException.HTTP_RESPONSE_STATUS.code(), urlConn.getResponseCode());
urlConn.disconnect();
// exception in body consumer's onFinish
urlConn = request("/test/v1/stream/customException", HttpMethod.POST);
urlConn.setRequestProperty("failOn", "finish");
- Files.copy(fname.toPath(), urlConn.getOutputStream());
+ FileUtils.copy(fname.getPath(), urlConn.getOutputStream());
Assert.assertEquals(TestHandler.CustomException.HTTP_RESPONSE_STATUS.code(), urlConn.getResponseCode());
urlConn.disconnect();
// exception in body consumer's handleError
urlConn = request("/test/v1/stream/customException", HttpMethod.POST);
urlConn.setRequestProperty("failOn", "error");
- Files.copy(fname.toPath(), urlConn.getOutputStream());
+ FileUtils.copy(fname.getPath(), urlConn.getOutputStream());
Assert.assertEquals(TestHandler.CustomException.HTTP_RESPONSE_STATUS.code(), urlConn.getResponseCode());
urlConn.disconnect();
}
@@ -773,7 +784,7 @@ public void testCompressResponse() throws Exception {
urlConn.setRequestProperty(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.GZIP_DEFLATE.toString());
Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode());
- Assert.assertTrue(urlConn.getHeaderField(HttpHeaderNames.CONTENT_ENCODING.toString()) != null);
+ Assert.assertNotNull(urlConn.getHeaderField(HttpHeaderNames.CONTENT_ENCODING.toString()));
Assert.assertEquals("Testing message", getContent(urlConn));
@@ -798,7 +809,7 @@ public void testContinueHandler() throws Exception {
urlConn.setRequestProperty("Expect", "100-continue");
urlConn.setRequestProperty("File-Path", filePath.getAbsolutePath());
- urlConn.getOutputStream().write("content".getBytes(StandardCharsets.UTF_8));
+ urlConn.getOutputStream().write("content".getBytes(Charset.forName("UTF-8")));
Assert.assertEquals(200, urlConn.getResponseCode());
String result = getContent(urlConn);
Assert.assertEquals("content", result);
@@ -825,7 +836,7 @@ public void testHeaders() throws IOException {
Assert.assertEquals(200, urlConn.getResponseCode());
Map> headers = urlConn.getHeaderFields();
- Assert.assertEquals(new HashSet<>(Arrays.asList("v1", "v2", "v3")), new HashSet<>(headers.get("k1")));
+ Assert.assertEquals(new HashSet(Arrays.asList("v1", "v2", "v3")), new HashSet(headers.get("k1")));
Assert.assertEquals(Collections.singletonList("v1"), headers.get("k2"));
}
@@ -888,10 +899,10 @@ private String getContent(InputStream is) throws IOException {
while (buffer.writeBytes(is, 1024) > 0) {
// no-op
}
- return buffer.toString(StandardCharsets.UTF_8);
+ return buffer.toString(Charset.forName("UTF-8"));
}
private void writeContent(HttpURLConnection urlConn, String content) throws IOException {
- urlConn.getOutputStream().write(content.getBytes(StandardCharsets.UTF_8));
+ urlConn.getOutputStream().write(content.getBytes(Charset.forName("UTF-8")));
}
}
diff --git a/src/test/java/io/cdap/http/HttpsServerTest.java b/src/test/java/io/cdap/http/HttpsServerTest.java
index 683460c..b52bd59 100644
--- a/src/test/java/io/cdap/http/HttpsServerTest.java
+++ b/src/test/java/io/cdap/http/HttpsServerTest.java
@@ -30,8 +30,6 @@
import java.net.Socket;
import java.net.URI;
import java.net.URL;
-import java.nio.file.Files;
-import java.nio.file.StandardCopyOption;
import javax.annotation.Nullable;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
@@ -46,11 +44,17 @@ public class HttpsServerTest extends HttpServerTest {
private static SSLClientContext sslClientContext;
@BeforeClass
- public static void setup() throws Exception {
+ public static void setup() throws Throwable {
File keyStore = tmpFolder.newFile();
-
- try (InputStream is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("cert.jks")) {
- Files.copy(is, keyStore.toPath(), StandardCopyOption.REPLACE_EXISTING);
+
+ InputStream is = null;
+ try {
+ is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("cert.jks");
+ FileUtils.copy(is, keyStore.getPath());
+ } finally {
+ if (is != null) {
+ is.close();
+ }
}
/* IMPORTANT
diff --git a/src/test/java/io/cdap/http/InternalHttpResponderTest.java b/src/test/java/io/cdap/http/InternalHttpResponderTest.java
index 2b31ba9..2f94a7b 100644
--- a/src/test/java/io/cdap/http/InternalHttpResponderTest.java
+++ b/src/test/java/io/cdap/http/InternalHttpResponderTest.java
@@ -32,7 +32,7 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
-import java.nio.charset.StandardCharsets;
+import java.nio.charset.Charset;
import javax.annotation.Nullable;
/**
@@ -49,9 +49,16 @@ public void testSendJson() throws IOException {
InternalHttpResponse response = responder.getResponse();
Assert.assertEquals(HttpResponseStatus.OK.code(), response.getStatusCode());
- try (Reader reader = new InputStreamReader(response.openInputStream(), "UTF-8")) {
+
+ Reader reader = null;
+ try {
+ reader = new InputStreamReader(response.openInputStream(), "UTF-8");
JsonObject responseData = new Gson().fromJson(reader, JsonObject.class);
Assert.assertEquals(output, responseData);
+ } finally {
+ if (reader != null) {
+ reader.close();
+ }
}
}
@@ -74,7 +81,7 @@ public void testSendStatus() throws IOException {
@Test
public void testSendByteArray() throws IOException {
InternalHttpResponder responder = new InternalHttpResponder();
- responder.sendByteArray(HttpResponseStatus.OK, "abc".getBytes(StandardCharsets.UTF_8), EmptyHttpHeaders.INSTANCE);
+ responder.sendByteArray(HttpResponseStatus.OK, "abc".getBytes(Charset.forName("UTF-8")), EmptyHttpHeaders.INSTANCE);
validateResponse(responder.getResponse(), HttpResponseStatus.OK, "abc");
}
@@ -91,9 +98,9 @@ public void testSendError() throws IOException {
public void testChunks() throws IOException {
InternalHttpResponder responder = new InternalHttpResponder();
ChunkResponder chunkResponder = responder.sendChunkStart(HttpResponseStatus.OK, null);
- chunkResponder.sendChunk(Unpooled.wrappedBuffer("a".getBytes(StandardCharsets.UTF_8)));
- chunkResponder.sendChunk(Unpooled.wrappedBuffer("b".getBytes(StandardCharsets.UTF_8)));
- chunkResponder.sendChunk(Unpooled.wrappedBuffer("c".getBytes(StandardCharsets.UTF_8)));
+ chunkResponder.sendChunk(Unpooled.wrappedBuffer("a".getBytes(Charset.forName("UTF-8"))));
+ chunkResponder.sendChunk(Unpooled.wrappedBuffer("b".getBytes(Charset.forName("UTF-8"))));
+ chunkResponder.sendChunk(Unpooled.wrappedBuffer("c".getBytes(Charset.forName("UTF-8"))));
chunkResponder.close();
validateResponse(responder.getResponse(), HttpResponseStatus.OK, "abc");
@@ -102,7 +109,7 @@ public void testChunks() throws IOException {
@Test
public void testSendContent() throws IOException {
InternalHttpResponder responder = new InternalHttpResponder();
- responder.sendContent(HttpResponseStatus.OK, Unpooled.wrappedBuffer("abc".getBytes(StandardCharsets.UTF_8)),
+ responder.sendContent(HttpResponseStatus.OK, Unpooled.wrappedBuffer("abc".getBytes(Charset.forName("UTF-8"))),
new DefaultHttpHeaders().set(HttpHeaderNames.CONTENT_TYPE, "contentType"));
validateResponse(responder.getResponse(), HttpResponseStatus.OK, "abc");
@@ -116,9 +123,15 @@ private void validateResponse(InternalHttpResponse response, HttpResponseStatus
if (expectedData != null) {
// read it twice to make sure the input supplier gives the full stream more than once.
for (int i = 0; i < 2; i++) {
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.openInputStream(), "UTF-8"))) {
+ BufferedReader reader = null;
+ try {
+ reader = new BufferedReader(new InputStreamReader(response.openInputStream(), "UTF-8"));
String data = reader.readLine();
Assert.assertEquals(expectedData, data);
+ } finally {
+ if (reader != null) {
+ reader.close();
+ }
}
}
}
diff --git a/src/test/java/io/cdap/http/MutualAuthServerTest.java b/src/test/java/io/cdap/http/MutualAuthServerTest.java
index 25c080b..0537048 100644
--- a/src/test/java/io/cdap/http/MutualAuthServerTest.java
+++ b/src/test/java/io/cdap/http/MutualAuthServerTest.java
@@ -20,8 +20,7 @@
import java.io.File;
import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.StandardCopyOption;
+import java.net.URI;
/**
* Test the HttpsServer with mutual authentication.
@@ -29,17 +28,29 @@
public class MutualAuthServerTest extends HttpsServerTest {
@BeforeClass
- public static void setup() throws Exception {
+ public static void setup() throws Throwable {
NettyHttpService.Builder builder = createBaseNettyHttpServiceBuilder();
File keyStore = tmpFolder.newFile();
- try (InputStream is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("cert.jks")) {
- Files.copy(is, keyStore.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ InputStream is = null;
+ try {
+ is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("cert.jks");
+ FileUtils.copy(is, keyStore.getPath());
+ } finally {
+ if (is != null) {
+ is.close();
+ }
}
File trustKeyStore = tmpFolder.newFile();
- try (InputStream is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("client.jks")) {
- Files.copy(is, trustKeyStore.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ is = null;
+ try {
+ is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("client.jks");
+ FileUtils.copy(is, trustKeyStore.getPath());
+ } finally {
+ if (is != null) {
+ is.close();
+ }
}
String keyStorePassword = "secret";
diff --git a/src/test/java/io/cdap/http/PathRouterTest.java b/src/test/java/io/cdap/http/PathRouterTest.java
index 41202a8..7f35e19 100644
--- a/src/test/java/io/cdap/http/PathRouterTest.java
+++ b/src/test/java/io/cdap/http/PathRouterTest.java
@@ -109,8 +109,9 @@ public void testPathRoutings() {
routes = pathRouter.getDestinations("/multi/match/def");
Assert.assertEquals(2, routes.size());
- Assert.assertEquals(new HashSet<>(Arrays.asList("multi-match-def", "multi-match-*")),
- new HashSet<>(Arrays.asList(routes.get(0).getDestination(), routes.get(1).getDestination())));
+ Assert.assertEquals(new HashSet(Arrays.asList("multi-match-def", "multi-match-*")),
+ new HashSet(Arrays.asList(routes.get(0).getDestination(),
+ routes.get(1).getDestination())));
Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty());
Assert.assertTrue(routes.get(1).getGroupNameValues().isEmpty());
@@ -121,35 +122,38 @@ public void testPathRoutings() {
routes = pathRouter.getDestinations("/multi/maxmatch/id1");
Assert.assertEquals(2, routes.size());
- Assert.assertEquals(new HashSet<>(Arrays.asList("multi-max-match-id", "multi-max-match-*")),
- new HashSet<>(Arrays.asList(routes.get(0).getDestination(), routes.get(1).getDestination())));
+ Assert.assertEquals(new HashSet(Arrays.asList("multi-max-match-id", "multi-max-match-*")),
+ new HashSet(Arrays.asList(routes.get(0).getDestination(),
+ routes.get(1).getDestination())));
- Assert.assertEquals(new HashSet<>(Arrays.asList(Collections.singletonMap("id", "id1"),
+ Assert.assertEquals(new HashSet>(Arrays.asList(Collections.singletonMap("id", "id1"),
Collections.emptyMap())),
- new HashSet<>(Arrays.asList(routes.get(0).getGroupNameValues(),
+ new HashSet>(Arrays.asList(routes.get(0).getGroupNameValues(),
routes.get(1).getGroupNameValues()))
);
routes = pathRouter.getDestinations("/multi/maxmatch/foo");
Assert.assertEquals(3, routes.size());
- Assert.assertEquals(new HashSet<>(Arrays.asList("multi-max-match-id", "multi-max-match-*", "multi-max-match-foo")),
- new HashSet<>(Arrays.asList(routes.get(0).getDestination(), routes.get(1).getDestination(),
- routes.get(2).getDestination())));
+ Assert.assertEquals(new HashSet(Arrays.asList("multi-max-match-id", "multi-max-match-*",
+ "multi-max-match-foo")),
+ new HashSet(Arrays.asList(routes.get(0).getDestination(),
+ routes.get(1).getDestination(), routes.get(2).getDestination())));
- Assert.assertEquals(new HashSet<>(Arrays.asList(Collections.singletonMap("id", "foo"),
+ Assert.assertEquals(new HashSet>(Arrays.asList(Collections.singletonMap("id", "foo"),
Collections.emptyMap())),
- new HashSet<>(Arrays.asList(routes.get(0).getGroupNameValues(),
+ new HashSet>(Arrays.asList(routes.get(0).getGroupNameValues(),
routes.get(1).getGroupNameValues()))
);
routes = pathRouter.getDestinations("/foo/bar/wildcard/id1");
Assert.assertEquals(2, routes.size());
- Assert.assertEquals(new HashSet<>(Arrays.asList("wildcard-id", "slash-wildcard-id")),
- new HashSet<>(Arrays.asList(routes.get(0).getDestination(), routes.get(1).getDestination())));
+ Assert.assertEquals(new HashSet(Arrays.asList("wildcard-id", "slash-wildcard-id")),
+ new HashSet(Arrays.asList(routes.get(0).getDestination(),
+ routes.get(1).getDestination())));
- Assert.assertEquals(new HashSet<>(Arrays.asList(Collections.singletonMap("id", "id1"),
+ Assert.assertEquals(new HashSet>(Arrays.asList(Collections.singletonMap("id", "id1"),
Collections.singletonMap("id", "id1"))),
- new HashSet<>(Arrays.asList(routes.get(0).getGroupNameValues(),
+ new HashSet>(Arrays.asList(routes.get(0).getGroupNameValues(),
routes.get(1).getGroupNameValues()))
);
@@ -160,23 +164,25 @@ public void testPathRoutings() {
routes = pathRouter.getDestinations("/foo/bar/wildcard/bar/foo/id1");
Assert.assertEquals(2, routes.size());
- Assert.assertEquals(new HashSet<>(Arrays.asList("wildcard-foo-id", "slash-wildcard-foo-id")),
- new HashSet<>(Arrays.asList(routes.get(0).getDestination(), routes.get(1).getDestination())));
+ Assert.assertEquals(new HashSet(Arrays.asList("wildcard-foo-id", "slash-wildcard-foo-id")),
+ new HashSet(Arrays.asList(routes.get(0).getDestination(),
+ routes.get(1).getDestination())));
- Assert.assertEquals(new HashSet<>(Arrays.asList(Collections.singletonMap("id", "id1"),
+ Assert.assertEquals(new HashSet>(Arrays.asList(Collections.singletonMap("id", "id1"),
Collections.singletonMap("id", "id1"))),
- new HashSet<>(Arrays.asList(routes.get(0).getGroupNameValues(),
+ new HashSet>(Arrays.asList(routes.get(0).getGroupNameValues(),
routes.get(1).getGroupNameValues()))
);
routes = pathRouter.getDestinations("/foo/bar/wildcard/bar/foo/id1/baz/bar");
Assert.assertEquals(2, routes.size());
- Assert.assertEquals(new HashSet<>(Arrays.asList("wildcard-foo-id-2", "slash-wildcard-foo-id-2")),
- new HashSet<>(Arrays.asList(routes.get(0).getDestination(), routes.get(1).getDestination())));
+ Assert.assertEquals(new HashSet(Arrays.asList("wildcard-foo-id-2", "slash-wildcard-foo-id-2")),
+ new HashSet(Arrays.asList(routes.get(0).getDestination(),
+ routes.get(1).getDestination())));
- Assert.assertEquals(new HashSet<>(Arrays.asList(Collections.singletonMap("id", "id1"),
+ Assert.assertEquals(new HashSet>(Arrays.asList(Collections.singletonMap("id", "id1"),
Collections.singletonMap("id", "id1"))),
- new HashSet<>(Arrays.asList(routes.get(0).getGroupNameValues(),
+ new HashSet>(Arrays.asList(routes.get(0).getGroupNameValues(),
routes.get(1).getGroupNameValues()))
);
diff --git a/src/test/java/io/cdap/http/SSLClientContext.java b/src/test/java/io/cdap/http/SSLClientContext.java
index 8f8be60..1c1fae9 100644
--- a/src/test/java/io/cdap/http/SSLClientContext.java
+++ b/src/test/java/io/cdap/http/SSLClientContext.java
@@ -57,7 +57,9 @@ public SSLClientContext(File keyStore, String keyStorePassword) {
}
private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws IOException {
- try (InputStream is = new FileInputStream(keyStore)) {
+ InputStream is = null;
+ try {
+ is = new FileInputStream(keyStore);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(is, keyStorePassword.toCharArray());
return ks;
@@ -66,6 +68,10 @@ private static KeyStore getKeyStore(File keyStore, String keyStorePassword) thro
throw ((RuntimeException) ex);
}
throw new IOException(ex);
+ } finally {
+ if (is != null) {
+ is.close();
+ }
}
}
diff --git a/src/test/java/io/cdap/http/SSLKeyStoreTest.java b/src/test/java/io/cdap/http/SSLKeyStoreTest.java
index 325dbdc..fa1e339 100644
--- a/src/test/java/io/cdap/http/SSLKeyStoreTest.java
+++ b/src/test/java/io/cdap/http/SSLKeyStoreTest.java
@@ -23,8 +23,6 @@
import java.io.File;
import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.StandardCopyOption;
/**
* Tests SSL KeyStore behaviour
@@ -38,8 +36,14 @@ public class SSLKeyStoreTest {
@BeforeClass
public static void setup() throws Exception {
keyStore = tmpFolder.newFile();
- try (InputStream is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("cert.jks")) {
- Files.copy(is, keyStore.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ InputStream is = null;
+ try {
+ is = SSLKeyStoreTest.class.getClassLoader().getResourceAsStream("cert.jks");
+ FileUtils.copy(is, keyStore.getPath());
+ } finally {
+ if (is != null) {
+ is.close();
+ }
}
}
diff --git a/src/test/java/io/cdap/http/TestHandler.java b/src/test/java/io/cdap/http/TestHandler.java
index 5904d24..256c7ac 100644
--- a/src/test/java/io/cdap/http/TestHandler.java
+++ b/src/test/java/io/cdap/http/TestHandler.java
@@ -37,7 +37,7 @@
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
-import java.nio.charset.StandardCharsets;
+import java.nio.charset.Charset;
import java.util.List;
import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
@@ -170,7 +170,7 @@ public void exception(HttpRequest request, HttpResponder responder) {
}
private String getStringContent(FullHttpRequest request) throws IOException {
- return request.content().toString(StandardCharsets.UTF_8);
+ return request.content().toString(Charset.forName("UTF-8"));
}
@Path("/multi-match/**")
@@ -366,6 +366,7 @@ public void finished(HttpResponder responder) {
responder.sendFile(file);
} catch (IOException e) {
throw new RuntimeException(e);
+ } catch (Throwable e) {
}
}
@@ -399,6 +400,7 @@ public void chunk(FullHttpRequest request, HttpResponder responder) throws IOExc
while (content.isReadable()) {
chunker.sendChunk(content.readBytes(1));
}
+ content.release();
chunker.close();
}
@@ -415,7 +417,7 @@ public void produceBody(HttpRequest request, HttpResponder responder,
@Override
public ByteBuf nextChunk() {
if (times < repeat) {
- return Unpooled.wrappedBuffer(StandardCharsets.UTF_8.encode(chunk + " " + times++));
+ return Unpooled.wrappedBuffer(Charset.forName("UTF-8").encode(chunk + " " + times++));
}
return Unpooled.EMPTY_BUFFER;
}
@@ -429,12 +431,18 @@ public void finished() throws Exception {
@Override
public void handleError(@Nullable Throwable cause) {
- try (PrintStream printer = new PrintStream(new FileOutputStream(new File(failureFile)), true)) {
+ PrintStream printer = null;
+ try {
+ printer = new PrintStream(new FileOutputStream(new File(failureFile)), true);
if (cause != null) {
cause.printStackTrace(printer);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
+ } finally {
+ if (printer != null) {
+ printer.close();
+ }
}
}
}, EmptyHttpHeaders.INSTANCE);
@@ -560,7 +568,7 @@ public void testCompressResponse(HttpRequest request, HttpResponder responder,
return;
}
- final ByteBuf content = Unpooled.copiedBuffer(message, StandardCharsets.UTF_8);
+ final ByteBuf content = Unpooled.copiedBuffer(message, Charset.forName("UTF-8"));
if (!chunk) {
responder.sendContent(HttpResponseStatus.OK, content, EmptyHttpHeaders.INSTANCE);
} else {
diff --git a/src/test/java/io/cdap/http/URLRewriterTest.java b/src/test/java/io/cdap/http/URLRewriterTest.java
index d3f0faa..583e4a5 100644
--- a/src/test/java/io/cdap/http/URLRewriterTest.java
+++ b/src/test/java/io/cdap/http/URLRewriterTest.java
@@ -35,7 +35,7 @@
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
-import java.nio.charset.StandardCharsets;
+import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
@@ -51,7 +51,7 @@ public class URLRewriterTest {
private static URI baseURI;
@BeforeClass
- public static void setup() throws Exception {
+ public static void setup() throws Throwable {
NettyHttpService.Builder builder = NettyHttpService.builder("test-url-rewrite");
builder.setHttpHandlers(new TestHandler());
@@ -66,7 +66,7 @@ public static void setup() throws Exception {
}
@AfterClass
- public static void teardown() throws Exception {
+ public static void teardown() throws Throwable {
service.stop();
}
@@ -162,6 +162,6 @@ private String getContent(HttpURLConnection urlConn) throws IOException {
while (buffer.writeBytes(is, 1024) > 0) {
// no-op
}
- return buffer.toString(StandardCharsets.UTF_8);
+ return buffer.toString(Charset.forName("UTF-8"));
}
}