diff options
227 files changed, 8308 insertions, 7691 deletions
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 227b6ce77..f82e8a4da 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -77,6 +77,11 @@ jobs: sudo ln -s /usr/local/gradle/bin/gradle /usr/local/bin gradle --version + - name: Run spotlessCheck + run: | + cd lib/java + gradle spotlessCheck + - name: Run bootstrap run: ./bootstrap.sh diff --git a/lib/java/build.gradle b/lib/java/build.gradle index 6bd2ec403..726d7b7f6 100644 --- a/lib/java/build.gradle +++ b/lib/java/build.gradle @@ -41,6 +41,7 @@ plugins { id 'signing' id 'com.github.johnrengelman.shadow' version '4.0.4' id "com.github.spotbugs" version "4.7.1" + id "com.diffplug.spotless" version "6.4.2" } description = 'Apache Thrift Java Library' diff --git a/lib/java/gradle/codeQualityChecks.gradle b/lib/java/gradle/codeQualityChecks.gradle index a3530979b..f633413cd 100644 --- a/lib/java/gradle/codeQualityChecks.gradle +++ b/lib/java/gradle/codeQualityChecks.gradle @@ -43,3 +43,12 @@ tasks.withType(Pmd) { xml.enabled = false } } + +spotless { + java { + target project.fileTree(project.rootDir) { + include 'src/**/*.java' + } + googleJavaFormat() + } +} diff --git a/lib/java/src/crossTest/java/org/apache/thrift/test/TestClient.java b/lib/java/src/crossTest/java/org/apache/thrift/test/TestClient.java index 2861a1d6b..32ac88f78 100644 --- a/lib/java/src/crossTest/java/org/apache/thrift/test/TestClient.java +++ b/lib/java/src/crossTest/java/org/apache/thrift/test/TestClient.java @@ -26,7 +26,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.http.impl.client.HttpClients; import org.apache.thrift.TApplicationException; import org.apache.thrift.TException; @@ -37,16 +36,14 @@ import org.apache.thrift.protocol.TJSONProtocol; import org.apache.thrift.protocol.TMultiplexedProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TSimpleJSONProtocol; -import org.apache.thrift.transport.layered.TFastFramedTransport; -import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.THttpClient; import org.apache.thrift.transport.TSSLTransportFactory; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.transport.TZlibTransport; - -// Generated code +import org.apache.thrift.transport.layered.TFastFramedTransport; +import org.apache.thrift.transport.layered.TFramedTransport; import thrift.test.Insanity; import thrift.test.Numberz; import thrift.test.SecondService; @@ -57,10 +54,8 @@ import thrift.test.Xtruct; import thrift.test.Xtruct2; /** - * Test Java client for thrift. Essentially just a copy of the C++ version, - * this makes a variety of requests to enable testing for both performance and - * correctness of the output. - * + * Test Java client for thrift. Essentially just a copy of the C++ version, this makes a variety of + * requests to enable testing for both performance and correctness of the output. */ public class TestClient { @@ -71,7 +66,7 @@ public class TestClient { private static int ERR_PROTOCOLS = 16; private static int ERR_UNKNOWN = 64; - public static void main(String [] args) { + public static void main(String[] args) { String host = "localhost"; int port = 9090; int numTests = 1; @@ -90,8 +85,7 @@ public class TestClient { host.trim(); } else if (args[i].startsWith("--port")) { port = Integer.valueOf(args[i].split("=")[1]); - } else if (args[i].startsWith("--n") || - args[i].startsWith("--testloops")){ + } else if (args[i].startsWith("--n") || args[i].startsWith("--testloops")) { numTests = Integer.valueOf(args[i].split("=")[1]); } else if (args[i].equals("--timeout")) { socketTimeout = Integer.valueOf(args[i].split("=")[1]); @@ -112,8 +106,14 @@ public class TestClient { System.out.println(" --help\t\t\tProduce help message"); System.out.println(" --host=arg (=" + host + ")\tHost to connect"); System.out.println(" --port=arg (=" + port + ")\tPort number to connect"); - System.out.println(" --transport=arg (=" + transport_type + ")\n\t\t\t\tTransport: buffered, framed, fastframed, http, zlib"); - System.out.println(" --protocol=arg (=" + protocol_type + ")\tProtocol: binary, compact, json, multi, multic, multij"); + System.out.println( + " --transport=arg (=" + + transport_type + + ")\n\t\t\t\tTransport: buffered, framed, fastframed, http, zlib"); + System.out.println( + " --protocol=arg (=" + + protocol_type + + ")\tProtocol: binary, compact, json, multi, multic, multij"); System.out.println(" --ssl\t\t\tEncrypted Transport using SSL"); System.out.println(" --zlib\t\t\tCompressed Transport using Zlib"); System.out.println(" --testloops[--n]=arg (=" + numTests + ")\tNumber of Tests"); @@ -215,10 +215,8 @@ public class TestClient { int returnCode = 0; for (int test = 0; test < numTests; ++test) { try { - /** - * CONNECT TEST - */ - System.out.println("Test #" + (test+1) + ", " + "connect " + host + ":" + port); + /** CONNECT TEST */ + System.out.println("Test #" + (test + 1) + ", " + "connect " + host + ":" + port); if (transport.isOpen() == false) { try { @@ -232,9 +230,7 @@ public class TestClient { long start = System.nanoTime(); - /** - * VOID TEST - */ + /** VOID TEST */ try { System.out.print("testVoid()"); testClient.testVoid(); @@ -244,9 +240,7 @@ public class TestClient { returnCode |= ERR_BASETYPES; } - /** - * STRING TEST - */ + /** STRING TEST */ System.out.print("testString(\"Test\")"); String s = testClient.testString("Test"); System.out.print(" = \"" + s + "\"\n"); @@ -255,9 +249,7 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * Multiplexed test - */ + /** Multiplexed test */ if (protocol_type.startsWith("multi")) { SecondService.Client secondClient = new SecondService.Client(tProtocol2); System.out.print("secondtestString(\"Test2\")"); @@ -268,20 +260,16 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } } - /** - * BYTE TEST - */ + /** BYTE TEST */ System.out.print("testByte(1)"); - byte i8 = testClient.testByte((byte)1); + byte i8 = testClient.testByte((byte) 1); System.out.print(" = " + i8 + "\n"); if (i8 != 1) { returnCode |= ERR_BASETYPES; System.out.println("*** FAILURE ***\n"); } - /** - * I32 TEST - */ + /** I32 TEST */ System.out.print("testI32(-1)"); int i32 = testClient.testI32(-1); System.out.print(" = " + i32 + "\n"); @@ -290,9 +278,7 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * I64 TEST - */ + /** I64 TEST */ System.out.print("testI64(-34359738368)"); long i64 = testClient.testI64(-34359738368L); System.out.print(" = " + i64 + "\n"); @@ -301,9 +287,7 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * DOUBLE TEST - */ + /** DOUBLE TEST */ System.out.print("testDouble(-5.325098235)"); double dub = testClient.testDouble(-5.325098235); System.out.print(" = " + dub + "\n"); @@ -312,12 +296,27 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * BINARY TEST - */ + /** BINARY TEST */ try { System.out.print("testBinary(-128...127) = "); - byte[] data = new byte[] {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114, -113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99, -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84, -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127}; + byte[] data = + new byte[] { + -128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, + -114, -113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, + -100, -99, -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, + -84, -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, -68, + -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, -53, -52, -51, + -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, + -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, + -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, + 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, + 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, + 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, + 125, 126, 127 + }; ByteBuffer bin = testClient.testBinary(ByteBuffer.wrap(data)); bin.mark(); byte[] bytes = new byte[bin.limit() - bin.position()]; @@ -326,10 +325,8 @@ public class TestClient { System.out.print("{"); boolean first = true; for (int i = 0; i < bytes.length; ++i) { - if (first) - first = false; - else - System.out.print(", "); + if (first) first = false; + else System.out.print(", "); System.out.print(bytes[i]); } System.out.println("}"); @@ -343,9 +340,7 @@ public class TestClient { ex.printStackTrace(System.out); } - /** - * STRUCT TEST - */ + /** STRUCT TEST */ System.out.print("testStruct({\"Zero\", 1, -3, -5})"); Xtruct out = new Xtruct(); out.string_thing = "Zero"; @@ -353,43 +348,54 @@ public class TestClient { out.i32_thing = -3; out.i64_thing = -5; Xtruct in = testClient.testStruct(out); - System.out.print(" = {" + "\"" + - in.string_thing + "\"," + - in.byte_thing + ", " + - in.i32_thing + ", " + - in.i64_thing + "}\n"); + System.out.print( + " = {" + + "\"" + + in.string_thing + + "\"," + + in.byte_thing + + ", " + + in.i32_thing + + ", " + + in.i64_thing + + "}\n"); if (!in.equals(out)) { returnCode |= ERR_STRUCTS; System.out.println("*** FAILURE ***\n"); } - /** - * NESTED STRUCT TEST - */ + /** NESTED STRUCT TEST */ System.out.print("testNest({1, {\"Zero\", 1, -3, -5}), 5}"); Xtruct2 out2 = new Xtruct2(); - out2.byte_thing = (short)1; + out2.byte_thing = (short) 1; out2.struct_thing = out; out2.i32_thing = 5; Xtruct2 in2 = testClient.testNest(out2); in = in2.struct_thing; - System.out.print(" = {" + in2.byte_thing + ", {" + "\"" + - in.string_thing + "\", " + - in.byte_thing + ", " + - in.i32_thing + ", " + - in.i64_thing + "}, " + - in2.i32_thing + "}\n"); + System.out.print( + " = {" + + in2.byte_thing + + ", {" + + "\"" + + in.string_thing + + "\", " + + in.byte_thing + + ", " + + in.i32_thing + + ", " + + in.i64_thing + + "}, " + + in2.i32_thing + + "}\n"); if (!in2.equals(out2)) { returnCode |= ERR_STRUCTS; System.out.println("*** FAILURE ***\n"); } - /** - * MAP TEST - */ - Map<Integer,Integer> mapout = new HashMap<Integer,Integer>(); + /** MAP TEST */ + Map<Integer, Integer> mapout = new HashMap<Integer, Integer>(); for (int i = 0; i < 5; ++i) { - mapout.put(i, i-10); + mapout.put(i, i - 10); } System.out.print("testMap({"); boolean first = true; @@ -402,7 +408,7 @@ public class TestClient { System.out.print(key + " => " + mapout.get(key)); } System.out.print("})"); - Map<Integer,Integer> mapin = testClient.testMap(mapout); + Map<Integer, Integer> mapin = testClient.testMap(mapout); System.out.print(" = {"); first = true; for (int key : mapin.keySet()) { @@ -419,9 +425,7 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * STRING MAP TEST - */ + /** STRING MAP TEST */ try { Map<String, String> smapout = new HashMap<String, String>(); smapout.put("a", "2"); @@ -458,9 +462,7 @@ public class TestClient { ex.printStackTrace(System.out); } - /** - * SET TEST - */ + /** SET TEST */ Set<Integer> setout = new HashSet<Integer>(); for (int i = -2; i < 3; ++i) { setout.add(i); @@ -493,9 +495,7 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * LIST TEST - */ + /** LIST TEST */ List<Integer> listout = new ArrayList<Integer>(); for (int i = -2; i < 3; ++i) { listout.add(i); @@ -528,9 +528,7 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * ENUM TEST - */ + /** ENUM TEST */ System.out.print("testEnum(ONE)"); Numberz ret = testClient.testEnum(Numberz.ONE); System.out.print(" = " + ret + "\n"); @@ -571,9 +569,7 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * TYPEDEF TEST - */ + /** TYPEDEF TEST */ System.out.print("testTypedef(309858235082523)"); long uid = testClient.testTypedef(309858235082523L); System.out.print(" = " + uid + "\n"); @@ -582,16 +578,13 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * NESTED MAP TEST - */ + /** NESTED MAP TEST */ System.out.print("testMapMap(1)"); - Map<Integer,Map<Integer,Integer>> mm = - testClient.testMapMap(1); + Map<Integer, Map<Integer, Integer>> mm = testClient.testMapMap(1); System.out.print(" = {"); for (int key : mm.keySet()) { System.out.print(key + " => {"); - Map<Integer,Integer> m2 = mm.get(key); + Map<Integer, Integer> m2 = mm.get(key); for (int k2 : m2.keySet()) { System.out.print(k2 + " => " + m2.get(k2) + ", "); } @@ -604,17 +597,20 @@ public class TestClient { } else { Map<Integer, Integer> m1 = mm.get(4); Map<Integer, Integer> m2 = mm.get(-4); - if (m1.get(1) != 1 || m1.get(2) != 2 || m1.get(3) != 3 || m1.get(4) != 4 || - m2.get(-1) != -1 || m2.get(-2) != -2 || m2.get(-3) != -3 || m2.get(-4) != -4) { + if (m1.get(1) != 1 + || m1.get(2) != 2 + || m1.get(3) != 3 + || m1.get(4) != 4 + || m2.get(-1) != -1 + || m2.get(-2) != -2 + || m2.get(-3) != -3 + || m2.get(-4) != -4) { returnCode |= ERR_CONTAINERS; System.out.println("*** FAILURE ***\n"); } } - /** - * INSANITY TEST - */ - + /** INSANITY TEST */ boolean insanityFailed = true; try { Xtruct hello = new Xtruct(); @@ -625,23 +621,22 @@ public class TestClient { Xtruct goodbye = new Xtruct(); goodbye.string_thing = "Goodbye4"; - goodbye.byte_thing = (byte)4; + goodbye.byte_thing = (byte) 4; goodbye.i32_thing = 4; - goodbye.i64_thing = (long)4; + goodbye.i64_thing = (long) 4; insane.userMap = new HashMap<Numberz, Long>(); - insane.userMap.put(Numberz.EIGHT, (long)8); - insane.userMap.put(Numberz.FIVE, (long)5); + insane.userMap.put(Numberz.EIGHT, (long) 8); + insane.userMap.put(Numberz.FIVE, (long) 5); insane.xtructs = new ArrayList<Xtruct>(); insane.xtructs.add(goodbye); insane.xtructs.add(hello); System.out.print("testInsanity()"); - Map<Long,Map<Numberz,Insanity>> whoa = - testClient.testInsanity(insane); + Map<Long, Map<Numberz, Insanity>> whoa = testClient.testInsanity(insane); System.out.print(" = {"); for (long key : whoa.keySet()) { - Map<Numberz,Insanity> val = whoa.get(key); + Map<Numberz, Insanity> val = whoa.get(key); System.out.print(key + " => {"); for (Numberz k2 : val.keySet()) { @@ -660,7 +655,17 @@ public class TestClient { System.out.print("{"); if (xtructs != null) { for (Xtruct x : xtructs) { - System.out.print("{" + "\"" + x.string_thing + "\", " + x.byte_thing + ", " + x.i32_thing + ", "+ x.i64_thing + "}, "); + System.out.print( + "{" + + "\"" + + x.string_thing + + "\", " + + x.byte_thing + + ", " + + x.i32_thing + + ", " + + x.i64_thing + + "}, "); } } System.out.print("}"); @@ -673,14 +678,14 @@ public class TestClient { if (whoa.size() == 2 && whoa.containsKey(1L) && whoa.containsKey(2L)) { Map<Numberz, Insanity> first_map = whoa.get(1L); Map<Numberz, Insanity> second_map = whoa.get(2L); - if (first_map.size() == 2 && - first_map.containsKey(Numberz.TWO) && - first_map.containsKey(Numberz.THREE) && - second_map.size() == 1 && - second_map.containsKey(Numberz.SIX) && - insane.equals(first_map.get(Numberz.TWO)) && - insane.equals(first_map.get(Numberz.THREE))) { - Insanity six =second_map.get(Numberz.SIX); + if (first_map.size() == 2 + && first_map.containsKey(Numberz.TWO) + && first_map.containsKey(Numberz.THREE) + && second_map.size() == 1 + && second_map.containsKey(Numberz.SIX) + && insane.equals(first_map.get(Numberz.TWO)) + && insane.equals(first_map.get(Numberz.THREE))) { + Insanity six = second_map.get(Numberz.SIX); // Cannot use "new Insanity().equals(six)" because as of now, struct/container // fields with default requiredness have isset=false for local instances and yet // received empty values from other languages like C++ have isset=true . @@ -701,15 +706,13 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } - /** - * EXECPTION TEST - */ + /** EXECPTION TEST */ try { System.out.print("testClient.testException(\"Xception\") =>"); testClient.testException("Xception"); System.out.print(" void\n*** FAILURE ***\n"); returnCode |= ERR_EXCEPTIONS; - } catch(Xception e) { + } catch (Xception e) { System.out.printf(" {%d, \"%s\"}\n", e.errorCode, e.message); } @@ -718,7 +721,7 @@ public class TestClient { testClient.testException("TException"); System.out.print(" void\n*** FAILURE ***\n"); returnCode |= ERR_EXCEPTIONS; - } catch(TException e) { + } catch (TException e) { System.out.printf(" {\"%s\"}\n", e.getMessage()); } @@ -726,22 +729,18 @@ public class TestClient { System.out.print("testClient.testException(\"success\") =>"); testClient.testException("success"); System.out.print(" void\n"); - }catch(Exception e) { + } catch (Exception e) { System.out.printf(" exception\n*** FAILURE ***\n"); returnCode |= ERR_EXCEPTIONS; } - - /** - * MULTI EXCEPTION TEST - */ - + /** MULTI EXCEPTION TEST */ try { System.out.printf("testClient.testMultiException(\"Xception\", \"test 1\") =>"); testClient.testMultiException("Xception", "test 1"); System.out.print(" result\n*** FAILURE ***\n"); returnCode |= ERR_EXCEPTIONS; - } catch(Xception e) { + } catch (Xception e) { System.out.printf(" {%d, \"%s\"}\n", e.errorCode, e.message); } @@ -750,7 +749,7 @@ public class TestClient { testClient.testMultiException("Xception2", "test 2"); System.out.print(" result\n*** FAILURE ***\n"); returnCode |= ERR_EXCEPTIONS; - } catch(Xception2 e) { + } catch (Xception2 e) { System.out.printf(" {%d, {\"%s\"}}\n", e.errorCode, e.struct_thing.string_thing); } @@ -759,42 +758,37 @@ public class TestClient { Xtruct result; result = testClient.testMultiException("success", "test 3"); System.out.printf(" {{\"%s\"}}\n", result.string_thing); - } catch(Exception e) { + } catch (Exception e) { System.out.printf(" exception\n*** FAILURE ***\n"); returnCode |= ERR_EXCEPTIONS; } - - - /** - * ONEWAY TEST - */ + /** ONEWAY TEST */ System.out.print("testOneway(3)..."); long startOneway = System.nanoTime(); testClient.testOneway(3); long onewayElapsedMillis = (System.nanoTime() - startOneway) / 1000000; if (onewayElapsedMillis > 200) { - System.out.println("Oneway test took too long to execute failed: took " + - onewayElapsedMillis + - "ms"); - System.out.println("oneway calls are 'fire and forget' and therefore should not cause blocking."); - System.out.println("Some transports (HTTP) have a required response, and typically this failure"); + System.out.println( + "Oneway test took too long to execute failed: took " + onewayElapsedMillis + "ms"); + System.out.println( + "oneway calls are 'fire and forget' and therefore should not cause blocking."); + System.out.println( + "Some transports (HTTP) have a required response, and typically this failure"); System.out.println("means the transport response was delayed until after the execution"); - System.out.println("of the RPC. The server should post the transport response immediately and"); + System.out.println( + "of the RPC. The server should post the transport response immediately and"); System.out.println("before executing the RPC."); System.out.println("*** FAILURE ***"); returnCode |= ERR_BASETYPES; } else { - System.out.println("Success - fire and forget only took " + - onewayElapsedMillis + - "ms"); + System.out.println("Success - fire and forget only took " + onewayElapsedMillis + "ms"); } - long stop = System.nanoTime(); - long tot = stop-start; + long tot = stop - start; - System.out.println("Total time: " + tot/1000 + "us"); + System.out.println("Total time: " + tot / 1000 + "us"); if (timeMin == 0 || tot < timeMin) { timeMin = tot; @@ -814,9 +808,9 @@ public class TestClient { long timeAvg = timeTot / numTests; - System.out.println("Min time: " + timeMin/1000 + "us"); - System.out.println("Max time: " + timeMax/1000 + "us"); - System.out.println("Avg time: " + timeAvg/1000 + "us"); + System.out.println("Min time: " + timeMin / 1000 + "us"); + System.out.println("Max time: " + timeMax / 1000 + "us"); + System.out.println("Avg time: " + timeAvg / 1000 + "us"); try { String json = (new TSerializer(new TSimpleJSONProtocol.Factory())).toString(insane); @@ -827,7 +821,6 @@ public class TestClient { returnCode |= ERR_BASETYPES; } - System.exit(returnCode); } } diff --git a/lib/java/src/crossTest/java/org/apache/thrift/test/TestNonblockingServer.java b/lib/java/src/crossTest/java/org/apache/thrift/test/TestNonblockingServer.java index 41c4b6500..c7c3f34ca 100644 --- a/lib/java/src/crossTest/java/org/apache/thrift/test/TestNonblockingServer.java +++ b/lib/java/src/crossTest/java/org/apache/thrift/test/TestNonblockingServer.java @@ -19,18 +19,16 @@ package org.apache.thrift.test; +import org.apache.thrift.server.ServerTestBase.TestHandler; import org.apache.thrift.server.THsHaServer; +import org.apache.thrift.server.THsHaServer.Args; import org.apache.thrift.server.TNonblockingServer; import org.apache.thrift.server.TServer; -import org.apache.thrift.server.THsHaServer.Args; import org.apache.thrift.transport.TNonblockingServerSocket; -import org.apache.thrift.server.ServerTestBase.TestHandler; - import thrift.test.ThriftTest; - public class TestNonblockingServer extends TestServer { - public static void main(String [] args) { + public static void main(String[] args) { try { int port = 9090; boolean hsha = false; @@ -42,17 +40,16 @@ public class TestNonblockingServer extends TestServer { hsha = true; } } - //@TODO add other protocol and transport types + // @TODO add other protocol and transport types // Processor - TestHandler testHandler = - new TestHandler(); - ThriftTest.Processor testProcessor = - new ThriftTest.Processor(testHandler); + TestHandler testHandler = new TestHandler(); + ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); // Transport TNonblockingServerSocket tServerSocket = - new TNonblockingServerSocket(new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(port)); + new TNonblockingServerSocket( + new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(port)); TServer serverEngine; diff --git a/lib/java/src/crossTest/java/org/apache/thrift/test/TestServer.java b/lib/java/src/crossTest/java/org/apache/thrift/test/TestServer.java index 386f2b60b..804a7f2f1 100644 --- a/lib/java/src/crossTest/java/org/apache/thrift/test/TestServer.java +++ b/lib/java/src/crossTest/java/org/apache/thrift/test/TestServer.java @@ -19,29 +19,28 @@ package org.apache.thrift.test; +import org.apache.thrift.TMultiplexedProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TJSONProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.server.ServerContext; +import org.apache.thrift.server.ServerTestBase.TestHandler; +import org.apache.thrift.server.TNonblockingServer; import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TServerEventHandler; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.server.TThreadPoolServer; -import org.apache.thrift.server.ServerTestBase.TestHandler; -import org.apache.thrift.server.TServerEventHandler; import org.apache.thrift.server.TThreadedSelectorServer; -import org.apache.thrift.server.TNonblockingServer; -import org.apache.thrift.transport.layered.TFramedTransport; -import org.apache.thrift.transport.layered.TFastFramedTransport; -import org.apache.thrift.transport.TZlibTransport; -import org.apache.thrift.transport.TServerSocket; +import org.apache.thrift.transport.TNonblockingServerSocket; import org.apache.thrift.transport.TSSLTransportFactory; +import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportFactory; -import org.apache.thrift.transport.TNonblockingServerSocket; -import org.apache.thrift.TMultiplexedProcessor; - +import org.apache.thrift.transport.TZlibTransport; +import org.apache.thrift.transport.layered.TFastFramedTransport; +import org.apache.thrift.transport.layered.TFramedTransport; import thrift.test.SecondService; import thrift.test.ThriftTest; @@ -60,26 +59,27 @@ public class TestServer { static class SecondHandler implements thrift.test.SecondService.Iface { @Override - public java.lang.String secondtestString(java.lang.String thing) throws org.apache.thrift.TException - { return "testString(\"" + thing + "\")"; } - + public java.lang.String secondtestString(java.lang.String thing) + throws org.apache.thrift.TException { + return "testString(\"" + thing + "\")"; + } } static class TestServerContext implements ServerContext { - int connectionId; + int connectionId; - public TestServerContext(int connectionId) { - this.connectionId = connectionId; - } + public TestServerContext(int connectionId) { + this.connectionId = connectionId; + } - public int getConnectionId() { - return connectionId; - } + public int getConnectionId() { + return connectionId; + } - public void setConnectionId(int connectionId) { - this.connectionId = connectionId; - } + public void setConnectionId(int connectionId) { + this.connectionId = connectionId; + } @Override public <T> T unwrap(Class<T> iface) { @@ -90,7 +90,8 @@ public class TestServer { throw new RuntimeException("The context is not a wrapper for " + iface.getName()); } } catch (Exception e) { - throw new RuntimeException("The context is not a wrapper and does not implement the interface"); + throw new RuntimeException( + "The context is not a wrapper and does not implement the interface"); } } @@ -98,37 +99,46 @@ public class TestServer { public boolean isWrapperFor(Class<?> iface) { return iface.isInstance(this); } - } static class TestServerEventHandler implements TServerEventHandler { - private int nextConnectionId = 1; + private int nextConnectionId = 1; - public void preServe() { - System.out.println("TServerEventHandler.preServe - called only once before server starts accepting connections"); - } - - public ServerContext createContext(TProtocol input, TProtocol output) { - //we can create some connection level data which is stored while connection is alive & served - TestServerContext ctx = new TestServerContext(nextConnectionId++); - System.out.println("TServerEventHandler.createContext - connection #"+ctx.getConnectionId()+" established"); - return ctx; - } + public void preServe() { + System.out.println( + "TServerEventHandler.preServe - called only once before server starts accepting connections"); + } - public void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) { - TestServerContext ctx = serverContext.unwrap(TestServerContext.class); - System.out.println("TServerEventHandler.deleteContext - connection #"+ctx.getConnectionId()+" terminated"); - } + public ServerContext createContext(TProtocol input, TProtocol output) { + // we can create some connection level data which is stored while connection is alive & served + TestServerContext ctx = new TestServerContext(nextConnectionId++); + System.out.println( + "TServerEventHandler.createContext - connection #" + + ctx.getConnectionId() + + " established"); + return ctx; + } - public void processContext(ServerContext serverContext, TTransport inputTransport, TTransport outputTransport) { - TestServerContext ctx = serverContext.unwrap(TestServerContext.class); - System.out.println("TServerEventHandler.processContext - connection #"+ctx.getConnectionId()+" is ready to process next request"); - } + public void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) { + TestServerContext ctx = serverContext.unwrap(TestServerContext.class); + System.out.println( + "TServerEventHandler.deleteContext - connection #" + + ctx.getConnectionId() + + " terminated"); + } + public void processContext( + ServerContext serverContext, TTransport inputTransport, TTransport outputTransport) { + TestServerContext ctx = serverContext.unwrap(TestServerContext.class); + System.out.println( + "TServerEventHandler.processContext - connection #" + + ctx.getConnectionId() + + " is ready to process next request"); + } } - public static void main(String [] args) { + public static void main(String[] args) { try { int port = 9090; boolean ssl = false; @@ -147,7 +157,7 @@ public class TestServer { server_type = args[i].split("=")[1]; server_type.trim(); } else if (args[i].startsWith("--port")) { - port=Integer.parseInt(args[i].split("=")[1]); + port = Integer.parseInt(args[i].split("=")[1]); } else if (args[i].startsWith("--protocol")) { protocol_type = args[i].split("=")[1]; protocol_type.trim(); @@ -166,13 +176,24 @@ public class TestServer { System.out.println("Allowed options:"); System.out.println(" --help\t\t\tProduce help message"); System.out.println(" --port=arg (=" + port + ")\tPort number to connect"); - System.out.println(" --transport=arg (=" + transport_type + ")\n\t\t\t\tTransport: buffered, framed, fastframed, zlib"); - System.out.println(" --protocol=arg (=" + protocol_type + ")\tProtocol: binary, compact, json, multi, multic, multij"); + System.out.println( + " --transport=arg (=" + + transport_type + + ")\n\t\t\t\tTransport: buffered, framed, fastframed, zlib"); + System.out.println( + " --protocol=arg (=" + + protocol_type + + ")\tProtocol: binary, compact, json, multi, multic, multij"); System.out.println(" --ssl\t\t\tEncrypted Transport using SSL"); System.out.println(" --zlib\t\t\tCompressed Transport using Zlib"); - System.out.println(" --server-type=arg (=" + server_type +")\n\t\t\t\tType of server: simple, thread-pool, nonblocking, threaded-selector"); - System.out.println(" --string-limit=arg (=" + string_limit + ")\tString read length limit"); - System.out.println(" --container-limit=arg (=" + container_limit + ")\tContainer read length limit"); + System.out.println( + " --server-type=arg (=" + + server_type + + ")\n\t\t\t\tType of server: simple, thread-pool, nonblocking, threaded-selector"); + System.out.println( + " --string-limit=arg (=" + string_limit + ")\tString read length limit"); + System.out.println( + " --container-limit=arg (=" + container_limit + ")\tContainer read length limit"); System.exit(0); } } @@ -249,29 +270,31 @@ public class TestServer { // If we are multiplexing services in one server... TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor(); - multiplexedProcessor.registerDefault (testProcessor); + multiplexedProcessor.registerDefault(testProcessor); multiplexedProcessor.registerProcessor("ThriftTest", testProcessor); multiplexedProcessor.registerProcessor("SecondService", secondProcessor); - if (server_type.equals("nonblocking") || - server_type.equals("threaded-selector")) { + if (server_type.equals("nonblocking") || server_type.equals("threaded-selector")) { // Nonblocking servers TNonblockingServerSocket tNonblockingServerSocket = - new TNonblockingServerSocket(new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(port)); + new TNonblockingServerSocket( + new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(port)); if (server_type.contains("nonblocking")) { // Nonblocking Server - TNonblockingServer.Args tNonblockingServerArgs - = new TNonblockingServer.Args(tNonblockingServerSocket); - tNonblockingServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); + TNonblockingServer.Args tNonblockingServerArgs = + new TNonblockingServer.Args(tNonblockingServerSocket); + tNonblockingServerArgs.processor( + protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tNonblockingServerArgs.protocolFactory(tProtocolFactory); tNonblockingServerArgs.transportFactory(tTransportFactory); serverEngine = new TNonblockingServer(tNonblockingServerArgs); } else { // server_type.equals("threaded-selector") // ThreadedSelector Server - TThreadedSelectorServer.Args tThreadedSelectorServerArgs - = new TThreadedSelectorServer.Args(tNonblockingServerSocket); - tThreadedSelectorServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); + TThreadedSelectorServer.Args tThreadedSelectorServerArgs = + new TThreadedSelectorServer.Args(tNonblockingServerSocket); + tThreadedSelectorServerArgs.processor( + protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tThreadedSelectorServerArgs.protocolFactory(tProtocolFactory); tThreadedSelectorServerArgs.transportFactory(tTransportFactory); serverEngine = new TThreadedSelectorServer(tThreadedSelectorServerArgs); @@ -284,21 +307,23 @@ public class TestServer { if (ssl) { tServerSocket = TSSLTransportFactory.getServerSocket(port, 0); } else { - tServerSocket = new TServerSocket(new TServerSocket.ServerSocketTransportArgs().port(port)); + tServerSocket = + new TServerSocket(new TServerSocket.ServerSocketTransportArgs().port(port)); } if (server_type.equals("simple")) { // Simple Server TServer.Args tServerArgs = new TServer.Args(tServerSocket); - tServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); + tServerArgs.processor( + protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tServerArgs.protocolFactory(tProtocolFactory); tServerArgs.transportFactory(tTransportFactory); serverEngine = new TSimpleServer(tServerArgs); } else { // server_type.equals("threadpool") // ThreadPool Server - TThreadPoolServer.Args tThreadPoolServerArgs - = new TThreadPoolServer.Args(tServerSocket); - tThreadPoolServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); + TThreadPoolServer.Args tThreadPoolServerArgs = new TThreadPoolServer.Args(tServerSocket); + tThreadPoolServerArgs.processor( + protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tThreadPoolServerArgs.protocolFactory(tProtocolFactory); tThreadPoolServerArgs.transportFactory(tTransportFactory); serverEngine = new TThreadPoolServer(tThreadPoolServerArgs); @@ -309,9 +334,17 @@ public class TestServer { serverEngine.setServerEventHandler(new TestServerEventHandler()); // Run it - System.out.println("Starting the " + (ssl ? "ssl server" : "server") + - " [" + protocol_type + "/" + transport_type + "/" + server_type + "] on " + - ((domain_socket == "") ? ("port " + port) : ("unix socket " + domain_socket))); + System.out.println( + "Starting the " + + (ssl ? "ssl server" : "server") + + " [" + + protocol_type + + "/" + + transport_type + + "/" + + server_type + + "] on " + + ((domain_socket == "") ? ("port " + port) : ("unix socket " + domain_socket))); serverEngine.serve(); } catch (Exception x) { diff --git a/lib/java/src/crossTest/java/org/apache/thrift/test/TestTServletServer.java b/lib/java/src/crossTest/java/org/apache/thrift/test/TestTServletServer.java index 93e7944f8..574cae64a 100644 --- a/lib/java/src/crossTest/java/org/apache/thrift/test/TestTServletServer.java +++ b/lib/java/src/crossTest/java/org/apache/thrift/test/TestTServletServer.java @@ -23,30 +23,26 @@ import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.Tomcat.FixContextListener; - -/** - * run tomcat for test TServlet - */ +/** run tomcat for test TServlet */ public class TestTServletServer { static final int port = 9090; - public static void main(String [] args) throws Exception{ + public static void main(String[] args) throws Exception { Tomcat tomcat = new Tomcat(); - tomcat.setPort( port ); - tomcat.setBaseDir(System.getProperty("user.dir")+"\\build"); - tomcat.getHost().setAutoDeploy( false ); + tomcat.setPort(port); + tomcat.setBaseDir(System.getProperty("user.dir") + "\\build"); + tomcat.getHost().setAutoDeploy(false); String contextPath = "/test"; StandardContext context = new StandardContext(); - context.setPath( contextPath ); - context.addLifecycleListener( new FixContextListener() ); - tomcat.getHost().addChild( context ); + context.setPath(contextPath); + context.addLifecycleListener(new FixContextListener()); + tomcat.getHost().addChild(context); - tomcat.addServlet( contextPath, "testServlet", new TestServlet() ); - context.addServletMappingDecoded( "/service", "testServlet"); + tomcat.addServlet(contextPath, "testServlet", new TestServlet()); + context.addServletMappingDecoded("/service", "testServlet"); tomcat.start(); tomcat.getServer().await(); } - } diff --git a/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java b/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java index 483c8d054..c7c4be303 100644 --- a/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java +++ b/lib/java/src/main/java/org/apache/thrift/AsyncProcessFunction.java @@ -24,32 +24,39 @@ import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.server.AbstractNonblockingServer; public abstract class AsyncProcessFunction<I, T extends TBase, R> { - final String methodName; + final String methodName; - public AsyncProcessFunction(String methodName) { - this.methodName = methodName; - } + public AsyncProcessFunction(String methodName) { + this.methodName = methodName; + } - protected abstract boolean isOneway(); + protected abstract boolean isOneway(); - public abstract void start(I iface, T args, AsyncMethodCallback<R> resultHandler) throws TException; + public abstract void start(I iface, T args, AsyncMethodCallback<R> resultHandler) + throws TException; - public abstract T getEmptyArgsInstance(); + public abstract T getEmptyArgsInstance(); - public abstract AsyncMethodCallback<R> getResultHandler(final AbstractNonblockingServer.AsyncFrameBuffer fb, int seqid); + public abstract AsyncMethodCallback<R> getResultHandler( + final AbstractNonblockingServer.AsyncFrameBuffer fb, int seqid); - public String getMethodName() { - return methodName; - } + public String getMethodName() { + return methodName; + } - public void sendResponse(final AbstractNonblockingServer.AsyncFrameBuffer fb, final TSerializable result, final byte type, final int seqid) throws TException { - TProtocol oprot = fb.getOutputProtocol(); + public void sendResponse( + final AbstractNonblockingServer.AsyncFrameBuffer fb, + final TSerializable result, + final byte type, + final int seqid) + throws TException { + TProtocol oprot = fb.getOutputProtocol(); - oprot.writeMessageBegin(new TMessage(getMethodName(), type, seqid)); - result.write(oprot); - oprot.writeMessageEnd(); - oprot.getTransport().flush(); + oprot.writeMessageBegin(new TMessage(getMethodName(), type, seqid)); + result.write(oprot); + oprot.writeMessageEnd(); + oprot.getTransport().flush(); - fb.responseReady(); - } + fb.responseReady(); + } } diff --git a/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java b/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java index d8cb1082b..d4bc7acc7 100644 --- a/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java +++ b/lib/java/src/main/java/org/apache/thrift/EncodingUtils.java @@ -19,34 +19,27 @@ package org.apache.thrift; -/** - * Utility methods for use when encoding/decoding raw data as byte arrays. - */ +/** Utility methods for use when encoding/decoding raw data as byte arrays. */ public class EncodingUtils { /** - * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> - * starting at position 0 within that buffer. + * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> starting at position 0 + * within that buffer. * - * @param integer - * The integer to encode. - * @param buf - * The buffer to write to. + * @param integer The integer to encode. + * @param buf The buffer to write to. */ public static final void encodeBigEndian(final int integer, final byte[] buf) { encodeBigEndian(integer, buf, 0); } /** - * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> - * starting at position <code>offset</code>. + * Encode <code>integer</code> as a series of 4 bytes into <code>buf</code> starting at position + * <code>offset</code>. * - * @param integer - * The integer to encode. - * @param buf - * The buffer to write to. - * @param offset - * The offset within <code>buf</code> to start the encoding. + * @param integer The integer to encode. + * @param buf The buffer to write to. + * @param offset The offset within <code>buf</code> to start the encoding. */ public static final void encodeBigEndian(final int integer, final byte[] buf, int offset) { buf[offset] = (byte) (0xff & (integer >> 24)); @@ -56,11 +49,10 @@ public class EncodingUtils { } /** - * Decode a series of 4 bytes from <code>buf</code>, starting at position 0, - * and interpret them as an integer. + * Decode a series of 4 bytes from <code>buf</code>, starting at position 0, and interpret them as + * an integer. * - * @param buf - * The buffer to read from. + * @param buf The buffer to read from. * @return An integer, as read from the buffer. */ public static final int decodeBigEndian(final byte[] buf) { @@ -68,36 +60,33 @@ public class EncodingUtils { } /** - * Decode a series of 4 bytes from <code>buf</code>, start at - * <code>offset</code>, and interpret them as an integer. + * Decode a series of 4 bytes from <code>buf</code>, start at <code>offset</code>, and interpret + * them as an integer. * - * @param buf - * The buffer to read from. - * @param offset - * The offset with <code>buf</code> to start the decoding. + * @param buf The buffer to read from. + * @param offset The offset with <code>buf</code> to start the decoding. * @return An integer, as read from the buffer. */ public static final int decodeBigEndian(final byte[] buf, int offset) { - return ((buf[offset] & 0xff) << 24) | ((buf[offset + 1] & 0xff) << 16) - | ((buf[offset + 2] & 0xff) << 8) | ((buf[offset + 3] & 0xff)); + return ((buf[offset] & 0xff) << 24) + | ((buf[offset + 1] & 0xff) << 16) + | ((buf[offset + 2] & 0xff) << 8) + | ((buf[offset + 3] & 0xff)); } /** - * Bitfield utilities. - * Returns true if the bit at position is set in v. + * Bitfield utilities. Returns true if the bit at position is set in v. * - * @param v - * the value whose bit is to be checked. - * @param position - * the 0 based bit number indicating the bit to check. + * @param v the value whose bit is to be checked. + * @param position the 0 based bit number indicating the bit to check. * @return true if the bit at position is set in v. */ public static final boolean testBit(byte v, int position) { - return testBit((int)v, position); + return testBit((int) v, position); } public static final boolean testBit(short v, int position) { - return testBit((int)v, position); + return testBit((int) v, position); } public static final boolean testBit(int v, int position) { @@ -111,18 +100,16 @@ public class EncodingUtils { /** * Returns v, with the bit at position set to zero. * - * @param v - * the value whose bit is to be cleared. - * @param position - * the 0 based bit number indicating the bit to clear. + * @param v the value whose bit is to be cleared. + * @param position the 0 based bit number indicating the bit to clear. * @return v, with the bit at position set to zero. */ public static final byte clearBit(byte v, int position) { - return (byte)clearBit((int)v, position); + return (byte) clearBit((int) v, position); } public static final short clearBit(short v, int position) { - return (short)clearBit((int)v, position); + return (short) clearBit((int) v, position); } public static final int clearBit(int v, int position) { @@ -136,33 +123,26 @@ public class EncodingUtils { /** * Returns v, with the bit at position set to 1 or 0 depending on value. * - * @param v - * the value whose bit is to be set. - * @param position - * the 0 based bit number indicating the bit to set. - * @param value - * if true, the given bit is set to 1; otherwise it is set to 0. + * @param v the value whose bit is to be set. + * @param position the 0 based bit number indicating the bit to set. + * @param value if true, the given bit is set to 1; otherwise it is set to 0. * @return v, with the bit at position set to 0 (if value is false) or 1 (if value is true). */ public static final byte setBit(byte v, int position, boolean value) { - return (byte)setBit((int)v, position, value); + return (byte) setBit((int) v, position, value); } public static final short setBit(short v, int position, boolean value) { - return (short)setBit((int)v, position, value); + return (short) setBit((int) v, position, value); } public static final int setBit(int v, int position, boolean value) { - if(value) - return v | (1 << position); - else - return clearBit(v, position); + if (value) return v | (1 << position); + else return clearBit(v, position); } public static final long setBit(long v, int position, boolean value) { - if(value) - return v | (1L << position); - else - return clearBit(v, position); + if (value) return v | (1L << position); + else return clearBit(v, position); } } diff --git a/lib/java/src/main/java/org/apache/thrift/Option.java b/lib/java/src/main/java/org/apache/thrift/Option.java index 6b036df96..601bcc16a 100644 --- a/lib/java/src/main/java/org/apache/thrift/Option.java +++ b/lib/java/src/main/java/org/apache/thrift/Option.java @@ -21,120 +21,123 @@ package org.apache.thrift; import java.util.Optional; -/** - * Implementation of the Option type pattern - */ +/** Implementation of the Option type pattern */ public abstract class Option<T> { - @SuppressWarnings("rawtypes") - private static final Option NONE = new None(); - - /** - * Whether the Option is defined or not - * @return - * true if the Option is defined (of type Some) - * false if the Option is not defined (of type None) - */ - public abstract boolean isDefined(); - - /** - * Get the value of the Option (if it is defined) - * @return the value - * @throws IllegalStateException if called on a None - */ - public abstract T get(); - - /** - * Get the contained value (if defined) or else return a default value - * @param other what to return if the value is not defined (a None) - * @return either the value, or other if the value is not defined - */ - public T or(T other) { - if (isDefined()) { - return get(); - } else { - return other; - } + @SuppressWarnings("rawtypes") + private static final Option NONE = new None(); + + /** + * Whether the Option is defined or not + * + * @return true if the Option is defined (of type Some) false if the Option is not defined (of + * type None) + */ + public abstract boolean isDefined(); + + /** + * Get the value of the Option (if it is defined) + * + * @return the value + * @throws IllegalStateException if called on a None + */ + public abstract T get(); + + /** + * Get the contained value (if defined) or else return a default value + * + * @param other what to return if the value is not defined (a None) + * @return either the value, or other if the value is not defined + */ + public T or(T other) { + if (isDefined()) { + return get(); + } else { + return other; + } + } + + /** + * Turn this Option into Java 8 Optional type + * + * @return Java 8+ Optional Type + */ + public Optional<T> toOptional() { + if (isDefined()) { + return Optional.of(get()); + } else { + return Optional.empty(); } + } - /** - * Turn this Option into Java 8 Optional type - * @return Java 8+ Optional Type - */ - public Optional<T> toOptional() { - if (isDefined()) { - return Optional.of(get()); - } else { - return Optional.empty(); - } + /** The None type, representing an absent value (instead of "null") */ + public static class None<T> extends Option<T> { + public boolean isDefined() { + return false; } - /** - * The None type, representing an absent value (instead of "null") - */ - public static class None<T> extends Option<T> { - public boolean isDefined() { - return false; - } - - public T get() { - throw new IllegalStateException("Cannot call get() on None"); - } - - public String toString() { - return "None"; - } + public T get() { + throw new IllegalStateException("Cannot call get() on None"); } - /** - * The Some type, representing an existence of some value - * @param <T> The type of value - */ - public static class Some<T> extends Option<T> { - private final T value; - public Some(T value) { - this.value = value; - } - - public boolean isDefined() { - return true; - } - - public T get() { - return value; - } - - public String toString() { - return "Some(" + value + ")"; - } + public String toString() { + return "None"; + } + } + + /** + * The Some type, representing an existence of some value + * + * @param <T> The type of value + */ + public static class Some<T> extends Option<T> { + private final T value; + + public Some(T value) { + this.value = value; } - /** - * Wraps value in an Option type, depending on whether or not value is null - * @param value the value to wrap in Option - * @param <T> the type of value - * @return Some(value) if value is not null, None if value is null - */ - public static <T> Option<T> fromNullable(T value) { - if (value != null) { - return some(value); - } else { - return none(); - } + public boolean isDefined() { + return true; } - /** - * Wrap value in a Some type (NB! value must not be null!) - * @param value the value to wrap. - * @param <T> the type of value - * @return a new Some(value) - */ - public static <T> Some<T> some(T value) { - return new Some<T>(value); + public T get() { + return value; } - @SuppressWarnings("unchecked") - public static <T> None<T> none() { - return (None<T>) NONE; + public String toString() { + return "Some(" + value + ")"; + } + } + + /** + * Wraps value in an Option type, depending on whether or not value is null + * + * @param value the value to wrap in Option + * @param <T> the type of value + * @return Some(value) if value is not null, None if value is null + */ + public static <T> Option<T> fromNullable(T value) { + if (value != null) { + return some(value); + } else { + return none(); } + } + + /** + * Wrap value in a Some type (NB! value must not be null!) + * + * @param value the value to wrap. + * @param <T> the type of value + * @return a new Some(value) + */ + public static <T> Some<T> some(T value) { + return new Some<T>(value); + } + + @SuppressWarnings("unchecked") + public static <T> None<T> none() { + return (None<T>) NONE; + } } diff --git a/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java b/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java index e6213dfa1..7399342a2 100644 --- a/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java +++ b/lib/java/src/main/java/org/apache/thrift/ProcessFunction.java @@ -17,13 +17,15 @@ public abstract class ProcessFunction<I, T extends TBase> { this.methodName = methodName; } - public final void process(int seqid, TProtocol iprot, TProtocol oprot, I iface) throws TException { + public final void process(int seqid, TProtocol iprot, TProtocol oprot, I iface) + throws TException { T args = getEmptyArgsInstance(); try { args.read(iprot); } catch (TProtocolException e) { iprot.readMessageEnd(); - TApplicationException x = new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage()); + TApplicationException x = + new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage()); oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid)); x.write(oprot); oprot.writeMessageEnd(); @@ -45,15 +47,17 @@ public abstract class ProcessFunction<I, T extends TBase> { msgType = TMessageType.EXCEPTION; } catch (Exception ex) { LOGGER.error("Internal error processing " + getMethodName(), ex); - if(rethrowUnhandledExceptions()) throw new RuntimeException(ex.getMessage(), ex); - if(!isOneway()) { - result = new TApplicationException(TApplicationException.INTERNAL_ERROR, - "Internal error processing " + getMethodName()); + if (rethrowUnhandledExceptions()) throw new RuntimeException(ex.getMessage(), ex); + if (!isOneway()) { + result = + new TApplicationException( + TApplicationException.INTERNAL_ERROR, + "Internal error processing " + getMethodName()); msgType = TMessageType.EXCEPTION; } } - if(!isOneway()) { + if (!isOneway()) { oprot.writeMessageBegin(new TMessage(getMethodName(), msgType, seqid)); result.write(oprot); oprot.writeMessageEnd(); @@ -63,8 +67,9 @@ public abstract class ProcessFunction<I, T extends TBase> { private void handleException(int seqid, TProtocol oprot) throws TException { if (!isOneway()) { - TApplicationException x = new TApplicationException(TApplicationException.INTERNAL_ERROR, - "Internal error processing " + getMethodName()); + TApplicationException x = + new TApplicationException( + TApplicationException.INTERNAL_ERROR, "Internal error processing " + getMethodName()); oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid)); x.write(oprot); oprot.writeMessageEnd(); @@ -72,7 +77,7 @@ public abstract class ProcessFunction<I, T extends TBase> { } } - protected boolean rethrowUnhandledExceptions(){ + protected boolean rethrowUnhandledExceptions() { return false; } diff --git a/lib/java/src/main/java/org/apache/thrift/TApplicationException.java b/lib/java/src/main/java/org/apache/thrift/TApplicationException.java index 59cff6930..daf107223 100644 --- a/lib/java/src/main/java/org/apache/thrift/TApplicationException.java +++ b/lib/java/src/main/java/org/apache/thrift/TApplicationException.java @@ -25,15 +25,12 @@ import org.apache.thrift.protocol.TProtocolUtil; import org.apache.thrift.protocol.TStruct; import org.apache.thrift.protocol.TType; -/** - * Application level exception - * - */ +/** Application level exception */ public class TApplicationException extends TException implements TSerializable { private static final TStruct TAPPLICATION_EXCEPTION_STRUCT = new TStruct("TApplicationException"); - private static final TField MESSAGE_FIELD = new TField("message", TType.STRING, (short)1); - private static final TField TYPE_FIELD = new TField("type", TType.I32, (short)2); + private static final TField MESSAGE_FIELD = new TField("message", TType.STRING, (short) 1); + private static final TField TYPE_FIELD = new TField("type", TType.I32, (short) 2); private static final long serialVersionUID = 1L; @@ -78,14 +75,12 @@ public class TApplicationException extends TException implements TSerializable { public String getMessage() { if (message_ == null) { return super.getMessage(); - } - else { + } else { return message_; } } - public void read(TProtocol iprot) throws TException - { + public void read(TProtocol iprot) throws TException { TField field; iprot.readStructBegin(); @@ -130,15 +125,13 @@ public class TApplicationException extends TException implements TSerializable { * @return an instance of TApplicationException read from iprot. * @throws TException if there is an error reading from iprot. */ - public static TApplicationException readFrom(TProtocol iprot) throws TException - { + public static TApplicationException readFrom(TProtocol iprot) throws TException { TApplicationException result = new TApplicationException(); result.read(iprot); return result; } - public void write(TProtocol oprot) throws TException - { + public void write(TProtocol oprot) throws TException { oprot.writeStructBegin(TAPPLICATION_EXCEPTION_STRUCT); if (getMessage() != null) { oprot.writeFieldBegin(MESSAGE_FIELD); diff --git a/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java b/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java index d435b08c5..4dc9160bf 100644 --- a/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TAsyncProcessor.java @@ -23,9 +23,8 @@ import org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer; public interface TAsyncProcessor { /** * Process a single frame. - - * <b>Note:</b> Implementations must call fb.responseReady() once processing - * is complete + * + * <p><b>Note:</b> Implementations must call fb.responseReady() once processing is complete * * @param fb the frame buffer to process. * @throws TException if the frame cannot be processed diff --git a/lib/java/src/main/java/org/apache/thrift/TBase.java b/lib/java/src/main/java/org/apache/thrift/TBase.java index be8ef9ba9..9c8bdbab1 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBase.java +++ b/lib/java/src/main/java/org/apache/thrift/TBase.java @@ -21,13 +21,9 @@ package org.apache.thrift; import java.io.Serializable; -import org.apache.thrift.protocol.TProtocol; - -/** - * Generic base interface for generated Thrift objects. - * - */ -public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Comparable<T>, TSerializable, Serializable { +/** Generic base interface for generated Thrift objects. */ +public interface TBase<T extends TBase<T, F>, F extends TFieldIdEnum> + extends Comparable<T>, TSerializable, Serializable { /** * Get the F instance that corresponds to fieldId. @@ -46,8 +42,8 @@ public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Com public boolean isSet(F field); /** - * Get a field's value by field variable. Primitive types will be wrapped in - * the appropriate "boxed" types. + * Get a field's value by field variable. Primitive types will be wrapped in the appropriate + * "boxed" types. * * @param field the field whose value is requested. * @return the value of the requested field. @@ -55,8 +51,8 @@ public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Com public Object getFieldValue(F field); /** - * Set a field's value by field variable. Primitive types must be "boxed" in - * the appropriate object wrapper type. + * Set a field's value by field variable. Primitive types must be "boxed" in the appropriate + * object wrapper type. * * @param field the field whose value is to be set. * @param value the value to be assigned to field. @@ -71,8 +67,8 @@ public interface TBase<T extends TBase<T,F>, F extends TFieldIdEnum> extends Com public T deepCopy(); /** - * Return to the state of having just been initialized, as though you had just - * called the default constructor. + * Return to the state of having just been initialized, as though you had just called the default + * constructor. */ public void clear(); } diff --git a/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java b/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java index f13f068ef..266f0c0ce 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TBaseAsyncProcessor.java @@ -18,97 +18,96 @@ */ package org.apache.thrift; -import org.apache.thrift.protocol.*; +import java.util.Collections; +import java.util.Map; import org.apache.thrift.async.AsyncMethodCallback; - +import org.apache.thrift.protocol.*; import org.apache.thrift.server.AbstractNonblockingServer.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Collections; -import java.util.Map; - public class TBaseAsyncProcessor<I> implements TAsyncProcessor, TProcessor { - protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); - - final I iface; - final Map<String,AsyncProcessFunction<I, ? extends TBase,?>> processMap; - - public TBaseAsyncProcessor(I iface, Map<String, AsyncProcessFunction<I, ? extends TBase,?>> processMap) { - this.iface = iface; - this.processMap = processMap; + protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); + + final I iface; + final Map<String, AsyncProcessFunction<I, ? extends TBase, ?>> processMap; + + public TBaseAsyncProcessor( + I iface, Map<String, AsyncProcessFunction<I, ? extends TBase, ?>> processMap) { + this.iface = iface; + this.processMap = processMap; + } + + public Map<String, AsyncProcessFunction<I, ? extends TBase, ?>> getProcessMapView() { + return Collections.unmodifiableMap(processMap); + } + + public void process(final AsyncFrameBuffer fb) throws TException { + + final TProtocol in = fb.getInputProtocol(); + final TProtocol out = fb.getOutputProtocol(); + + // Find processing function + final TMessage msg = in.readMessageBegin(); + AsyncProcessFunction fn = processMap.get(msg.name); + if (fn == null) { + TProtocolUtil.skip(in, TType.STRUCT); + in.readMessageEnd(); + + TApplicationException x = + new TApplicationException( + TApplicationException.UNKNOWN_METHOD, "Invalid method name: '" + msg.name + "'"); + LOGGER.debug("Invalid method name", x); + + // this means it is a two-way request, so we can send a reply + if (msg.type == TMessageType.CALL) { + out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); + x.write(out); + out.writeMessageEnd(); + out.getTransport().flush(); + } + fb.responseReady(); + return; } - public Map<String,AsyncProcessFunction<I, ? extends TBase,?>> getProcessMapView() { - return Collections.unmodifiableMap(processMap); + // Get Args + TBase args = fn.getEmptyArgsInstance(); + + try { + args.read(in); + } catch (TProtocolException e) { + in.readMessageEnd(); + + TApplicationException x = + new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage()); + LOGGER.debug("Could not retrieve function arguments", x); + + if (!fn.isOneway()) { + out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); + x.write(out); + out.writeMessageEnd(); + out.getTransport().flush(); + } + fb.responseReady(); + return; } + in.readMessageEnd(); - public void process(final AsyncFrameBuffer fb) throws TException { - - final TProtocol in = fb.getInputProtocol(); - final TProtocol out = fb.getOutputProtocol(); - - //Find processing function - final TMessage msg = in.readMessageBegin(); - AsyncProcessFunction fn = processMap.get(msg.name); - if (fn == null) { - TProtocolUtil.skip(in, TType.STRUCT); - in.readMessageEnd(); - - TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, - "Invalid method name: '" + msg.name + "'"); - LOGGER.debug("Invalid method name", x); - - // this means it is a two-way request, so we can send a reply - if (msg.type == TMessageType.CALL) { - out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); - x.write(out); - out.writeMessageEnd(); - out.getTransport().flush(); - } - fb.responseReady(); - return; - } - - //Get Args - TBase args = fn.getEmptyArgsInstance(); - - try { - args.read(in); - } catch (TProtocolException e) { - in.readMessageEnd(); - - TApplicationException x = new TApplicationException(TApplicationException.PROTOCOL_ERROR, - e.getMessage()); - LOGGER.debug("Could not retrieve function arguments", x); - - if (!fn.isOneway()) { - out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); - x.write(out); - out.writeMessageEnd(); - out.getTransport().flush(); - } - fb.responseReady(); - return; - } - in.readMessageEnd(); - - if (fn.isOneway()) { - fb.responseReady(); - } - - //start off processing function - AsyncMethodCallback resultHandler = fn.getResultHandler(fb, msg.seqid); - try { - fn.start(iface, args, resultHandler); - } catch (Exception e) { - LOGGER.debug("Exception handling function", e); - resultHandler.onError(e); - } - return; + if (fn.isOneway()) { + fb.responseReady(); } - @Override - public void process(TProtocol in, TProtocol out) throws TException { + // start off processing function + AsyncMethodCallback resultHandler = fn.getResultHandler(fb, msg.seqid); + try { + fn.start(iface, args, resultHandler); + } catch (Exception e) { + LOGGER.debug("Exception handling function", e); + resultHandler.onError(e); } + return; + } + + @Override + public void process(TProtocol in, TProtocol out) throws TException {} } diff --git a/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java b/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java index 6f6c6ebf5..be7a9f3c9 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java +++ b/lib/java/src/main/java/org/apache/thrift/TBaseHelper.java @@ -1,24 +1,29 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; import java.io.Serializable; import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; @@ -26,28 +31,24 @@ import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; public final class TBaseHelper { - private TBaseHelper(){} + private TBaseHelper() {} private static final Comparator comparator = new NestedStructureComparator(); public static int compareTo(Object o1, Object o2) { if (o1 instanceof Comparable) { - return compareTo((Comparable)o1, (Comparable)o2); + return compareTo((Comparable) o1, (Comparable) o2); } else if (o1 instanceof List) { - return compareTo((List)o1, (List)o2); + return compareTo((List) o1, (List) o2); } else if (o1 instanceof Set) { - return compareTo((Set)o1, (Set)o2); + return compareTo((Set) o1, (Set) o2); } else if (o1 instanceof Map) { - return compareTo((Map)o1, (Map)o2); + return compareTo((Map) o1, (Map) o2); } else if (o1 instanceof byte[]) { - return compareTo((byte[])o1, (byte[])o2); + return compareTo((byte[]) o1, (byte[]) o2); } else { throw new IllegalArgumentException("Cannot compare objects of type " + o1.getClass()); } @@ -62,7 +63,7 @@ public final class TBaseHelper { } public static int compareTo(short a, short b) { - return Short.compare(a,b); + return Short.compare(a, b); } public static int compareTo(int a, int b) { @@ -165,9 +166,7 @@ public final class TBaseHelper { return 0; } - /** - * Comparator to compare items inside a structure (e.g. a list, set, or map). - */ + /** Comparator to compare items inside a structure (e.g. a list, set, or map). */ private static class NestedStructureComparator implements Comparator, Serializable { public int compare(Object oA, Object oB) { if (oA == null && oB == null) { @@ -177,15 +176,15 @@ public final class TBaseHelper { } else if (oB == null) { return 1; } else if (oA instanceof List) { - return compareTo((List)oA, (List)oB); + return compareTo((List) oA, (List) oB); } else if (oA instanceof Set) { - return compareTo((Set)oA, (Set)oB); + return compareTo((Set) oA, (Set) oB); } else if (oA instanceof Map) { - return compareTo((Map)oA, (Map)oB); + return compareTo((Map) oA, (Map) oB); } else if (oA instanceof byte[]) { - return compareTo((byte[])oA, (byte[])oB); + return compareTo((byte[]) oA, (byte[]) oB); } else { - return compareTo((Comparable)oA, (Comparable)oB); + return compareTo((Comparable) oA, (Comparable) oB); } } } @@ -244,14 +243,15 @@ public final class TBaseHelper { public static boolean wrapsFullArray(ByteBuffer byteBuffer) { return byteBuffer.hasArray() - && byteBuffer.position() == 0 - && byteBuffer.arrayOffset() == 0 - && byteBuffer.remaining() == byteBuffer.capacity(); + && byteBuffer.position() == 0 + && byteBuffer.arrayOffset() == 0 + && byteBuffer.remaining() == byteBuffer.capacity(); } public static int byteBufferToByteArray(ByteBuffer byteBuffer, byte[] target, int offset) { int remaining = byteBuffer.remaining(); - System.arraycopy(byteBuffer.array(), + System.arraycopy( + byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), target, offset, @@ -275,7 +275,8 @@ public final class TBaseHelper { } ByteBuffer copy = ByteBuffer.wrap(new byte[orig.remaining()]); if (orig.hasArray()) { - System.arraycopy(orig.array(), orig.arrayOffset() + orig.position(), copy.array(), 0, orig.remaining()); + System.arraycopy( + orig.array(), orig.arrayOffset() + orig.position(), copy.array(), 0, orig.remaining()); } else { orig.slice().get(copy.array()); } diff --git a/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java b/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java index 55a0f15d3..05cd7b8cc 100644 --- a/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TBaseProcessor.java @@ -2,7 +2,6 @@ package org.apache.thrift; import java.util.Collections; import java.util.Map; - import org.apache.thrift.protocol.TMessage; import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; @@ -11,14 +10,15 @@ import org.apache.thrift.protocol.TType; public abstract class TBaseProcessor<I> implements TProcessor { private final I iface; - private final Map<String,ProcessFunction<I, ? extends TBase>> processMap; + private final Map<String, ProcessFunction<I, ? extends TBase>> processMap; - protected TBaseProcessor(I iface, Map<String, ProcessFunction<I, ? extends TBase>> processFunctionMap) { + protected TBaseProcessor( + I iface, Map<String, ProcessFunction<I, ? extends TBase>> processFunctionMap) { this.iface = iface; this.processMap = processFunctionMap; } - public Map<String,ProcessFunction<I, ? extends TBase>> getProcessMapView() { + public Map<String, ProcessFunction<I, ? extends TBase>> getProcessMapView() { return Collections.unmodifiableMap(processMap); } @@ -29,7 +29,9 @@ public abstract class TBaseProcessor<I> implements TProcessor { if (fn == null) { TProtocolUtil.skip(in, TType.STRUCT); in.readMessageEnd(); - TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, "Invalid method name: '"+msg.name+"'"); + TApplicationException x = + new TApplicationException( + TApplicationException.UNKNOWN_METHOD, "Invalid method name: '" + msg.name + "'"); out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); x.write(out); out.writeMessageEnd(); diff --git a/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java b/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java index 3a2d56c88..69bb5ba80 100644 --- a/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java +++ b/lib/java/src/main/java/org/apache/thrift/TByteArrayOutputStream.java @@ -22,11 +22,7 @@ package org.apache.thrift; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; -/** - * Class that allows access to the underlying buf without doing deep - * copies on it. - * - */ +/** Class that allows access to the underlying buf without doing deep copies on it. */ public class TByteArrayOutputStream extends ByteArrayOutputStream { private final int initialSize; diff --git a/lib/java/src/main/java/org/apache/thrift/TConfiguration.java b/lib/java/src/main/java/org/apache/thrift/TConfiguration.java index b98274aad..0391d5b23 100644 --- a/lib/java/src/main/java/org/apache/thrift/TConfiguration.java +++ b/lib/java/src/main/java/org/apache/thrift/TConfiguration.java @@ -18,84 +18,85 @@ */ package org.apache.thrift; - public class TConfiguration { - public static final int DEFAULT_MAX_MESSAGE_SIZE = 100 * 1024 * 1024; - public static final int DEFAULT_MAX_FRAME_SIZE = 16384000; // this value is used consistently across all Thrift libraries - public static final int DEFAULT_RECURSION_DEPTH = 64; + public static final int DEFAULT_MAX_MESSAGE_SIZE = 100 * 1024 * 1024; + public static final int DEFAULT_MAX_FRAME_SIZE = + 16384000; // this value is used consistently across all Thrift libraries + public static final int DEFAULT_RECURSION_DEPTH = 64; - private int maxMessageSize; - private int maxFrameSize; - private int recursionLimit; + private int maxMessageSize; + private int maxFrameSize; + private int recursionLimit; - public TConfiguration() { - this(DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_FRAME_SIZE, DEFAULT_RECURSION_DEPTH); - } - public TConfiguration(int maxMessageSize, int maxFrameSize, int recursionLimit) { - this.maxFrameSize = maxFrameSize; - this.maxMessageSize = maxMessageSize; - this.recursionLimit = recursionLimit; - } + public TConfiguration() { + this(DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_FRAME_SIZE, DEFAULT_RECURSION_DEPTH); + } - public int getMaxMessageSize() { - return maxMessageSize; - } + public TConfiguration(int maxMessageSize, int maxFrameSize, int recursionLimit) { + this.maxFrameSize = maxFrameSize; + this.maxMessageSize = maxMessageSize; + this.recursionLimit = recursionLimit; + } - public int getMaxFrameSize() { - return maxFrameSize; - } + public int getMaxMessageSize() { + return maxMessageSize; + } - public int getRecursionLimit() { - return recursionLimit; - } + public int getMaxFrameSize() { + return maxFrameSize; + } - public void setMaxMessageSize(int maxMessageSize) { - this.maxMessageSize = maxMessageSize; - } + public int getRecursionLimit() { + return recursionLimit; + } - public void setMaxFrameSize(int maxFrameSize) { - this.maxFrameSize = maxFrameSize; + public void setMaxMessageSize(int maxMessageSize) { + this.maxMessageSize = maxMessageSize; + } + + public void setMaxFrameSize(int maxFrameSize) { + this.maxFrameSize = maxFrameSize; + } + + public void setRecursionLimit(int recursionLimit) { + this.recursionLimit = recursionLimit; + } + + public static final TConfiguration DEFAULT = new Builder().build(); + + public static TConfiguration.Builder custom() { + return new Builder(); + } + + public static class Builder { + private int maxMessageSize; + private int maxFrameSize; + private int recursionLimit; + + Builder() { + super(); + this.maxFrameSize = DEFAULT_MAX_FRAME_SIZE; + this.maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE; + this.recursionLimit = DEFAULT_RECURSION_DEPTH; } - public void setRecursionLimit(int recursionLimit) { - this.recursionLimit = recursionLimit; + public Builder setMaxMessageSize(int maxMessageSize) { + this.maxMessageSize = maxMessageSize; + return this; } - public static final TConfiguration DEFAULT = new Builder().build(); + public Builder setMaxFrameSize(int maxFrameSize) { + this.maxFrameSize = maxFrameSize; + return this; + } - public static TConfiguration.Builder custom() { - return new Builder(); + public Builder setRecursionLimit(int recursionLimit) { + this.recursionLimit = recursionLimit; + return this; } - public static class Builder { - private int maxMessageSize ; - private int maxFrameSize; - private int recursionLimit ; - - Builder() { - super(); - this.maxFrameSize = DEFAULT_MAX_FRAME_SIZE; - this.maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE; - this.recursionLimit = DEFAULT_RECURSION_DEPTH; - } - - public Builder setMaxMessageSize(int maxMessageSize) { - this.maxMessageSize = maxMessageSize; - return this; - } - - public Builder setMaxFrameSize(int maxFrameSize) { - this.maxFrameSize = maxFrameSize; - return this; - } - - public Builder setRecursionLimit(int recursionLimit) { - this.recursionLimit = recursionLimit; - return this; - } - - public TConfiguration build() { - return new TConfiguration(maxMessageSize, maxFrameSize, recursionLimit); - } + public TConfiguration build() { + return new TConfiguration(maxMessageSize, maxFrameSize, recursionLimit); } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/TDeserializer.java b/lib/java/src/main/java/org/apache/thrift/TDeserializer.java index dd63996db..1cdc54870 100644 --- a/lib/java/src/main/java/org/apache/thrift/TDeserializer.java +++ b/lib/java/src/main/java/org/apache/thrift/TDeserializer.java @@ -19,6 +19,9 @@ package org.apache.thrift; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.util.Collection; import org.apache.thrift.meta_data.EnumMetaData; import org.apache.thrift.meta_data.StructMetaData; import org.apache.thrift.partial.TFieldData; @@ -38,15 +41,7 @@ import org.apache.thrift.protocol.TType; import org.apache.thrift.transport.TMemoryInputTransport; import org.apache.thrift.transport.TTransportException; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.util.Collection; - -/** - * Generic utility for easily deserializing objects from a byte array or Java - * String. - * - */ +/** Generic utility for easily deserializing objects from a byte array or Java String. */ public class TDeserializer { private final TProtocol protocol_; private final TMemoryInputTransport trans_; @@ -67,8 +62,8 @@ public class TDeserializer { } /** - * Create a new TDeserializer. It will use the TProtocol specified by the - * factory that is passed in. + * Create a new TDeserializer. It will use the TProtocol specified by the factory that is passed + * in. * * @param protocolFactory Factory to create a protocol * @throws TTransportException if there an error initializing the underlying transport. @@ -79,8 +74,8 @@ public class TDeserializer { } /** - * Construct a new TDeserializer that supports partial deserialization - * that outputs instances of type controlled by the given {@code processor}. + * Construct a new TDeserializer that supports partial deserialization that outputs instances of + * type controlled by the given {@code processor}. * * @param thriftClass a TBase derived class. * @param fieldNames list of fields to deserialize. @@ -91,7 +86,8 @@ public class TDeserializer { Class<? extends TBase> thriftClass, Collection<String> fieldNames, ThriftFieldValueProcessor processor, - TProtocolFactory protocolFactory) throws TTransportException { + TProtocolFactory protocolFactory) + throws TTransportException { this(protocolFactory); Validate.checkNotNull(thriftClass, "thriftClass"); @@ -103,8 +99,8 @@ public class TDeserializer { } /** - * Construct a new TDeserializer that supports partial deserialization - * that outputs {@code TBase} instances. + * Construct a new TDeserializer that supports partial deserialization that outputs {@code TBase} + * instances. * * @param thriftClass a TBase derived class. * @param fieldNames list of fields to deserialize. @@ -113,7 +109,8 @@ public class TDeserializer { public TDeserializer( Class<? extends TBase> thriftClass, Collection<String> fieldNames, - TProtocolFactory protocolFactory) throws TTransportException { + TProtocolFactory protocolFactory) + throws TTransportException { this(thriftClass, fieldNames, new ThriftStructProcessor(), protocolFactory); } @@ -134,7 +131,7 @@ public class TDeserializer { * @throws TException if an error is encountered during deserialization. */ public void deserialize(TBase base, byte[] bytes) throws TException { - deserialize(base, bytes, 0, bytes.length); + deserialize(base, bytes, 0, bytes.length); } /** @@ -161,8 +158,7 @@ public class TDeserializer { } /** - * Deserialize the Thrift object from a Java string, using a specified - * character set for decoding. + * Deserialize the Thrift object from a Java string, using a specified character set for decoding. * * @param base The object to read into * @param data The string to read from @@ -180,15 +176,18 @@ public class TDeserializer { } /** - * Deserialize only a single Thrift object (addressed by recursively using field id) - * from a byte record. + * Deserialize only a single Thrift object (addressed by recursively using field id) from a byte + * record. + * * @param tb The object to read into * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path tb * @param fieldIdPathRest The rest FieldId's that define a path tb * @throws TException if an error is encountered during deserialization. */ - public void partialDeserialize(TBase tb, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public void partialDeserialize( + TBase tb, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { try { if (locateField(bytes, fieldIdPathFirst, fieldIdPathRest) != null) { // if this line is reached, iprot will be positioned at the start of tb. @@ -203,123 +202,143 @@ public class TDeserializer { } /** - * Deserialize only a boolean field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a boolean field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a boolean field * @param fieldIdPathRest The rest FieldId's that define a path to a boolean field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Boolean partialDeserializeBool(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Boolean partialDeserializeBool( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Boolean) partialDeserializeField(TType.BOOL, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a byte field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a byte field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a byte field * @param fieldIdPathRest The rest FieldId's that define a path to a byte field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Byte partialDeserializeByte(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Byte partialDeserializeByte( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Byte) partialDeserializeField(TType.BYTE, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a double field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a double field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a double field * @param fieldIdPathRest The rest FieldId's that define a path to a double field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Double partialDeserializeDouble(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Double partialDeserializeDouble( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Double) partialDeserializeField(TType.DOUBLE, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only an i16 field (addressed by recursively using field id) - * from a byte record. + * Deserialize only an i16 field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to an i16 field * @param fieldIdPathRest The rest FieldId's that define a path to an i16 field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Short partialDeserializeI16(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Short partialDeserializeI16( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Short) partialDeserializeField(TType.I16, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only an i32 field (addressed by recursively using field id) - * from a byte record. + * Deserialize only an i32 field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to an i32 field * @param fieldIdPathRest The rest FieldId's that define a path to an i32 field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Integer partialDeserializeI32(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Integer partialDeserializeI32( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Integer) partialDeserializeField(TType.I32, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only an i64 field (addressed by recursively using field id) - * from a byte record. + * Deserialize only an i64 field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to an i64 field * @param fieldIdPathRest The rest FieldId's that define a path to an i64 field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Long partialDeserializeI64(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Long partialDeserializeI64( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (Long) partialDeserializeField(TType.I64, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a string field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a string field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a string field * @param fieldIdPathRest The rest FieldId's that define a path to a string field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public String partialDeserializeString(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public String partialDeserializeString( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { return (String) partialDeserializeField(TType.STRING, bytes, fieldIdPathFirst, fieldIdPathRest); } /** - * Deserialize only a binary field (addressed by recursively using field id) - * from a byte record. + * Deserialize only a binary field (addressed by recursively using field id) from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a binary field * @param fieldIdPathRest The rest FieldId's that define a path to a binary field * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public ByteBuffer partialDeserializeByteArray(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public ByteBuffer partialDeserializeByteArray( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { // TType does not have binary, so we use the arbitrary num 100 - return (ByteBuffer) partialDeserializeField((byte)100, bytes, fieldIdPathFirst, fieldIdPathRest); + return (ByteBuffer) + partialDeserializeField((byte) 100, bytes, fieldIdPathFirst, fieldIdPathRest); } /** * Deserialize only the id of the field set in a TUnion (addressed by recursively using field id) * from a byte record. + * * @param bytes The serialized object to read from * @param fieldIdPathFirst First of the FieldId's that define a path to a TUnion * @param fieldIdPathRest The rest FieldId's that define a path to a TUnion * @return the deserialized value. * @throws TException if an error is encountered during deserialization. */ - public Short partialDeserializeSetFieldIdInUnion(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + public Short partialDeserializeSetFieldIdInUnion( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { try { TField field = locateField(bytes, fieldIdPathFirst, fieldIdPathRest); - if (field != null){ + if (field != null) { protocol_.readStructBegin(); // The Union return protocol_.readFieldBegin().id; // The field set in the union } @@ -332,7 +351,9 @@ public class TDeserializer { } } - private Object partialDeserializeField(byte ttype, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + private Object partialDeserializeField( + byte ttype, byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { try { TField field = locateField(bytes, fieldIdPathFirst, fieldIdPathRest); if (field != null) { @@ -340,22 +361,22 @@ public class TDeserializer { // if this point is reached, iprot will be positioned at the start of // the field switch (ttype) { - case TType.BOOL: - return protocol_.readBool(); - case TType.BYTE: - return protocol_.readByte(); - case TType.DOUBLE: - return protocol_.readDouble(); - case TType.I16: - return protocol_.readI16(); - case TType.I32: - return protocol_.readI32(); - case TType.I64: - return protocol_.readI64(); - case TType.STRING: - return protocol_.readString(); - default: - return null; + case TType.BOOL: + return protocol_.readBool(); + case TType.BYTE: + return protocol_.readByte(); + case TType.DOUBLE: + return protocol_.readDouble(); + case TType.I16: + return protocol_.readI16(); + case TType.I32: + return protocol_.readI32(); + case TType.I64: + return protocol_.readI64(); + case TType.STRING: + return protocol_.readString(); + default: + return null; } } // hack to differentiate between string and binary @@ -372,7 +393,9 @@ public class TDeserializer { } } - private TField locateField(byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + private TField locateField( + byte[] bytes, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum... fieldIdPathRest) + throws TException { trans_.reset(bytes); TFieldIdEnum[] fieldIdPath = new TFieldIdEnum[fieldIdPathRest.length + 1]; @@ -412,8 +435,7 @@ public class TDeserializer { } /** - * Deserialize the Thrift object from a Java string, using the default JVM - * charset encoding. + * Deserialize the Thrift object from a Java string, using the default JVM charset encoding. * * @param base The object to read into * @param data The string to read from @@ -569,9 +591,7 @@ public class TDeserializer { } private void deserializeStructField( - Object instance, - TFieldIdEnum fieldId, - ThriftMetadata.ThriftObject data) throws TException { + Object instance, TFieldIdEnum fieldId, ThriftMetadata.ThriftObject data) throws TException { byte fieldType = data.data.valueMetaData.type; Object value; @@ -695,8 +715,7 @@ public class TDeserializer { private void ensurePartialDeserializationMode() throws IllegalStateException { if (!this.isPartialDeserializationMode()) { throw new IllegalStateException( - "Members metadata and processor must be correctly initialized in order to use this method" - ); + "Members metadata and processor must be correctly initialized in order to use this method"); } } @@ -705,8 +724,7 @@ public class TDeserializer { if (!(this.processor_ instanceof ThriftStructProcessor)) { throw new IllegalStateException( - "processor must be an instance of ThriftStructProcessor to use this method" - ); + "processor must be an instance of ThriftStructProcessor to use this method"); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java b/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java index fbc778751..84aa82e8d 100644 --- a/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java +++ b/lib/java/src/main/java/org/apache/thrift/TEnumHelper.java @@ -19,27 +19,20 @@ package org.apache.thrift; -import java.lang.NoSuchMethodException; -import java.lang.IllegalAccessException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -/** - * Utility class with static methods for interacting with TEnum - */ +/** Utility class with static methods for interacting with TEnum */ public class TEnumHelper { /** - * Given a TEnum class and integer value, this method will return - * the associated constant from the given TEnum class. - * This method MUST be modified should the name of the 'findByValue' method + * Given a TEnum class and integer value, this method will return the associated constant from the + * given TEnum class. This method MUST be modified should the name of the 'findByValue' method * change. * * @param enumClass TEnum from which to return a matching constant. * @param value Value for which to return the constant. - * - * @return The constant in 'enumClass' whose value is 'value' or null if - * something went wrong. + * @return The constant in 'enumClass' whose value is 'value' or null if something went wrong. */ public static TEnum getByValue(Class<? extends TEnum> enumClass, int value) { try { diff --git a/lib/java/src/main/java/org/apache/thrift/TException.java b/lib/java/src/main/java/org/apache/thrift/TException.java index f84f4812e..b2273d919 100644 --- a/lib/java/src/main/java/org/apache/thrift/TException.java +++ b/lib/java/src/main/java/org/apache/thrift/TException.java @@ -19,10 +19,7 @@ package org.apache.thrift; -/** - * Generic exception class for Thrift. - * - */ +/** Generic exception class for Thrift. */ public class TException extends Exception { private static final long serialVersionUID = 1L; diff --git a/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java b/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java index 20b845e61..f270630b0 100644 --- a/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java +++ b/lib/java/src/main/java/org/apache/thrift/TFieldIdEnum.java @@ -18,9 +18,7 @@ */ package org.apache.thrift; -/** - * Interface for all generated struct Fields objects. - */ +/** Interface for all generated struct Fields objects. */ public interface TFieldIdEnum { /** * Gets the Thrift field id for the named field. diff --git a/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java b/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java index 74bac4eff..065cdfcc5 100644 --- a/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java +++ b/lib/java/src/main/java/org/apache/thrift/TFieldRequirementType.java @@ -19,12 +19,9 @@ package org.apache.thrift; -/** - * Requirement type constants. - * - */ +/** Requirement type constants. */ public final class TFieldRequirementType { - public static final byte REQUIRED = 1; + public static final byte REQUIRED = 1; public static final byte OPTIONAL = 2; public static final byte DEFAULT = 3; } diff --git a/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java b/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java index d797a606f..28ae13880 100644 --- a/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TMultiplexedProcessor.java @@ -19,19 +19,20 @@ package org.apache.thrift; -import org.apache.thrift.protocol.*; - -import java.util.Map; import java.util.HashMap; +import java.util.Map; +import org.apache.thrift.protocol.*; /** - * <code>TMultiplexedProcessor</code> is a <code>TProcessor</code> allowing - * a single <code>TServer</code> to provide multiple services. + * <code>TMultiplexedProcessor</code> is a <code>TProcessor</code> allowing a single <code>TServer + * </code> to provide multiple services. + * + * <p>To do so, you instantiate the processor and then register additional processors with it, as + * shown in the following example: * - * <p>To do so, you instantiate the processor and then register additional - * processors with it, as shown in the following example:</p> + * <blockquote> * - * <blockquote><code> + * <code> * TMultiplexedProcessor processor = new TMultiplexedProcessor(); * * processor.registerProcessor( @@ -46,113 +47,121 @@ import java.util.HashMap; * TSimpleServer server = new TSimpleServer(processor, t); * * server.serve(); - * </code></blockquote> + * </code> + * + * </blockquote> */ public class TMultiplexedProcessor implements TProcessor { - private final Map<String,TProcessor> SERVICE_PROCESSOR_MAP - = new HashMap<String,TProcessor>(); - private TProcessor defaultProcessor; + private final Map<String, TProcessor> SERVICE_PROCESSOR_MAP = new HashMap<String, TProcessor>(); + private TProcessor defaultProcessor; - /** - * 'Register' a service with this <code>TMultiplexedProcessor</code>. This - * allows us to broker requests to individual services by using the service - * name to select them at request time. - * - * @param serviceName Name of a service, has to be identical to the name - * declared in the Thrift IDL, e.g. "WeatherReport". - * @param processor Implementation of a service, usually referred to - * as "handlers", e.g. WeatherReportHandler implementing WeatherReport.Iface. - */ - public void registerProcessor(String serviceName, TProcessor processor) { - SERVICE_PROCESSOR_MAP.put(serviceName, processor); - } + /** + * 'Register' a service with this <code>TMultiplexedProcessor</code>. This allows us to broker + * requests to individual services by using the service name to select them at request time. + * + * @param serviceName Name of a service, has to be identical to the name declared in the Thrift + * IDL, e.g. "WeatherReport". + * @param processor Implementation of a service, usually referred to as "handlers", e.g. + * WeatherReportHandler implementing WeatherReport.Iface. + */ + public void registerProcessor(String serviceName, TProcessor processor) { + SERVICE_PROCESSOR_MAP.put(serviceName, processor); + } - /** - * Register a service to be called to process queries without service name - * @param processor the service to be called. - */ - public void registerDefault(TProcessor processor) { - defaultProcessor = processor; + /** + * Register a service to be called to process queries without service name + * + * @param processor the service to be called. + */ + public void registerDefault(TProcessor processor) { + defaultProcessor = processor; + } + + /** + * This implementation of <code>process</code> performs the following steps: + * + * <ol> + * <li>Read the beginning of the message. + * <li>Extract the service name from the message. + * <li>Using the service name to locate the appropriate processor. + * <li>Dispatch to the processor, with a decorated instance of TProtocol that allows + * readMessageBegin() to return the original TMessage. + * </ol> + * + * @throws TProtocolException If the message type is not CALL or ONEWAY, if the service name was + * not found in the message, or if the service name was not found in the service map. You + * called {@link #registerProcessor(String, TProcessor) registerProcessor} during + * initialization, right? :) + */ + public void process(TProtocol iprot, TProtocol oprot) throws TException { + /* + Use the actual underlying protocol (e.g. TBinaryProtocol) to read the + message header. This pulls the message "off the wire", which we'll + deal with at the end of this method. + */ + TMessage message = iprot.readMessageBegin(); + + if (message.type != TMessageType.CALL && message.type != TMessageType.ONEWAY) { + throw new TProtocolException( + TProtocolException.NOT_IMPLEMENTED, "This should not have happened!?"); } - /** - * This implementation of <code>process</code> performs the following steps: - * - * <ol> - * <li>Read the beginning of the message.</li> - * <li>Extract the service name from the message.</li> - * <li>Using the service name to locate the appropriate processor.</li> - * <li>Dispatch to the processor, with a decorated instance of TProtocol - * that allows readMessageBegin() to return the original TMessage.</li> - * </ol> - * - * @throws TProtocolException If the message type is not CALL or ONEWAY, if - * the service name was not found in the message, or if the service - * name was not found in the service map. You called {@link #registerProcessor(String, TProcessor) registerProcessor} - * during initialization, right? :) - */ - public void process(TProtocol iprot, TProtocol oprot) throws TException { - /* - Use the actual underlying protocol (e.g. TBinaryProtocol) to read the - message header. This pulls the message "off the wire", which we'll - deal with at the end of this method. - */ - TMessage message = iprot.readMessageBegin(); + // Extract the service name + int index = message.name.indexOf(TMultiplexedProtocol.SEPARATOR); + if (index < 0) { + if (defaultProcessor != null) { + // Dispatch processing to the stored processor + defaultProcessor.process(new StoredMessageProtocol(iprot, message), oprot); + return; + } + throw new TProtocolException( + TProtocolException.NOT_IMPLEMENTED, + "Service name not found in message name: " + + message.name + + ". Did you " + + "forget to use a TMultiplexProtocol in your client?"); + } - if (message.type != TMessageType.CALL && message.type != TMessageType.ONEWAY) { - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "This should not have happened!?"); - } + // Create a new TMessage, something that can be consumed by any TProtocol + String serviceName = message.name.substring(0, index); + TProcessor actualProcessor = SERVICE_PROCESSOR_MAP.get(serviceName); + if (actualProcessor == null) { + throw new TProtocolException( + TProtocolException.NOT_IMPLEMENTED, + "Service name not found: " + + serviceName + + ". Did you forget " + + "to call registerProcessor()?"); + } - // Extract the service name - int index = message.name.indexOf(TMultiplexedProtocol.SEPARATOR); - if (index < 0) { - if (defaultProcessor != null) { - // Dispatch processing to the stored processor - defaultProcessor.process(new StoredMessageProtocol(iprot, message), oprot); - return; - } - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Service name not found in message name: " + message.name + ". Did you " + - "forget to use a TMultiplexProtocol in your client?"); - } + // Create a new TMessage, removing the service name + TMessage standardMessage = + new TMessage( + message.name.substring(serviceName.length() + TMultiplexedProtocol.SEPARATOR.length()), + message.type, + message.seqid); - // Create a new TMessage, something that can be consumed by any TProtocol - String serviceName = message.name.substring(0, index); - TProcessor actualProcessor = SERVICE_PROCESSOR_MAP.get(serviceName); - if (actualProcessor == null) { - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Service name not found: " + serviceName + ". Did you forget " + - "to call registerProcessor()?"); - } + // Dispatch processing to the stored processor + actualProcessor.process(new StoredMessageProtocol(iprot, standardMessage), oprot); + } - // Create a new TMessage, removing the service name - TMessage standardMessage = new TMessage( - message.name.substring(serviceName.length()+TMultiplexedProtocol.SEPARATOR.length()), - message.type, - message.seqid - ); + /** + * Our goal was to work with any protocol. In order to do that, we needed to allow them to call + * readMessageBegin() and get a TMessage in exactly the standard format, without the service name + * prepended to TMessage.name. + */ + private static class StoredMessageProtocol extends TProtocolDecorator { + TMessage messageBegin; - // Dispatch processing to the stored processor - actualProcessor.process(new StoredMessageProtocol(iprot, standardMessage), oprot); + public StoredMessageProtocol(TProtocol protocol, TMessage messageBegin) { + super(protocol); + this.messageBegin = messageBegin; } - /** - * Our goal was to work with any protocol. In order to do that, we needed - * to allow them to call readMessageBegin() and get a TMessage in exactly - * the standard format, without the service name prepended to TMessage.name. - */ - private static class StoredMessageProtocol extends TProtocolDecorator { - TMessage messageBegin; - public StoredMessageProtocol(TProtocol protocol, TMessage messageBegin) { - super(protocol); - this.messageBegin = messageBegin; - } - @Override - public TMessage readMessageBegin() throws TException { - return messageBegin; - } + @Override + public TMessage readMessageBegin() throws TException { + return messageBegin; } - + } } diff --git a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java index 13e8031b6..034cc8599 100644 --- a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java +++ b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchClient.java @@ -1,25 +1,23 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -35,49 +33,39 @@ import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * This class uses a single thread to set up non-blocking sockets to a set - * of remote servers (hostname and port pairs), and sends a same request to - * all these servers. It then fetches responses from servers. + * This class uses a single thread to set up non-blocking sockets to a set of remote servers + * (hostname and port pairs), and sends a same request to all these servers. It then fetches + * responses from servers. * - * Parameters: - * int maxRecvBufBytesPerServer - an upper limit for receive buffer size - * per server (in byte). If a response from a server exceeds this limit, the - * client will not allocate memory or read response data for it. + * <p>Parameters: int maxRecvBufBytesPerServer - an upper limit for receive buffer size per server + * (in byte). If a response from a server exceeds this limit, the client will not allocate memory or + * read response data for it. * - * int fetchTimeoutSeconds - time limit for fetching responses from all - * servers (in second). After the timeout, the fetch job is stopped and - * available responses are returned. + * <p>int fetchTimeoutSeconds - time limit for fetching responses from all servers (in second). + * After the timeout, the fetch job is stopped and available responses are returned. * - * ByteBuffer requestBuf - request message that is sent to all servers. + * <p>ByteBuffer requestBuf - request message that is sent to all servers. * - * Output: - * Responses are stored in an array of ByteBuffers. Index of elements in - * this array corresponds to index of servers in the server list. Content in - * a ByteBuffer may be in one of the following forms: - * 1. First 4 bytes form an integer indicating length of following data, - * then followed by the data. - * 2. First 4 bytes form an integer indicating length of following data, - * then followed by nothing - this happens when the response data size - * exceeds maxRecvBufBytesPerServer, and the client will not read any - * response data. - * 3. No data in the ByteBuffer - this happens when the server does not - * return any response within fetchTimeoutSeconds. + * <p>Output: Responses are stored in an array of ByteBuffers. Index of elements in this array + * corresponds to index of servers in the server list. Content in a ByteBuffer may be in one of the + * following forms: 1. First 4 bytes form an integer indicating length of following data, then + * followed by the data. 2. First 4 bytes form an integer indicating length of following data, then + * followed by nothing - this happens when the response data size exceeds maxRecvBufBytesPerServer, + * and the client will not read any response data. 3. No data in the ByteBuffer - this happens when + * the server does not return any response within fetchTimeoutSeconds. * - * In some special cases (no servers are given, fetchTimeoutSeconds less - * than or equal to 0, requestBuf is null), the return is null. - * - * Note: - * It assumes all remote servers are TNonblockingServers and use - * TFramedTransport. + * <p>In some special cases (no servers are given, fetchTimeoutSeconds less than or equal to 0, + * requestBuf is null), the return is null. * + * <p>Note: It assumes all remote servers are TNonblockingServers and use TFramedTransport. */ public class TNonblockingMultiFetchClient { - private static final Logger LOGGER = LoggerFactory.getLogger( - TNonblockingMultiFetchClient.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TNonblockingMultiFetchClient.class); // if the size of the response msg exceeds this limit (in byte), we will // not read the msg @@ -97,9 +85,11 @@ public class TNonblockingMultiFetchClient { private TNonblockingMultiFetchStats stats; private ByteBuffer[] recvBuf; - public TNonblockingMultiFetchClient(int maxRecvBufBytesPerServer, - int fetchTimeoutSeconds, ByteBuffer requestBuf, - List<InetSocketAddress> servers) { + public TNonblockingMultiFetchClient( + int maxRecvBufBytesPerServer, + int fetchTimeoutSeconds, + ByteBuffer requestBuf, + List<InetSocketAddress> servers) { this.maxRecvBufBytesPerServer = maxRecvBufBytesPerServer; this.fetchTimeoutSeconds = fetchTimeoutSeconds; this.requestBuf = requestBuf; @@ -154,8 +144,7 @@ public class TNonblockingMultiFetchClient { recvBuf = null; stats.clear(); - if (servers == null || servers.size() == 0 || - requestBuf == null || fetchTimeoutSeconds <= 0) { + if (servers == null || servers.size() == 0 || requestBuf == null || fetchTimeoutSeconds <= 0) { return recvBuf; } @@ -185,9 +174,8 @@ public class TNonblockingMultiFetchClient { } /** - * Private class that does real fetch job. - * Users are not allowed to directly use this class, as its run() - * function may run forever. + * Private class that does real fetch job. Users are not allowed to directly use this class, as + * its run() function may run forever. */ private class MultiFetch implements Runnable { private Selector selector; @@ -195,11 +183,11 @@ public class TNonblockingMultiFetchClient { /** * main entry function for fetching. * - * Server responses are stored in TNonblocingMultiFetchClient.recvBuf, - * and fetch statistics is in TNonblockingMultiFetchClient.stats. + * <p>Server responses are stored in TNonblocingMultiFetchClient.recvBuf, and fetch statistics + * is in TNonblockingMultiFetchClient.stats. * - * Sanity check for parameters has been done in - * TNonblockingMultiFetchClient before calling this function. + * <p>Sanity check for parameters has been done in TNonblockingMultiFetchClient before calling + * this function. */ public void run() { long t1 = System.currentTimeMillis(); @@ -208,7 +196,7 @@ public class TNonblockingMultiFetchClient { stats.setNumTotalServers(numTotalServers); // buffer for receiving response from servers - recvBuf = new ByteBuffer[numTotalServers]; + recvBuf = new ByteBuffer[numTotalServers]; // buffer for sending request ByteBuffer[] sendBuf = new ByteBuffer[numTotalServers]; long[] numBytesRead = new long[numTotalServers]; @@ -246,23 +234,26 @@ public class TNonblockingMultiFetchClient { // free resource if (s != null) { - try {s.close();} catch (Exception ex) {} + try { + s.close(); + } catch (Exception ex) { + } } if (key != null) { - key.cancel(); + key.cancel(); } } } // wait for events - while (stats.getNumReadCompletedServers() + - stats.getNumConnectErrorServers() < stats.getNumTotalServers()) { + while (stats.getNumReadCompletedServers() + stats.getNumConnectErrorServers() + < stats.getNumTotalServers()) { // if the thread is interrupted (e.g., task is cancelled) if (Thread.currentThread().isInterrupted()) { return; } - try{ + try { selector.select(); } catch (Exception e) { LOGGER.error("Selector selects error", e); @@ -275,13 +266,13 @@ public class TNonblockingMultiFetchClient { it.remove(); // get previously attached index - int index = (Integer)selKey.attachment(); + int index = (Integer) selKey.attachment(); if (selKey.isValid() && selKey.isConnectable()) { // if this socket throws an exception (e.g., connection refused), // print error msg and skip it. try { - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); sChannel.finishConnect(); } catch (Exception e) { stats.incNumConnectErrorServers(); @@ -294,7 +285,7 @@ public class TNonblockingMultiFetchClient { // if this socket throws an exception, print error msg and // skip it. try { - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); sChannel.write(sendBuf[index]); } catch (Exception e) { LOGGER.error("Socket {} writes to server {} error", index, servers.get(index), e); @@ -306,34 +297,38 @@ public class TNonblockingMultiFetchClient { // if this socket throws an exception, print error msg and // skip it. try { - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); int bytesRead = sChannel.read(recvBuf[index]); if (bytesRead > 0) { numBytesRead[index] += bytesRead; - if (!hasReadFrameSize[index] && - recvBuf[index].remaining()==0) { + if (!hasReadFrameSize[index] && recvBuf[index].remaining() == 0) { // if the frame size has been read completely, then prepare // to read the actual frame. frameSize[index] = recvBuf[index].getInt(0); if (frameSize[index] <= 0) { stats.incNumInvalidFrameSize(); - LOGGER.error("Read an invalid frame size {} from {}. Does the server use TFramedTransport?", - frameSize[index], servers.get(index)); + LOGGER.error( + "Read an invalid frame size {} from {}. Does the server use TFramedTransport?", + frameSize[index], + servers.get(index)); sChannel.close(); continue; } if (frameSize[index] + 4 > stats.getMaxResponseBytes()) { - stats.setMaxResponseBytes(frameSize[index]+4); + stats.setMaxResponseBytes(frameSize[index] + 4); } if (frameSize[index] + 4 > maxRecvBufBytesPerServer) { stats.incNumOverflowedRecvBuf(); - LOGGER.error("Read frame size {} from {}, total buffer size would exceed limit {}", - frameSize[index], servers.get(index), maxRecvBufBytesPerServer); + LOGGER.error( + "Read frame size {} from {}, total buffer size would exceed limit {}", + frameSize[index], + servers.get(index), + maxRecvBufBytesPerServer); sChannel.close(); continue; } @@ -346,34 +341,30 @@ public class TNonblockingMultiFetchClient { hasReadFrameSize[index] = true; } - if (hasReadFrameSize[index] && - numBytesRead[index] >= frameSize[index]+4) { + if (hasReadFrameSize[index] && numBytesRead[index] >= frameSize[index] + 4) { // has read all data sChannel.close(); stats.incNumReadCompletedServers(); long t2 = System.currentTimeMillis(); - stats.setReadTime(t2-t1); + stats.setReadTime(t2 - t1); } } } catch (Exception e) { - LOGGER.error("Socket {} reads from server {} error", - index, servers.get(index), e); + LOGGER.error("Socket {} reads from server {} error", index, servers.get(index), e); } } } } } - /** - * dispose any resource allocated - */ + /** dispose any resource allocated */ public void close() { try { if (selector.isOpen()) { Iterator<SelectionKey> it = selector.keys().iterator(); while (it.hasNext()) { SelectionKey selKey = it.next(); - SocketChannel sChannel = (SocketChannel)selKey.channel(); + SocketChannel sChannel = (SocketChannel) selKey.channel(); sChannel.close(); } diff --git a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java index 90b86208b..bc0243738 100644 --- a/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java +++ b/lib/java/src/main/java/org/apache/thrift/TNonblockingMultiFetchStats.java @@ -1,36 +1,35 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; -/** - * This class keeps track of statistics for TNonblockinMultiFetchClient. - */ +/** This class keeps track of statistics for TNonblockinMultiFetchClient. */ public class TNonblockingMultiFetchStats { - private int numTotalServers; - private int numReadCompletedServers; - private int numConnectErrorServers; - private int totalRecvBufBytes; - private int maxResponseBytes; - private int numOverflowedRecvBuf; - private int numInvalidFrameSize; + private int numTotalServers; + private int numReadCompletedServers; + private int numConnectErrorServers; + private int totalRecvBufBytes; + private int maxResponseBytes; + private int numOverflowedRecvBuf; + private int numInvalidFrameSize; // time from the beginning of fetch() function to the reading finish // time of the last socket (in milli-second) - private long readTime; + private long readTime; public TNonblockingMultiFetchStats() { clear(); @@ -48,33 +47,86 @@ public class TNonblockingMultiFetchStats { } public String toString() { - String stats = String.format("numTotalServers=%d, " + - "numReadCompletedServers=%d, numConnectErrorServers=%d, " + - "numUnresponsiveServers=%d, totalRecvBufBytes=%fM, " + - "maxResponseBytes=%d, numOverflowedRecvBuf=%d, " + - "numInvalidFrameSize=%d, readTime=%dms", - numTotalServers, numReadCompletedServers, numConnectErrorServers, - (numTotalServers-numReadCompletedServers-numConnectErrorServers), - totalRecvBufBytes/1024.0/1024, maxResponseBytes, numOverflowedRecvBuf, - numInvalidFrameSize, readTime); + String stats = + String.format( + "numTotalServers=%d, " + + "numReadCompletedServers=%d, numConnectErrorServers=%d, " + + "numUnresponsiveServers=%d, totalRecvBufBytes=%fM, " + + "maxResponseBytes=%d, numOverflowedRecvBuf=%d, " + + "numInvalidFrameSize=%d, readTime=%dms", + numTotalServers, + numReadCompletedServers, + numConnectErrorServers, + (numTotalServers - numReadCompletedServers - numConnectErrorServers), + totalRecvBufBytes / 1024.0 / 1024, + maxResponseBytes, + numOverflowedRecvBuf, + numInvalidFrameSize, + readTime); return stats; } - public void setNumTotalServers(int val) { numTotalServers = val; } - public void setMaxResponseBytes(int val) { maxResponseBytes = val; } - public void setReadTime(long val) { readTime = val; } - public void incNumReadCompletedServers() { numReadCompletedServers++; } - public void incNumConnectErrorServers() { numConnectErrorServers++; } - public void incNumOverflowedRecvBuf() { numOverflowedRecvBuf++; } - public void incTotalRecvBufBytes(int val) { totalRecvBufBytes += val; } - public void incNumInvalidFrameSize() { numInvalidFrameSize++; } - - public int getMaxResponseBytes() { return maxResponseBytes; } - public int getNumReadCompletedServers() { return numReadCompletedServers; } - public int getNumConnectErrorServers() { return numConnectErrorServers; } - public int getNumTotalServers() { return numTotalServers; } - public int getNumOverflowedRecvBuf() { return numOverflowedRecvBuf;} - public int getTotalRecvBufBytes() { return totalRecvBufBytes;} - public int getNumInvalidFrameSize() { return numInvalidFrameSize; } - public long getReadTime() { return readTime; } + public void setNumTotalServers(int val) { + numTotalServers = val; + } + + public void setMaxResponseBytes(int val) { + maxResponseBytes = val; + } + + public void setReadTime(long val) { + readTime = val; + } + + public void incNumReadCompletedServers() { + numReadCompletedServers++; + } + + public void incNumConnectErrorServers() { + numConnectErrorServers++; + } + + public void incNumOverflowedRecvBuf() { + numOverflowedRecvBuf++; + } + + public void incTotalRecvBufBytes(int val) { + totalRecvBufBytes += val; + } + + public void incNumInvalidFrameSize() { + numInvalidFrameSize++; + } + + public int getMaxResponseBytes() { + return maxResponseBytes; + } + + public int getNumReadCompletedServers() { + return numReadCompletedServers; + } + + public int getNumConnectErrorServers() { + return numConnectErrorServers; + } + + public int getNumTotalServers() { + return numTotalServers; + } + + public int getNumOverflowedRecvBuf() { + return numOverflowedRecvBuf; + } + + public int getTotalRecvBufBytes() { + return totalRecvBufBytes; + } + + public int getNumInvalidFrameSize() { + return numInvalidFrameSize; + } + + public long getReadTime() { + return readTime; + } } diff --git a/lib/java/src/main/java/org/apache/thrift/TProcessor.java b/lib/java/src/main/java/org/apache/thrift/TProcessor.java index 15ba9c0fe..3a0e6fd2b 100644 --- a/lib/java/src/main/java/org/apache/thrift/TProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/TProcessor.java @@ -22,8 +22,8 @@ package org.apache.thrift; import org.apache.thrift.protocol.TProtocol; /** - * A processor is a generic object which operates upon an input stream and - * writes to some output stream. + * A processor is a generic object which operates upon an input stream and writes to some output + * stream. */ public interface TProcessor { public void process(TProtocol in, TProtocol out) throws TException; diff --git a/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java b/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java index 81933a211..fab4005ae 100644 --- a/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/TProcessorFactory.java @@ -21,10 +21,7 @@ package org.apache.thrift; import org.apache.thrift.transport.TTransport; -/** - * The default processor factory just returns a singleton - * instance. - */ +/** The default processor factory just returns a singleton instance. */ public class TProcessorFactory { private final TProcessor processor_; @@ -38,6 +35,6 @@ public class TProcessorFactory { } public boolean isAsyncProcessor() { - return processor_ instanceof TAsyncProcessor; + return processor_ instanceof TAsyncProcessor; } } diff --git a/lib/java/src/main/java/org/apache/thrift/TSerializable.java b/lib/java/src/main/java/org/apache/thrift/TSerializable.java index 317814b45..125280418 100644 --- a/lib/java/src/main/java/org/apache/thrift/TSerializable.java +++ b/lib/java/src/main/java/org/apache/thrift/TSerializable.java @@ -21,10 +21,7 @@ package org.apache.thrift; import org.apache.thrift.protocol.TProtocol; -/** - * Generic base interface for generated Thrift objects. - * - */ +/** Generic base interface for generated Thrift objects. */ public interface TSerializable { /** @@ -42,5 +39,4 @@ public interface TSerializable { * @throws TException if there is an error writing to oprot */ public void write(TProtocol oprot) throws TException; - } diff --git a/lib/java/src/main/java/org/apache/thrift/TSerializer.java b/lib/java/src/main/java/org/apache/thrift/TSerializer.java index 710cd2124..6c0c7c2f8 100644 --- a/lib/java/src/main/java/org/apache/thrift/TSerializer.java +++ b/lib/java/src/main/java/org/apache/thrift/TSerializer.java @@ -20,33 +20,22 @@ package org.apache.thrift; import java.io.ByteArrayOutputStream; - import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TTransportException; -/** - * Generic utility for easily serializing objects into a byte array or Java - * String. - * - */ +/** Generic utility for easily serializing objects into a byte array or Java String. */ public class TSerializer { - /** - * This is the byte array that data is actually serialized into - */ + /** This is the byte array that data is actually serialized into */ private final ByteArrayOutputStream baos_ = new ByteArrayOutputStream(); - /** - * This transport wraps that byte array - */ + /** This transport wraps that byte array */ private final TIOStreamTransport transport_; - /** - * Internal protocol used for serializing objects. - */ + /** Internal protocol used for serializing objects. */ private TProtocol protocol_; /** @@ -59,8 +48,7 @@ public class TSerializer { } /** - * Create a new TSerializer. It will use the TProtocol specified by the - * factory that is passed in. + * Create a new TSerializer. It will use the TProtocol specified by the factory that is passed in. * * @param protocolFactory Factory to create a protocol * @throws TTransportException if there an error initializing the underlying transport. @@ -71,9 +59,8 @@ public class TSerializer { } /** - * Serialize the Thrift object into a byte array. The process is simple, - * just clear the byte array output, write the object into it, and grab the - * raw bytes. + * Serialize the Thrift object into a byte array. The process is simple, just clear the byte array + * output, write the object into it, and grab the raw bytes. * * @param base The object to serialize * @return Serialized object in byte[] format @@ -86,8 +73,7 @@ public class TSerializer { } /** - * Serialize the Thrift object into a Java string, using the default JVM - * charset encoding. + * Serialize the Thrift object into a Java string, using the default JVM charset encoding. * * @param base The object to serialize * @return Serialized object as a String diff --git a/lib/java/src/main/java/org/apache/thrift/TServiceClient.java b/lib/java/src/main/java/org/apache/thrift/TServiceClient.java index 00a36ee7f..6c3759658 100644 --- a/lib/java/src/main/java/org/apache/thrift/TServiceClient.java +++ b/lib/java/src/main/java/org/apache/thrift/TServiceClient.java @@ -24,8 +24,8 @@ import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; /** - * A TServiceClient is used to communicate with a TService implementation - * across protocols and transports. + * A TServiceClient is used to communicate with a TService implementation across protocols and + * transports. */ public abstract class TServiceClient { public TServiceClient(TProtocol prot) { @@ -44,6 +44,7 @@ public abstract class TServiceClient { /** * Get the TProtocol being used as the input (read) protocol. + * * @return the TProtocol being used as the input (read) protocol. */ public TProtocol getInputProtocol() { @@ -52,28 +53,29 @@ public abstract class TServiceClient { /** * Get the TProtocol being used as the output (write) protocol. + * * @return the TProtocol being used as the output (write) protocol. */ public TProtocol getOutputProtocol() { return this.oprot_; } - protected void sendBase(String methodName, TBase<?,?> args) throws TException { + protected void sendBase(String methodName, TBase<?, ?> args) throws TException { sendBase(methodName, args, TMessageType.CALL); } - protected void sendBaseOneway(String methodName, TBase<?,?> args) throws TException { + protected void sendBaseOneway(String methodName, TBase<?, ?> args) throws TException { sendBase(methodName, args, TMessageType.ONEWAY); } - private void sendBase(String methodName, TBase<?,?> args, byte type) throws TException { + private void sendBase(String methodName, TBase<?, ?> args, byte type) throws TException { oprot_.writeMessageBegin(new TMessage(methodName, type, ++seqid_)); args.write(oprot_); oprot_.writeMessageEnd(); oprot_.getTransport().flush(); } - protected void receiveBase(TBase<?,?> result, String methodName) throws TException { + protected void receiveBase(TBase<?, ?> result, String methodName) throws TException { TMessage msg = iprot_.readMessageBegin(); if (msg.type == TMessageType.EXCEPTION) { TApplicationException x = new TApplicationException(); @@ -82,8 +84,11 @@ public abstract class TServiceClient { throw x; } if (msg.seqid != seqid_) { - throw new TApplicationException(TApplicationException.BAD_SEQUENCE_ID, - String.format("%s failed: out of sequence response: expected %d but got %d", methodName, seqid_, msg.seqid)); + throw new TApplicationException( + TApplicationException.BAD_SEQUENCE_ID, + String.format( + "%s failed: out of sequence response: expected %d but got %d", + methodName, seqid_, msg.seqid)); } result.read(iprot_); iprot_.readMessageEnd(); diff --git a/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java b/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java index 7f08ba674..16363329a 100644 --- a/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/TServiceClientFactory.java @@ -22,21 +22,24 @@ package org.apache.thrift; import org.apache.thrift.protocol.TProtocol; /** - * A TServiceClientFactory provides a general way to get a TServiceClient - * connected to a remote TService via a protocol. + * A TServiceClientFactory provides a general way to get a TServiceClient connected to a remote + * TService via a protocol. + * * @param <T> the type of TServiceClient to get. */ public interface TServiceClientFactory<T extends TServiceClient> { /** * Get a brand-new T using <i>prot</i> as both the input and output protocol. + * * @param prot The protocol to use for getting T. * @return A brand-new T using <i>prot</i> as both the input and output protocol. */ public T getClient(TProtocol prot); /** - * Get a brand new T using the specified input and output protocols. The - * input and output protocols may be the same instance. + * Get a brand new T using the specified input and output protocols. The input and output + * protocols may be the same instance. + * * @param iprot The input protocol to use for getting T. * @param oprot The output protocol to use for getting T. * @return a brand new T using the specified input and output protocols diff --git a/lib/java/src/main/java/org/apache/thrift/TUnion.java b/lib/java/src/main/java/org/apache/thrift/TUnion.java index 0ad6881a9..65c92dc56 100644 --- a/lib/java/src/main/java/org/apache/thrift/TUnion.java +++ b/lib/java/src/main/java/org/apache/thrift/TUnion.java @@ -1,19 +1,20 @@ -/** +/* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.thrift; @@ -24,7 +25,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.thrift.protocol.TField; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolException; @@ -34,7 +34,8 @@ import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; -public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> implements TBase<T, F> { +public abstract class TUnion<T extends TUnion<T, F>, F extends TFieldIdEnum> + implements TBase<T, F> { protected Object value_; protected F setField_; @@ -44,7 +45,9 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl value_ = null; } - private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); + private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = + new HashMap<Class<? extends IScheme>, SchemeFactory>(); + static { schemes.put(StandardScheme.class, new TUnionStandardSchemeFactory()); schemes.put(TupleScheme.class, new TUnionTupleSchemeFactory()); @@ -64,15 +67,15 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl private static Object deepCopyObject(Object o) { if (o instanceof TBase) { - return ((TBase)o).deepCopy(); + return ((TBase) o).deepCopy(); } else if (o instanceof ByteBuffer) { - return TBaseHelper.copyBinary((ByteBuffer)o); + return TBaseHelper.copyBinary((ByteBuffer) o); } else if (o instanceof List) { - return deepCopyList((List)o); + return deepCopyList((List) o); } else if (o instanceof Set) { - return deepCopySet((Set)o); + return deepCopySet((Set) o); } else if (o instanceof Map) { - return deepCopyMap((Map)o); + return deepCopyMap((Map) o); } else { return o; } @@ -112,14 +115,18 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl public Object getFieldValue(F fieldId) { if (fieldId != setField_) { - throw new IllegalArgumentException("Cannot get the value of field " + fieldId + " because union's set field is " + setField_); + throw new IllegalArgumentException( + "Cannot get the value of field " + + fieldId + + " because union's set field is " + + setField_); } return getFieldValue(); } public Object getFieldValue(int fieldId) { - return getFieldValue(enumForId((short)fieldId)); + return getFieldValue(enumForId((short) fieldId)); } public boolean isSet() { @@ -131,7 +138,7 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl } public boolean isSet(int fieldId) { - return isSet(enumForId((short)fieldId)); + return isSet(enumForId((short) fieldId)); } public void read(TProtocol iprot) throws TException { @@ -145,7 +152,7 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl } public void setFieldValue(int fieldId, Object value) { - setFieldValue(enumForId((short)fieldId), value); + setFieldValue(enumForId((short) fieldId), value); } public void write(TProtocol oprot) throws TException { @@ -153,8 +160,8 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl } /** - * Implementation should be generated so that we can efficiently type check - * various values. + * Implementation should be generated so that we can efficiently type check various values. + * * @param setField the field to assign value to. * @param value the value to be assigned to setField. * @throws ClassCastException if the type of value is incompatible with the type of setField. @@ -162,18 +169,21 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl protected abstract void checkType(F setField, Object value) throws ClassCastException; /** - * Implementation should be generated to read the right stuff from the wire - * based on the field header. + * Implementation should be generated to read the right stuff from the wire based on the field + * header. * * @param iprot input protocol from which to read a value. * @param field the field whose value is to be read from iprot. * @return read Object based on the field header, as specified by the argument. * @throws TException on error during read. */ - protected abstract Object standardSchemeReadValue(TProtocol iprot, TField field) throws TException; + protected abstract Object standardSchemeReadValue(TProtocol iprot, TField field) + throws TException; + protected abstract void standardSchemeWriteValue(TProtocol oprot) throws TException; protected abstract Object tupleSchemeReadValue(TProtocol iprot, short fieldID) throws TException; + protected abstract void tupleSchemeWriteValue(TProtocol oprot) throws TException; protected abstract TStruct getStructDesc(); @@ -193,8 +203,8 @@ public abstract class TUnion<T extends TUnion<T,F>, F extends TFieldIdEnum> impl Object v = getFieldValue(); sb.append(getFieldDesc(getSetField()).name); sb.append(":"); - if(v instanceof ByteBuffer) { - TBaseHelper.toString((ByteBuffer)v, sb); + if (v instanceof ByteBuffer) { + TBaseHelper.toString((ByteBuffer) v, sb); } else { sb.append(v.toString()); } diff --git a/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java b/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java index a34b01ebb..55d4608ed 100644 --- a/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java +++ b/lib/java/src/main/java/org/apache/thrift/annotation/Nullable.java @@ -19,15 +19,12 @@ package org.apache.thrift.annotation; -import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** - * Annotation indicating a field, method return, or method parameter may be {@code null}. - * We package our own annotation to avoid a mandatory third-party dependency. + * Annotation indicating a field, method return, or method parameter may be {@code null}. We package + * our own annotation to avoid a mandatory third-party dependency. */ @Retention(RetentionPolicy.CLASS) -public @interface Nullable { - -} +public @interface Nullable {} diff --git a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java index 4ebde0741..3939bc227 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java +++ b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodCallback.java @@ -19,33 +19,29 @@ package org.apache.thrift.async; /** - * A handler interface asynchronous clients can implement to receive future - * notice of the results of an asynchronous method call. + * A handler interface asynchronous clients can implement to receive future notice of the results of + * an asynchronous method call. * * @param <T> The return type of the asynchronously invoked method. */ public interface AsyncMethodCallback<T> { /** - * This method will be called when the remote side has completed invoking - * your method call and the result is fully read. For {@code oneway} method - * calls, this method will be called as soon as we have completed writing out - * the request. + * This method will be called when the remote side has completed invoking your method call and the + * result is fully read. For {@code oneway} method calls, this method will be called as soon as we + * have completed writing out the request. * - * @param response The return value of the asynchronously invoked method; - * {@code null} for void methods which includes - * {@code oneway} methods. + * @param response The return value of the asynchronously invoked method; {@code null} for void + * methods which includes {@code oneway} methods. */ void onComplete(T response); /** - * This method will be called when there is either an unexpected client-side - * exception like an IOException or else when the remote method raises an - * exception, either declared in the IDL or due to an unexpected server-side - * error. + * This method will be called when there is either an unexpected client-side exception like an + * IOException or else when the remote method raises an exception, either declared in the IDL or + * due to an unexpected server-side error. * - * @param exception The exception encountered processing the the asynchronous - * method call, may be a local exception or an unmarshalled - * remote exception. + * @param exception The exception encountered processing the the asynchronous method call, may be + * a local exception or an unmarshalled remote exception. */ void onError(Exception exception); } diff --git a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java index 0bee3a7cf..202af7bff 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java +++ b/lib/java/src/main/java/org/apache/thrift/async/AsyncMethodFutureAdapter.java @@ -3,33 +3,33 @@ package org.apache.thrift.async; import java.util.concurrent.CompletableFuture; /** - * A simple adapter that bridges {@link AsyncMethodCallback} with {@link CompletableFuture}-returning style clients. - * Compiler generated code will invoke this adapter to implement {@code FutureClient}s. + * A simple adapter that bridges {@link AsyncMethodCallback} with {@link + * CompletableFuture}-returning style clients. Compiler generated code will invoke this adapter to + * implement {@code FutureClient}s. * * @param <T> return type (can be {@link Void}). */ public final class AsyncMethodFutureAdapter<T> implements AsyncMethodCallback<T> { - private AsyncMethodFutureAdapter() { - } + private AsyncMethodFutureAdapter() {} - public static <T> AsyncMethodFutureAdapter<T> create() { - return new AsyncMethodFutureAdapter<>(); - } + public static <T> AsyncMethodFutureAdapter<T> create() { + return new AsyncMethodFutureAdapter<>(); + } - private final CompletableFuture<T> future = new CompletableFuture<>(); + private final CompletableFuture<T> future = new CompletableFuture<>(); - public CompletableFuture<T> getFuture() { - return future; - } + public CompletableFuture<T> getFuture() { + return future; + } - @Override - public void onComplete(T response) { - future.complete(response); - } + @Override + public void onComplete(T response) { + future.complete(response); + } - @Override - public void onError(Exception exception) { - future.completeExceptionally(exception); - } + @Override + public void onError(Exception exception) { + future.completeExceptionally(exception); + } } diff --git a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java index 8ba135642..06d6f6382 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java +++ b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClient.java @@ -29,11 +29,18 @@ public abstract class TAsyncClient { private Exception ___error; private long ___timeout; - public TAsyncClient(TProtocolFactory protocolFactory, TAsyncClientManager manager, TNonblockingTransport transport) { + public TAsyncClient( + TProtocolFactory protocolFactory, + TAsyncClientManager manager, + TNonblockingTransport transport) { this(protocolFactory, manager, transport, 0); } - public TAsyncClient(TProtocolFactory protocolFactory, TAsyncClientManager manager, TNonblockingTransport transport, long timeout) { + public TAsyncClient( + TProtocolFactory protocolFactory, + TAsyncClientManager manager, + TNonblockingTransport transport, + long timeout) { this.___protocolFactory = protocolFactory; this.___manager = manager; this.___transport = transport; @@ -58,6 +65,7 @@ public abstract class TAsyncClient { /** * Is the client in an error state? + * * @return If client in an error state? */ public boolean hasError() { @@ -66,7 +74,9 @@ public abstract class TAsyncClient { /** * Get the client's error - returns null if no error - * @return Get the client's error. <p> returns null if no error + * + * @return Get the client's error. + * <p>returns null if no error */ public Exception getError() { return ___error; @@ -75,7 +85,8 @@ public abstract class TAsyncClient { protected void checkReady() { // Ensure we are not currently executing a method if (___currentMethod != null) { - throw new IllegalStateException("Client is currently executing another method: " + ___currentMethod.getClass().getName()); + throw new IllegalStateException( + "Client is currently executing another method: " + ___currentMethod.getClass().getName()); } // Ensure we're not in an error state @@ -84,9 +95,7 @@ public abstract class TAsyncClient { } } - /** - * Called by delegate method when finished - */ + /** Called by delegate method when finished */ protected void onComplete() { ___currentMethod = null; } diff --git a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java index c07ccd540..ba6a5fd2e 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java +++ b/lib/java/src/main/java/org/apache/thrift/async/TAsyncClientManager.java @@ -29,19 +29,17 @@ import java.util.Iterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeoutException; - import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Contains selector thread which transitions method call objects - */ +/** Contains selector thread which transitions method call objects */ public class TAsyncClientManager { private static final Logger LOGGER = LoggerFactory.getLogger(TAsyncClientManager.class.getName()); private final SelectThread selectThread; - private final ConcurrentLinkedQueue<TAsyncMethodCall> pendingCalls = new ConcurrentLinkedQueue<TAsyncMethodCall>(); + private final ConcurrentLinkedQueue<TAsyncMethodCall> pendingCalls = + new ConcurrentLinkedQueue<TAsyncMethodCall>(); public TAsyncClientManager() throws IOException { this.selectThread = new SelectThread(); @@ -68,7 +66,8 @@ public class TAsyncClientManager { private class SelectThread extends Thread { private final Selector selector; private volatile boolean running; - private final TreeSet<TAsyncMethodCall> timeoutWatchSet = new TreeSet<TAsyncMethodCall>(new TAsyncMethodCallTimeoutComparator()); + private final TreeSet<TAsyncMethodCall> timeoutWatchSet = + new TreeSet<TAsyncMethodCall>(new TAsyncMethodCallTimeoutComparator()); public SelectThread() throws IOException { this.selector = SelectorProvider.provider().openSelector(); @@ -96,7 +95,8 @@ public class TAsyncClientManager { // No timeouts, so select indefinitely selector.select(); } else { - // We have a timeout pending, so calculate the time until then and select appropriately + // We have a timeout pending, so calculate the time until then and select + // appropriately long nextTimeout = timeoutWatchSet.first().getTimeoutTimestamp(); long selectTime = nextTimeout - System.currentTimeMillis(); if (selectTime > 0) { @@ -139,7 +139,7 @@ public class TAsyncClientManager { // just skip continue; } - TAsyncMethodCall methodCall = (TAsyncMethodCall)key.attachment(); + TAsyncMethodCall methodCall = (TAsyncMethodCall) key.attachment(); methodCall.transition(key); // If done or error occurred, remove from timeout watch set @@ -160,7 +160,13 @@ public class TAsyncClientManager { TAsyncMethodCall methodCall = iterator.next(); if (currentTime >= methodCall.getTimeoutTimestamp()) { iterator.remove(); - methodCall.onError(new TimeoutException("Operation " + methodCall.getClass() + " timed out after " + (currentTime - methodCall.getStartTime()) + " ms.")); + methodCall.onError( + new TimeoutException( + "Operation " + + methodCall.getClass() + + " timed out after " + + (currentTime - methodCall.getStartTime()) + + " ms.")); } else { break; } @@ -189,12 +195,13 @@ public class TAsyncClientManager { } /** Comparator used in TreeSet */ - private static class TAsyncMethodCallTimeoutComparator implements Comparator<TAsyncMethodCall>, Serializable { + private static class TAsyncMethodCallTimeoutComparator + implements Comparator<TAsyncMethodCall>, Serializable { public int compare(TAsyncMethodCall left, TAsyncMethodCall right) { if (left.getTimeoutTimestamp() == right.getTimeoutTimestamp()) { - return (int)(left.getSequenceId() - right.getSequenceId()); + return (int) (left.getSequenceId() - right.getSequenceId()); } else { - return (int)(left.getTimeoutTimestamp() - right.getTimeoutTimestamp()); + return (int) (left.getTimeoutTimestamp() - right.getTimeoutTimestamp()); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java b/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java index a119f23e0..df586b4ec 100644 --- a/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java +++ b/lib/java/src/main/java/org/apache/thrift/async/TAsyncMethodCall.java @@ -23,22 +23,22 @@ import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.concurrent.atomic.AtomicLong; - import org.apache.thrift.TException; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; -import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.TMemoryBuffer; import org.apache.thrift.transport.TNonblockingTransport; import org.apache.thrift.transport.TTransportException; +import org.apache.thrift.transport.layered.TFramedTransport; /** * Encapsulates an async method call. - * <p> - * Need to generate: + * + * <p>Need to generate: + * * <ul> - * <li>protected abstract void write_args(TProtocol protocol)</li> - * <li>protected abstract T getResult() throws <Exception_1>, <Exception_2>, ...</li> + * <li>protected abstract void write_args(TProtocol protocol) + * <li>protected abstract T getResult() throws <Exception_1>, <Exception_2>, ... * </ul> * * @param <T> The return type of the encapsulated method call. @@ -58,9 +58,7 @@ public abstract class TAsyncMethodCall<T> { ERROR; } - /** - * Next step in the call, initialized by start() - */ + /** Next step in the call, initialized by start() */ private State state = null; protected final TNonblockingTransport transport; @@ -77,7 +75,12 @@ public abstract class TAsyncMethodCall<T> { private long startTime = System.currentTimeMillis(); - protected TAsyncMethodCall(TAsyncClient client, TProtocolFactory protocolFactory, TNonblockingTransport transport, AsyncMethodCallback<T> callback, boolean isOneway) { + protected TAsyncMethodCall( + TAsyncClient client, + TProtocolFactory protocolFactory, + TNonblockingTransport transport, + AsyncMethodCallback<T> callback, + boolean isOneway) { this.transport = transport; this.callback = callback; this.protocolFactory = protocolFactory; @@ -121,6 +124,7 @@ public abstract class TAsyncMethodCall<T> { /** * Initialize buffers. + * * @throws TException if buffer initialization fails */ protected void prepareMethodCall() throws TException { @@ -137,6 +141,7 @@ public abstract class TAsyncMethodCall<T> { /** * Register with selector and start first state, which could be either connecting or writing. + * * @throws IOException if register or starting fails */ void start(Selector sel) throws IOException { @@ -168,9 +173,10 @@ public abstract class TAsyncMethodCall<T> { } /** - * Transition to next state, doing whatever work is required. Since this - * method is only called by the selector thread, we can make changes to our - * select interests without worrying about concurrency. + * Transition to next state, doing whatever work is required. Since this method is only called by + * the selector thread, we can make changes to our select interests without worrying about + * concurrency. + * * @param key */ void transition(SelectionKey key) { @@ -201,8 +207,10 @@ public abstract class TAsyncMethodCall<T> { doReadingResponseBody(key); break; default: // RESPONSE_READ, ERROR, or bug - throw new IllegalStateException("Method call in state " + state - + " but selector called transition method. Seems like a bug..."); + throw new IllegalStateException( + "Method call in state " + + state + + " but selector called transition method. Seems like a bug..."); } } catch (Exception e) { key.cancel(); @@ -260,7 +268,7 @@ public abstract class TAsyncMethodCall<T> { cleanUpAndFireCallback(key); } else { state = State.READING_RESPONSE_SIZE; - sizeBuffer.rewind(); // Prepare to read incoming frame size + sizeBuffer.rewind(); // Prepare to read incoming frame size key.interestOps(SelectionKey.OP_READ); } } @@ -268,7 +276,8 @@ public abstract class TAsyncMethodCall<T> { private void doWritingRequestSize() throws TTransportException { if (transport.write(sizeBuffer) < 0) { - throw new TTransportException(TTransportException.END_OF_FILE, "Write call frame size failed"); + throw new TTransportException( + TTransportException.END_OF_FILE, "Write call frame size failed"); } if (sizeBuffer.remaining() == 0) { state = State.WRITING_REQUEST_BODY; @@ -277,7 +286,8 @@ public abstract class TAsyncMethodCall<T> { private void doConnecting(SelectionKey key) throws IOException { if (!key.isConnectable() || !transport.finishConnect()) { - throw new IOException("not connectable or finishConnect returned false after we got an OP_CONNECT"); + throw new IOException( + "not connectable or finishConnect returned false after we got an OP_CONNECT"); } registerForFirstWrite(key); } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java index be49cb949..b6fc11326 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/EnumMetaData.java @@ -23,9 +23,9 @@ import org.apache.thrift.TEnum; public class EnumMetaData extends FieldValueMetaData { public final Class<? extends TEnum> enumClass; - - public EnumMetaData(byte type, Class<? extends TEnum> sClass){ + + public EnumMetaData(byte type, Class<? extends TEnum> sClass) { super(type); this.enumClass = sClass; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java index 5691f83e6..b78919385 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java @@ -19,42 +19,41 @@ package org.apache.thrift.meta_data; -import java.util.AbstractMap; -import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.apache.thrift.TBase; import org.apache.thrift.TFieldIdEnum; /** - * This class is used to store meta data about thrift fields. Every field in a - * a struct should have a corresponding instance of this class describing it. + * This class is used to store meta data about thrift fields. Every field in a a struct should have + * a corresponding instance of this class describing it. * - * The meta data is registered by ALL Thrift struct classes via a static {...} - * initializer block in the generated Thrift code. + * <p>The meta data is registered by ALL Thrift struct classes via a static {...} initializer block + * in the generated Thrift code. * - * Since different threads could be initializing different Thrift classes, calls - * to the public static methods of this class could be racy. + * <p>Since different threads could be initializing different Thrift classes, calls to the public + * static methods of this class could be racy. * - * All methods of this class should be made thread safe. + * <p>All methods of this class should be made thread safe. */ public class FieldMetaData implements java.io.Serializable { public final String fieldName; public final byte requirementType; public final FieldValueMetaData valueMetaData; private final Map<String, String> fieldAnnotations; - private static final Map<Class<? extends TBase>, Map<? extends TFieldIdEnum, FieldMetaData>> structMap = new ConcurrentHashMap<>(); + private static final Map<Class<? extends TBase>, Map<? extends TFieldIdEnum, FieldMetaData>> + structMap = new ConcurrentHashMap<>(); - public FieldMetaData(String name, byte req, FieldValueMetaData vMetaData){ + public FieldMetaData(String name, byte req, FieldValueMetaData vMetaData) { this(name, req, vMetaData, Collections.emptyMap()); } - public FieldMetaData(String fieldName, byte requirementType, FieldValueMetaData valueMetaData, Map<String, String> fieldAnnotations) { + public FieldMetaData( + String fieldName, + byte requirementType, + FieldValueMetaData valueMetaData, + Map<String, String> fieldAnnotations) { this.fieldName = fieldName; this.requirementType = requirementType; this.valueMetaData = valueMetaData; @@ -62,26 +61,26 @@ public class FieldMetaData implements java.io.Serializable { } /** - * @return an unmodifiable view of the annotations for this field, empty if no annotations present or code gen param - * is not turned on + * @return an unmodifiable view of the annotations for this field, empty if no annotations present + * or code gen param is not turned on */ public Map<String, String> getFieldAnnotations() { return Collections.unmodifiableMap(fieldAnnotations); } - public static void addStructMetaDataMap(Class<? extends TBase> sClass, Map<? extends TFieldIdEnum, FieldMetaData> map){ + public static void addStructMetaDataMap( + Class<? extends TBase> sClass, Map<? extends TFieldIdEnum, FieldMetaData> map) { structMap.put(sClass, map); } /** - * Returns a map with metadata (i.e. instances of FieldMetaData) that - * describe the fields of the given class. + * Returns a map with metadata (i.e. instances of FieldMetaData) that describe the fields of the + * given class. * - * @param sClass The TBase class for which the metadata map is requested. It is not - * guaranteed that sClass will have been statically initialized before - * this method is called. A racy call to - * {@link FieldMetaData#addStructMetaDataMap(Class, Map)} from a different - * thread during static initialization of the Thrift class is possible. + * @param sClass The TBase class for which the metadata map is requested. It is not guaranteed + * that sClass will have been statically initialized before this method is called. A racy call + * to {@link FieldMetaData#addStructMetaDataMap(Class, Map)} from a different thread during + * static initialization of the Thrift class is possible. */ public static Map<? extends TFieldIdEnum, FieldMetaData> getStructMetaDataMap( Class<? extends TBase> sClass) { @@ -89,13 +88,21 @@ public class FieldMetaData implements java.io.Serializable { // Similarly, do not trigger sClass.newInstance() while holding a lock on structMap, // it will lead to the same deadlock. // See: https://issues.apache.org/jira/browse/THRIFT-5430 for details. - if (!structMap.containsKey(sClass)){ // Load class if it hasn't been loaded - try{ + if (!structMap.containsKey(sClass)) { // Load class if it hasn't been loaded + try { sClass.newInstance(); - } catch (InstantiationException e){ - throw new RuntimeException("InstantiationException for TBase class: " + sClass.getName() + ", message: " + e.getMessage()); - } catch (IllegalAccessException e){ - throw new RuntimeException("IllegalAccessException for TBase class: " + sClass.getName() + ", message: " + e.getMessage()); + } catch (InstantiationException e) { + throw new RuntimeException( + "InstantiationException for TBase class: " + + sClass.getName() + + ", message: " + + e.getMessage()); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "IllegalAccessException for TBase class: " + + sClass.getName() + + ", message: " + + e.getMessage()); } } return structMap.get(sClass); diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java index 2180b089b..d022e11bb 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/FieldValueMetaData.java @@ -22,11 +22,10 @@ package org.apache.thrift.meta_data; import org.apache.thrift.protocol.TType; /** - * FieldValueMetaData and collection of subclasses to store metadata about - * the value(s) of a field + * FieldValueMetaData and collection of subclasses to store metadata about the value(s) of a field */ public class FieldValueMetaData implements java.io.Serializable { - public final byte type; + public final byte type; private final boolean isTypedefType; private final String typedefName; @@ -59,7 +58,7 @@ public class FieldValueMetaData implements java.io.Serializable { } public boolean isStruct() { - return type == TType.STRUCT; + return type == TType.STRUCT; } public boolean isContainer() { diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java index 8e7073bf5..e87e97a73 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/ListMetaData.java @@ -21,9 +21,9 @@ package org.apache.thrift.meta_data; public class ListMetaData extends FieldValueMetaData { public final FieldValueMetaData elemMetaData; - - public ListMetaData(byte type, FieldValueMetaData eMetaData){ + + public ListMetaData(byte type, FieldValueMetaData eMetaData) { super(type); this.elemMetaData = eMetaData; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java index e7c408c78..692a372ec 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/MapMetaData.java @@ -22,10 +22,10 @@ package org.apache.thrift.meta_data; public class MapMetaData extends FieldValueMetaData { public final FieldValueMetaData keyMetaData; public final FieldValueMetaData valueMetaData; - - public MapMetaData(byte type, FieldValueMetaData kMetaData, FieldValueMetaData vMetaData){ + + public MapMetaData(byte type, FieldValueMetaData kMetaData, FieldValueMetaData vMetaData) { super(type); this.keyMetaData = kMetaData; this.valueMetaData = vMetaData; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java index cf4b96aab..3f2b1e20d 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/SetMetaData.java @@ -21,9 +21,9 @@ package org.apache.thrift.meta_data; public class SetMetaData extends FieldValueMetaData { public final FieldValueMetaData elemMetaData; - - public SetMetaData(byte type, FieldValueMetaData eMetaData){ + + public SetMetaData(byte type, FieldValueMetaData eMetaData) { super(type); this.elemMetaData = eMetaData; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java b/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java index b37d21dab..98d734179 100644 --- a/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java +++ b/lib/java/src/main/java/org/apache/thrift/meta_data/StructMetaData.java @@ -23,9 +23,9 @@ import org.apache.thrift.TBase; public class StructMetaData extends FieldValueMetaData { public final Class<? extends TBase> structClass; - - public StructMetaData(byte type, Class<? extends TBase> sClass){ + + public StructMetaData(byte type, Class<? extends TBase> sClass) { super(type); this.structClass = sClass; - } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java b/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java index 22423f10c..a56d20286 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/EnumCache.java @@ -19,22 +19,19 @@ package org.apache.thrift.partial; -import org.apache.thrift.partial.Validate; - -import org.apache.thrift.TEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import org.apache.thrift.TEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Provides a memoized way to lookup an enum by its value. * - * This class is used internally by {@code TDeserializer}. - * It is not intended to be used separately on its own. + * <p>This class is used internally by {@code TDeserializer}. It is not intended to be used + * separately on its own. */ public class EnumCache { private static Logger LOG = LoggerFactory.getLogger(EnumCache.class); @@ -46,8 +43,7 @@ public class EnumCache { } /** - * Gets an instance of the enum type {@code enumClass} - * corresponding to the given {@code value}. + * Gets an instance of the enum type {@code enumClass} corresponding to the given {@code value}. * * @param enumClass class of the enum to be returned. * @param value value returned by {@code getValue()}. diff --git a/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java b/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java index f636c80d9..e635dc643 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java @@ -19,26 +19,23 @@ package org.apache.thrift.partial; -import org.apache.thrift.TBase; -import org.apache.thrift.protocol.TType; - -import java.lang.StringBuilder; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.thrift.TBase; +import org.apache.thrift.protocol.TType; /** - * Enables comparison of two TBase instances such that the comparison - * is limited to the subset of fields defined by the supplied metadata. + * Enables comparison of two TBase instances such that the comparison is limited to the subset of + * fields defined by the supplied metadata. * - * This comparer is useful when comparing two instances where: - * -- one is generated by full deserialization. - * -- the other is generated by partial deserialization. + * <p>This comparer is useful when comparing two instances where: -- one is generated by full + * deserialization. -- the other is generated by partial deserialization. * - * The typical use case is to establish correctness of partial deserialization. + * <p>The typical use case is to establish correctness of partial deserialization. */ public class PartialThriftComparer<T extends TBase> { @@ -61,12 +58,12 @@ public class PartialThriftComparer<T extends TBase> { } /** - * Compares thrift objects {@code t1} and {@code t2} and - * returns true if they are equal false otherwise. The comparison is limited - * to the scope defined by {@code metadata}. - * <p> - * If the objects are not equal then it optionally records their differences - * if {@code sb} is supplied. + * Compares thrift objects {@code t1} and {@code t2} and returns true if they are equal false + * otherwise. The comparison is limited to the scope defined by {@code metadata}. + * + * <p>If the objects are not equal then it optionally records their differences if {@code sb} is + * supplied. + * * <p> * * @param t1 the first object. @@ -79,10 +76,7 @@ public class PartialThriftComparer<T extends TBase> { } private boolean areEqual( - ThriftMetadata.ThriftObject data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftObject data, Object o1, Object o2, StringBuilder sb) { byte fieldType = data.data.valueMetaData.type; switch (fieldType) { @@ -116,10 +110,7 @@ public class PartialThriftComparer<T extends TBase> { } private boolean areEqual( - ThriftMetadata.ThriftStruct data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftStruct data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; @@ -151,10 +142,7 @@ public class PartialThriftComparer<T extends TBase> { } private boolean areEqual( - ThriftMetadata.ThriftPrimitive data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftPrimitive data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { @@ -173,11 +161,7 @@ public class PartialThriftComparer<T extends TBase> { return false; } - private boolean areEqual( - ThriftMetadata.ThriftEnum data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftEnum data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { @@ -192,11 +176,7 @@ public class PartialThriftComparer<T extends TBase> { return false; } - private boolean areEqual( - ThriftMetadata.ThriftList data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftList data, Object o1, Object o2, StringBuilder sb) { List<Object> l1 = (List<Object>) o1; List<Object> l2 = (List<Object>) o2; @@ -221,11 +201,7 @@ public class PartialThriftComparer<T extends TBase> { return true; } - private boolean areEqual( - ThriftMetadata.ThriftSet data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftSet data, Object o1, Object o2, StringBuilder sb) { Set<Object> s1 = (Set<Object>) o1; Set<Object> s2 = (Set<Object>) o2; @@ -249,11 +225,7 @@ public class PartialThriftComparer<T extends TBase> { return true; } - private boolean areEqual( - ThriftMetadata.ThriftMap data, - Object o1, - Object o2, - StringBuilder sb) { + private boolean areEqual(ThriftMetadata.ThriftMap data, Object o1, Object o2, StringBuilder sb) { Map<Object, Object> m1 = (Map<Object, Object>) o1; Map<Object, Object> m2 = (Map<Object, Object>) o2; @@ -303,10 +275,7 @@ public class PartialThriftComparer<T extends TBase> { } private void appendResult( - ThriftMetadata.ThriftObject data, - StringBuilder sb, - String format, - Object... args) { + ThriftMetadata.ThriftObject data, StringBuilder sb, String format, Object... args) { if (sb != null) { String msg = String.format(format, args); sb.append(data.fieldId.getFieldName()); @@ -330,16 +299,12 @@ public class PartialThriftComparer<T extends TBase> { appendResult(data, sb, "%s (%s) != %s (%s)", o1name, o1s, o2name, o2s); } else { appendResult( - data, sb, "%s != %s\n%s =\n%s\n%s =\n%s\n", - o1name, o2name, o1name, o1s, o2name, o2s); + data, sb, "%s != %s\n%s =\n%s\n%s =\n%s\n", o1name, o2name, o1name, o1s, o2name, o2s); } } private ComparisonResult checkNullEquality( - ThriftMetadata.ThriftObject data, - Object o1, - Object o2, - StringBuilder sb) { + ThriftMetadata.ThriftObject data, Object o1, Object o2, StringBuilder sb) { if ((o1 == null) && (o2 == null)) { return ComparisonResult.EQUAL; } @@ -364,8 +329,7 @@ public class PartialThriftComparer<T extends TBase> { if (c1.size() != c2.size()) { appendResult( - data, sb, "%s1.size(%d) != %s2.size(%d)", - typeName, c1.size(), typeName, c2.size()); + data, sb, "%s1.size(%d) != %s2.size(%d)", typeName, c1.size(), typeName, c2.size()); return false; } diff --git a/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java b/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java index d77302e48..5119259f9 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/TFieldData.java @@ -22,8 +22,8 @@ package org.apache.thrift.partial; /** * Holds the type and id members of a {@link org.apache.thrift.protocol.TField} into a single int. * - * This encoding scheme obviates the need to instantiate TField - * during the partial deserialization process. + * <p>This encoding scheme obviates the need to instantiate TField during the partial + * deserialization process. */ public class TFieldData { public static int encode(byte type) { diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java index 1b5a08c80..a0fbda6a6 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftField.java @@ -19,8 +19,6 @@ package org.apache.thrift.partial; -import org.apache.thrift.partial.Validate; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -28,21 +26,19 @@ import java.util.List; /** * Holds name of a thrift field and of its sub-fields recursively. - * <p> - * This class is meant to be used in conjunction with {@code TDeserializer}. + * + * <p>This class is meant to be used in conjunction with {@code TDeserializer}. */ public class ThriftField { - /** - * Name of this field as it appears in a thrift file. Case sensitive. - */ + /** Name of this field as it appears in a thrift file. Case sensitive. */ public final String name; /** * List of sub-fields of this field. * - * This list should have only those sub-fields that need to be deserialized - * by the {@code TDeserializer}. + * <p>This list should have only those sub-fields that need to be deserialized by the {@code + * TDeserializer}. */ public final List<ThriftField> fields; @@ -60,9 +56,7 @@ public class ThriftField { this.fields = Collections.unmodifiableList(fields); } - /** - * Constructs a {@link ThriftField} that does not have any sub-fields. - */ + /** Constructs a {@link ThriftField} that does not have any sub-fields. */ ThriftField(String name) { this(name, Collections.emptyList()); } @@ -146,15 +140,12 @@ public class ThriftField { /** * Generates and returns n-ary tree of fields and their sub-fields. - * <p> - * @param fieldNames collection of fully qualified field names. * - * for example, - * In case of PinJoin thrift struct, the following are valid field names - * -- signature - * -- pins.user.userId - * -- textSignal.termSignal.termDataMap + * <p> * + * @param fieldNames collection of fully qualified field names. + * <p>for example, In case of PinJoin thrift struct, the following are valid field names -- + * signature -- pins.user.userId -- textSignal.termSignal.termDataMap * @return n-ary tree of fields and their sub-fields. */ public static List<ThriftField> fromNames(Collection<String> fieldNames) { diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java index 33982d1d2..edb106c15 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftFieldValueProcessor.java @@ -19,18 +19,17 @@ package org.apache.thrift.partial; +import java.nio.ByteBuffer; import org.apache.thrift.TEnum; import org.apache.thrift.TFieldIdEnum; -import java.nio.ByteBuffer; - /** - * Provides an abstraction to process deserialized field values and place them - * into the collection that holds them. This abstraction allows different types - * of collections to be output from partial deserialization. + * Provides an abstraction to process deserialized field values and place them into the collection + * that holds them. This abstraction allows different types of collections to be output from partial + * deserialization. * - * In case of the usual Thrift deserialization, the collection that holds field - * values is simply an instance of TBase. + * <p>In case of the usual Thrift deserialization, the collection that holds field values is simply + * an instance of TBase. */ public interface ThriftFieldValueProcessor<V> { @@ -39,15 +38,15 @@ public interface ThriftFieldValueProcessor<V> { V prepareStruct(Object instance); - void setBool(V valueCollection, TFieldIdEnum fieldId, boolean value); + void setBool(V valueCollection, TFieldIdEnum fieldId, boolean value); - void setByte(V valueCollection, TFieldIdEnum fieldId, byte value); + void setByte(V valueCollection, TFieldIdEnum fieldId, byte value); - void setInt16(V valueCollection, TFieldIdEnum fieldId, short value); + void setInt16(V valueCollection, TFieldIdEnum fieldId, short value); - void setInt32(V valueCollection, TFieldIdEnum fieldId, int value); + void setInt32(V valueCollection, TFieldIdEnum fieldId, int value); - void setInt64(V valueCollection, TFieldIdEnum fieldId, long value); + void setInt64(V valueCollection, TFieldIdEnum fieldId, long value); void setDouble(V valueCollection, TFieldIdEnum fieldId, double value); diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java index 46a37f2d9..69f76cff6 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java @@ -19,6 +19,14 @@ package org.apache.thrift.partial; +import java.io.Serializable; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.thrift.TBase; import org.apache.thrift.TFieldIdEnum; @@ -31,20 +39,10 @@ import org.apache.thrift.meta_data.SetMetaData; import org.apache.thrift.meta_data.StructMetaData; import org.apache.thrift.protocol.TType; -import java.io.Serializable; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** - * Container for Thrift metadata classes such as {@link ThriftPrimitive}, - * {@link ThriftList}, etc. - * <p> - * This class is mainly used by {@code TDeserializer}. + * Container for Thrift metadata classes such as {@link ThriftPrimitive}, {@link ThriftList}, etc. + * + * <p>This class is mainly used by {@code TDeserializer}. */ public class ThriftMetadata { @@ -84,9 +82,8 @@ public class ThriftMetadata { /** * Base class of field types that can be partially deserialized. * - * Holds metadata necessary for partial deserialization. - * The metadata is internally computed and used; therefore it is not visible to - * the users of {@code TDeserializer}. + * <p>Holds metadata necessary for partial deserialization. The metadata is internally computed + * and used; therefore it is not visible to the users of {@code TDeserializer}. */ public abstract static class ThriftObject implements Serializable { public final ThriftObject parent; @@ -111,23 +108,17 @@ public class ThriftMetadata { */ protected abstract void toPrettyString(StringBuilder sb, int level); - /** - * Gets a space string whose length is proportional to the given indent level. - */ + /** Gets a space string whose length is proportional to the given indent level. */ protected String getIndent(int level) { return StringUtils.repeat(" ", level * 4); } - /** - * Helper method to append a formatted string to the given {@code StringBuilder}. - */ + /** Helper method to append a formatted string to the given {@code StringBuilder}. */ protected void append(StringBuilder sb, String format, Object... args) { sb.append(String.format(format, args)); } - /** - * Gets the name of this field. - */ + /** Gets the name of this field. */ protected String getName() { return this.fieldId.getFieldName(); } @@ -145,10 +136,7 @@ public class ThriftMetadata { private static class Factory { static ThriftObject createNew( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { byte fieldType = data.valueMetaData.type; switch (fieldType) { @@ -183,9 +171,7 @@ public class ThriftMetadata { } } - /** - * Metadata about primitive types. - */ + /** Metadata about primitive types. */ public static class ThriftPrimitive extends ThriftObject { ThriftPrimitive(ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data) { super(parent, fieldId, data); @@ -248,15 +234,10 @@ public class ThriftMetadata { } } - /** - * Metadata of container like objects: list, set, map - */ + /** Metadata of container like objects: list, set, map */ public abstract static class ThriftContainer extends ThriftObject { - public ThriftContainer( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data) { + public ThriftContainer(ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data) { super(parent, fieldId, data); } @@ -267,20 +248,18 @@ public class ThriftMetadata { public final ThriftObject elementData; ThriftList( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { super(parent, fieldId, data); - this.elementData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.LIST_ELEMENT, - new FieldMetaData( - getSubElementName(fieldId), - TFieldRequirementType.REQUIRED, - ((ListMetaData) data.valueMetaData).elemMetaData), - fields); + this.elementData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.LIST_ELEMENT, + new FieldMetaData( + getSubElementName(fieldId), + TFieldRequirementType.REQUIRED, + ((ListMetaData) data.valueMetaData).elemMetaData), + fields); } @Override @@ -300,20 +279,18 @@ public class ThriftMetadata { public final ThriftObject elementData; ThriftSet( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { super(parent, fieldId, data); - this.elementData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.SET_ELEMENT, - new FieldMetaData( - getSubElementName(fieldId), - TFieldRequirementType.REQUIRED, - ((SetMetaData) data.valueMetaData).elemMetaData), - fields); + this.elementData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.SET_ELEMENT, + new FieldMetaData( + getSubElementName(fieldId), + TFieldRequirementType.REQUIRED, + ((SetMetaData) data.valueMetaData).elemMetaData), + fields); } @Override @@ -334,29 +311,28 @@ public class ThriftMetadata { public final ThriftObject valueData; ThriftMap( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data, - List<ThriftField> fields) { + ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { super(parent, fieldId, data); - this.keyData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.MAP_KEY, - new FieldMetaData( - getSubElementName(fieldId, "key"), - TFieldRequirementType.REQUIRED, - ((MapMetaData) data.valueMetaData).keyMetaData), - Collections.emptyList()); - - this.valueData = ThriftObject.Factory.createNew( - this, - FieldTypeEnum.MAP_VALUE, - new FieldMetaData( - getSubElementName(fieldId, "value"), - TFieldRequirementType.REQUIRED, - ((MapMetaData) data.valueMetaData).valueMetaData), - fields); + this.keyData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.MAP_KEY, + new FieldMetaData( + getSubElementName(fieldId, "key"), + TFieldRequirementType.REQUIRED, + ((MapMetaData) data.valueMetaData).keyMetaData), + Collections.emptyList()); + + this.valueData = + ThriftObject.Factory.createNew( + this, + FieldTypeEnum.MAP_VALUE, + new FieldMetaData( + getSubElementName(fieldId, "value"), + TFieldRequirementType.REQUIRED, + ((MapMetaData) data.valueMetaData).valueMetaData), + fields); } @Override @@ -378,14 +354,11 @@ public class ThriftMetadata { } /** - * Base class for metadata of ThriftStruct and ThriftUnion. - * Holds functionality that is common to both. + * Base class for metadata of ThriftStruct and ThriftUnion. Holds functionality that is common to + * both. */ public abstract static class ThriftStructBase<U extends TBase> extends ThriftObject { - public ThriftStructBase( - ThriftObject parent, - TFieldIdEnum fieldId, - FieldMetaData data) { + public ThriftStructBase(ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data) { super(parent, fieldId, data); } @@ -419,10 +392,7 @@ public class ThriftMetadata { } } - /** - * Metadata of a Thrift union. - * Currently not adequately supported. - */ + /** Metadata of a Thrift union. Currently not adequately supported. */ public static class ThriftUnion<U extends TBase> extends ThriftStructBase { public ThriftUnion( ThriftObject parent, @@ -442,9 +412,7 @@ public class ThriftMetadata { } } - /** - * Metadata of a Thrift struct. - */ + /** Metadata of a Thrift struct. */ public static class ThriftStruct<U extends TBase> extends ThriftStructBase { public final Map<Integer, ThriftObject> fields; @@ -474,14 +442,12 @@ public class ThriftMetadata { } public static <T extends TBase> ThriftStruct fromFieldNames( - Class<T> clasz, - Collection<String> fieldNames) { + Class<T> clasz, Collection<String> fieldNames) { return fromFields(clasz, ThriftField.fromNames(fieldNames)); } public static <T extends TBase> ThriftStruct fromFields( - Class<T> clasz, - Iterable<ThriftField> fields) { + Class<T> clasz, Iterable<ThriftField> fields) { Validate.checkNotNull(clasz, "clasz"); Validate.checkNotNull(fields, "fields"); @@ -521,9 +487,7 @@ public class ThriftMetadata { } private static <U extends TBase> Map<Integer, ThriftObject> getFields( - ThriftStruct parent, - Class<U> clasz, - Iterable<ThriftField> fieldsData) { + ThriftStruct parent, Class<U> clasz, Iterable<ThriftField> fieldsData) { Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData = FieldMetaData.getStructMetaDataMap(clasz); @@ -535,7 +499,8 @@ public class ThriftMetadata { TFieldIdEnum fieldId = entry.getKey(); FieldMetaData fieldMetaData = entry.getValue(); ThriftObject field = - ThriftObject.Factory.createNew(parent, fieldId, fieldMetaData, Collections.emptyList()); + ThriftObject.Factory.createNew( + parent, fieldId, fieldMetaData, Collections.emptyList()); fields.put((int) fieldId.getThriftFieldId(), field); } } else { @@ -553,8 +518,7 @@ public class ThriftMetadata { } private static FieldMetaData findFieldMetaData( - Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, - String fieldName) { + Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, String fieldName) { for (FieldMetaData fieldData : fieldsMetaData.values()) { if (fieldData.fieldName.equals(fieldName)) { @@ -566,8 +530,7 @@ public class ThriftMetadata { } private static TFieldIdEnum findFieldId( - Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, - String fieldName) { + Map<? extends TFieldIdEnum, FieldMetaData> fieldsMetaData, String fieldName) { for (TFieldIdEnum fieldId : fieldsMetaData.keySet()) { if (fieldId.getFieldName().equals(fieldName)) { diff --git a/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java b/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java index 95789144d..249e6a256 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/ThriftStructProcessor.java @@ -19,20 +19,19 @@ package org.apache.thrift.partial; -import org.apache.thrift.TBase; -import org.apache.thrift.TEnum; -import org.apache.thrift.TFieldIdEnum; - import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import org.apache.thrift.TBase; +import org.apache.thrift.TEnum; +import org.apache.thrift.TFieldIdEnum; /** * Provides a way to create and initialize an instance of TBase during partial deserialization. * - * This class is supposed to be used as a helper class for {@code PartialThriftDeserializer}. + * <p>This class is supposed to be used as a helper class for {@code PartialThriftDeserializer}. */ public class ThriftStructProcessor implements ThriftFieldValueProcessor<TBase> { @@ -109,27 +108,27 @@ public class ThriftStructProcessor implements ThriftFieldValueProcessor<TBase> { } @Override - public void setBool(TBase valueCollection, TFieldIdEnum fieldId, boolean value) { + public void setBool(TBase valueCollection, TFieldIdEnum fieldId, boolean value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setByte(TBase valueCollection, TFieldIdEnum fieldId, byte value) { + public void setByte(TBase valueCollection, TFieldIdEnum fieldId, byte value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setInt16(TBase valueCollection, TFieldIdEnum fieldId, short value) { + public void setInt16(TBase valueCollection, TFieldIdEnum fieldId, short value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setInt32(TBase valueCollection, TFieldIdEnum fieldId, int value) { + public void setInt32(TBase valueCollection, TFieldIdEnum fieldId, int value) { valueCollection.setFieldValue(fieldId, value); } @Override - public void setInt64(TBase valueCollection, TFieldIdEnum fieldId, long value) { + public void setInt64(TBase valueCollection, TFieldIdEnum fieldId, long value) { valueCollection.setFieldValue(fieldId, value); } diff --git a/lib/java/src/main/java/org/apache/thrift/partial/Validate.java b/lib/java/src/main/java/org/apache/thrift/partial/Validate.java index ef0466a5e..f4bbd9a5a 100644 --- a/lib/java/src/main/java/org/apache/thrift/partial/Validate.java +++ b/lib/java/src/main/java/org/apache/thrift/partial/Validate.java @@ -26,30 +26,24 @@ import java.util.Collection; /** * A superset of Validate class in Apache commons lang3. * - * It provides consistent message strings for frequently encountered checks. - * That simplifies callers because they have to supply only the name of the argument - * that failed a check instead of having to supply the entire message. + * <p>It provides consistent message strings for frequently encountered checks. That simplifies + * callers because they have to supply only the name of the argument that failed a check instead of + * having to supply the entire message. */ public final class Validate { private Validate() {} - /** - * Validates that the given reference argument is not null. - */ + /** Validates that the given reference argument is not null. */ public static void checkNotNull(Object obj, String argName) { checkArgument(obj != null, "'%s' must not be null.", argName); } - /** - * Validates that the given integer argument is not zero or negative. - */ + /** Validates that the given integer argument is not zero or negative. */ public static void checkPositiveInteger(long value, String argName) { checkArgument(value > 0, "'%s' must be a positive integer.", argName); } - /** - * Validates that the given integer argument is not negative. - */ + /** Validates that the given integer argument is not negative. */ public static void checkNotNegative(long value, String argName) { checkArgument(value >= 0, "'%s' must not be negative.", argName); } @@ -61,83 +55,60 @@ public final class Validate { checkArgument(isPresent, "'%s' is required.", argName); } - /** - * Validates that the expression (that checks a field is valid) is true. - */ + /** Validates that the expression (that checks a field is valid) is true. */ public static void checkValid(boolean isValid, String argName) { checkArgument(isValid, "'%s' is invalid.", argName); } - /** - * Validates that the expression (that checks a field is valid) is true. - */ + /** Validates that the expression (that checks a field is valid) is true. */ public static void checkValid(boolean isValid, String argName, String validValues) { checkArgument(isValid, "'%s' is invalid. Valid values are: %s.", argName, validValues); } - /** - * Validates that the given string is not null and has non-zero length. - */ + /** Validates that the given string is not null and has non-zero length. */ public static void checkNotNullAndNotEmpty(String arg, String argName) { Validate.checkNotNull(arg, argName); - Validate.checkArgument( - arg.length() > 0, - "'%s' must not be empty.", - argName); + Validate.checkArgument(arg.length() > 0, "'%s' must not be empty.", argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static <T> void checkNotNullAndNotEmpty(T[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(byte[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(short[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(int[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given array is not null and has at least one element. - */ + /** Validates that the given array is not null and has at least one element. */ public static void checkNotNullAndNotEmpty(long[] array, String argName) { Validate.checkNotNull(array, argName); checkNotEmpty(array.length, argName); } - /** - * Validates that the given buffer is not null and has non-zero capacity. - */ + /** Validates that the given buffer is not null and has non-zero capacity. */ public static <T> void checkNotNullAndNotEmpty(Iterable<T> iter, String argName) { Validate.checkNotNull(iter, argName); int minNumElements = iter.iterator().hasNext() ? 1 : 0; checkNotEmpty(minNumElements, argName); } - /** - * Validates that the given set is not null and has an exact number of items. - */ + /** Validates that the given set is not null and has an exact number of items. */ public static <T> void checkNotNullAndNumberOfElements( Collection<T> collection, int numElements, String argName) { Validate.checkNotNull(collection, argName); @@ -146,18 +117,12 @@ public final class Validate { "Number of elements in '%s' must be exactly %s, %s given.", argName, numElements, - collection.size() - ); + collection.size()); } - /** - * Validates that the given two values are equal. - */ + /** Validates that the given two values are equal. */ public static void checkValuesEqual( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 == value2, "'%s' (%s) must equal '%s' (%s).", @@ -167,14 +132,9 @@ public final class Validate { value2); } - /** - * Validates that the first value is an integer multiple of the second value. - */ + /** Validates that the first value is an integer multiple of the second value. */ public static void checkIntegerMultiple( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( (value1 % value2) == 0, "'%s' (%s) must be an integer multiple of '%s' (%s).", @@ -184,14 +144,8 @@ public final class Validate { value2); } - /** - * Validates that the first value is greater than the second value. - */ - public static void checkGreater( - long value1, - String value1Name, - long value2, - String value2Name) { + /** Validates that the first value is greater than the second value. */ + public static void checkGreater(long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 > value2, "'%s' (%s) must be greater than '%s' (%s).", @@ -201,14 +155,9 @@ public final class Validate { value2); } - /** - * Validates that the first value is greater than or equal to the second value. - */ + /** Validates that the first value is greater than or equal to the second value. */ public static void checkGreaterOrEqual( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 >= value2, "'%s' (%s) must be greater than or equal to '%s' (%s).", @@ -218,14 +167,9 @@ public final class Validate { value2); } - /** - * Validates that the first value is less than or equal to the second value. - */ + /** Validates that the first value is less than or equal to the second value. */ public static void checkLessOrEqual( - long value1, - String value1Name, - long value2, - String value2Name) { + long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 <= value2, "'%s' (%s) must be less than or equal to '%s' (%s).", @@ -235,14 +179,9 @@ public final class Validate { value2); } - /** - * Validates that the given value is within the given range of values. - */ + /** Validates that the given value is within the given range of values. */ public static void checkWithinRange( - long value, - String valueName, - long minValueInclusive, - long maxValueInclusive) { + long value, String valueName, long minValueInclusive, long maxValueInclusive) { checkArgument( (value >= minValueInclusive) && (value <= maxValueInclusive), "'%s' (%s) must be within the range [%s, %s].", @@ -252,14 +191,9 @@ public final class Validate { maxValueInclusive); } - /** - * Validates that the given value is within the given range of values. - */ + /** Validates that the given value is within the given range of values. */ public static void checkWithinRange( - double value, - String valueName, - double minValueInclusive, - double maxValueInclusive) { + double value, String valueName, double minValueInclusive, double maxValueInclusive) { checkArgument( (value >= minValueInclusive) && (value <= maxValueInclusive), "'%s' (%s) must be within the range [%s, %s].", @@ -277,10 +211,7 @@ public final class Validate { public static void checkPathExistsAsDir(Path path, String argName) { checkPathExists(path, argName); checkArgument( - Files.isDirectory(path), - "Path %s (%s) must point to a directory.", - argName, - path); + Files.isDirectory(path), "Path %s (%s) must point to a directory.", argName, path); } public static void checkPathExistsAsFile(Path path, String argName) { @@ -297,9 +228,6 @@ public final class Validate { } private static void checkNotEmpty(int arraySize, String argName) { - Validate.checkArgument( - arraySize > 0, - "'%s' must have at least one element.", - argName); + Validate.checkArgument(arraySize > 0, "'%s' must have at least one element.", argName); } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java b/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java index 9e6593074..64afb6064 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/ShortStack.java @@ -21,9 +21,9 @@ package org.apache.thrift.protocol; import java.util.Arrays; /** - * ShortStack is a short-specific Stack implementation written for the express - * purpose of very fast operations on TCompactProtocol's field id stack. This - * implementation performs at least 10x faster than java.util.Stack. + * ShortStack is a short-specific Stack implementation written for the express purpose of very fast + * operations on TCompactProtocol's field id stack. This implementation performs at least 10x faster + * than java.util.Stack. */ class ShortStack { diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java b/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java index abfc965b7..a948d13c0 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TBase64Utils.java @@ -22,105 +22,96 @@ package org.apache.thrift.protocol; /** * Class for encoding and decoding Base64 data. * - * This class is kept at package level because the interface does no input - * validation and is therefore too low-level for generalized reuse. - * - * Note also that the encoding does not pad with equal signs , as discussed in - * section 2.2 of the RFC (http://www.faqs.org/rfcs/rfc3548.html). Furthermore, - * bad data encountered when decoding is neither rejected or ignored but simply - * results in bad decoded data -- this is not in compliance with the RFC but is - * done in the interest of performance. + * <p>This class is kept at package level because the interface does no input validation and is + * therefore too low-level for generalized reuse. * + * <p>Note also that the encoding does not pad with equal signs , as discussed in section 2.2 of the + * RFC (http://www.faqs.org/rfcs/rfc3548.html). Furthermore, bad data encountered when decoding is + * neither rejected or ignored but simply results in bad decoded data -- this is not in compliance + * with the RFC but is done in the interest of performance. */ class TBase64Utils { private static final String ENCODE_TABLE = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** - * Encode len bytes of data in src at offset srcOff, storing the result into - * dst at offset dstOff. len must be 1, 2, or 3. dst must have at least len+1 - * bytes of space at dstOff. src and dst should not be the same object. This - * method does no validation of the input values in the interest of - * performance. + * Encode len bytes of data in src at offset srcOff, storing the result into dst at offset dstOff. + * len must be 1, 2, or 3. dst must have at least len+1 bytes of space at dstOff. src and dst + * should not be the same object. This method does no validation of the input values in the + * interest of performance. * - * @param src the source of bytes to encode - * @param srcOff the offset into the source to read the unencoded bytes - * @param len the number of bytes to encode (must be 1, 2, or 3). - * @param dst the destination for the encoding - * @param dstOff the offset into the destination to place the encoded bytes + * @param src the source of bytes to encode + * @param srcOff the offset into the source to read the unencoded bytes + * @param len the number of bytes to encode (must be 1, 2, or 3). + * @param dst the destination for the encoding + * @param dstOff the offset into the destination to place the encoded bytes */ - static final void encode(byte[] src, int srcOff, int len, byte[] dst, - int dstOff) { - dst[dstOff] = (byte)ENCODE_TABLE.charAt((src[srcOff] >> 2) & 0x3F); + static final void encode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) { + dst[dstOff] = (byte) ENCODE_TABLE.charAt((src[srcOff] >> 2) & 0x3F); if (len == 3) { dst[dstOff + 1] = - (byte)ENCODE_TABLE.charAt( - ((src[srcOff] << 4) & 0x30) | ((src[srcOff+1] >> 4) & 0x0F)); - dst[dstOff + 2] = - (byte)ENCODE_TABLE.charAt( - ((src[srcOff+1] << 2) & 0x3C) | ((src[srcOff+2] >> 6) & 0x03)); - dst[dstOff + 3] = - (byte)ENCODE_TABLE.charAt(src[srcOff+2] & 0x3F); - } - else if (len == 2) { - dst[dstOff+1] = - (byte)ENCODE_TABLE.charAt( - ((src[srcOff] << 4) & 0x30) | ((src[srcOff+1] >> 4) & 0x0F)); + (byte) ENCODE_TABLE.charAt(((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)); dst[dstOff + 2] = - (byte)ENCODE_TABLE.charAt((src[srcOff+1] << 2) & 0x3C); - } - else { // len == 1) { + (byte) + ENCODE_TABLE.charAt( + ((src[srcOff + 1] << 2) & 0x3C) | ((src[srcOff + 2] >> 6) & 0x03)); + dst[dstOff + 3] = (byte) ENCODE_TABLE.charAt(src[srcOff + 2] & 0x3F); + } else if (len == 2) { dst[dstOff + 1] = - (byte)ENCODE_TABLE.charAt((src[srcOff] << 4) & 0x30); + (byte) ENCODE_TABLE.charAt(((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)); + dst[dstOff + 2] = (byte) ENCODE_TABLE.charAt((src[srcOff + 1] << 2) & 0x3C); + } else { // len == 1) { + dst[dstOff + 1] = (byte) ENCODE_TABLE.charAt((src[srcOff] << 4) & 0x30); } } private static final byte[] DECODE_TABLE = { - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, - 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, - 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, - -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, - 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** - * Decode len bytes of data in src at offset srcOff, storing the result into - * dst at offset dstOff. len must be 2, 3, or 4. dst must have at least len-1 - * bytes of space at dstOff. src and dst may be the same object as long as - * dstoff <= srcOff. This method does no validation of the input values in - * the interest of performance. + * Decode len bytes of data in src at offset srcOff, storing the result into dst at offset dstOff. + * len must be 2, 3, or 4. dst must have at least len-1 bytes of space at dstOff. src and dst may + * be the same object as long as dstoff <= srcOff. This method does no validation of the input + * values in the interest of performance. * - * @param src the source of bytes to decode - * @param srcOff the offset into the source to read the encoded bytes - * @param len the number of bytes to decode (must be 2, 3, or 4) - * @param dst the destination for the decoding - * @param dstOff the offset into the destination to place the decoded bytes + * @param src the source of bytes to decode + * @param srcOff the offset into the source to read the encoded bytes + * @param len the number of bytes to decode (must be 2, 3, or 4) + * @param dst the destination for the decoding + * @param dstOff the offset into the destination to place the decoded bytes */ - static final void decode(byte[] src, int srcOff, int len, byte[] dst, - int dstOff) { - dst[dstOff] = (byte) - ((DECODE_TABLE[src[srcOff] & 0x0FF] << 2) | - (DECODE_TABLE[src[srcOff+1] & 0x0FF] >> 4)); + static final void decode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) { + dst[dstOff] = + (byte) + ((DECODE_TABLE[src[srcOff] & 0x0FF] << 2) + | (DECODE_TABLE[src[srcOff + 1] & 0x0FF] >> 4)); if (len > 2) { - dst[dstOff+1] = (byte) - (((DECODE_TABLE[src[srcOff+1] & 0x0FF] << 4) & 0xF0) | - (DECODE_TABLE[src[srcOff+2] & 0x0FF] >> 2)); + dst[dstOff + 1] = + (byte) + (((DECODE_TABLE[src[srcOff + 1] & 0x0FF] << 4) & 0xF0) + | (DECODE_TABLE[src[srcOff + 2] & 0x0FF] >> 2)); if (len > 3) { - dst[dstOff+2] = (byte) - (((DECODE_TABLE[src[srcOff+2] & 0x0FF] << 6) & 0xC0) | - DECODE_TABLE[src[srcOff+3] & 0x0FF]); + dst[dstOff + 2] = + (byte) + (((DECODE_TABLE[src[srcOff + 2] & 0x0FF] << 6) & 0xC0) + | DECODE_TABLE[src[srcOff + 3] & 0x0FF]); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java index e8444fefb..3b93dbf98 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TBinaryProtocol.java @@ -21,16 +21,12 @@ package org.apache.thrift.protocol; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; - import org.apache.thrift.TException; import org.apache.thrift.partial.TFieldData; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; -/** - * Binary protocol implementation for thrift. - * - */ +/** Binary protocol implementation for thrift. */ public class TBinaryProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(); private static final long NO_LENGTH_LIMIT = -1; @@ -39,15 +35,14 @@ public class TBinaryProtocol extends TProtocol { protected static final int VERSION_1 = 0x80010000; /** - * The maximum number of bytes to read from the transport for - * variable-length fields (such as strings or binary) or {@link #NO_LENGTH_LIMIT} for - * unlimited. + * The maximum number of bytes to read from the transport for variable-length fields (such as + * strings or binary) or {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long stringLengthLimit_; /** - * The maximum number of elements to read from the network for - * containers (maps, sets, lists), or {@link #NO_LENGTH_LIMIT} for unlimited. + * The maximum number of elements to read from the network for containers (maps, sets, lists), or + * {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long containerLengthLimit_; @@ -56,9 +51,7 @@ public class TBinaryProtocol extends TProtocol { private final byte[] inoutTemp = new byte[8]; - /** - * Factory - */ + /** Factory */ public static class Factory implements TProtocolFactory { protected long stringLengthLimit_; protected long containerLengthLimit_; @@ -77,7 +70,11 @@ public class TBinaryProtocol extends TProtocol { this(false, true, stringLengthLimit, containerLengthLimit); } - public Factory(boolean strictRead, boolean strictWrite, long stringLengthLimit, long containerLengthLimit) { + public Factory( + boolean strictRead, + boolean strictWrite, + long stringLengthLimit, + long containerLengthLimit) { stringLengthLimit_ = stringLengthLimit; containerLengthLimit_ = containerLengthLimit; strictRead_ = strictRead; @@ -85,13 +82,12 @@ public class TBinaryProtocol extends TProtocol { } public TProtocol getProtocol(TTransport trans) { - return new TBinaryProtocol(trans, stringLengthLimit_, containerLengthLimit_, strictRead_, strictWrite_); + return new TBinaryProtocol( + trans, stringLengthLimit_, containerLengthLimit_, strictRead_, strictWrite_); } } - /** - * Constructor - */ + /** Constructor */ public TBinaryProtocol(TTransport trans) { this(trans, false, true); } @@ -104,7 +100,12 @@ public class TBinaryProtocol extends TProtocol { this(trans, stringLengthLimit, containerLengthLimit, false, true); } - public TBinaryProtocol(TTransport trans, long stringLengthLimit, long containerLengthLimit, boolean strictRead, boolean strictWrite) { + public TBinaryProtocol( + TTransport trans, + long stringLengthLimit, + long containerLengthLimit, + boolean strictRead, + boolean strictWrite) { super(trans); stringLengthLimit_ = stringLengthLimit; containerLengthLimit_ = containerLengthLimit; @@ -179,7 +180,7 @@ public class TBinaryProtocol extends TProtocol { @Override public void writeBool(boolean b) throws TException { - writeByte(b ? (byte)1 : (byte)0); + writeByte(b ? (byte) 1 : (byte) 0); } @Override @@ -190,30 +191,30 @@ public class TBinaryProtocol extends TProtocol { @Override public void writeI16(short i16) throws TException { - inoutTemp[0] = (byte)(0xff & (i16 >> 8)); - inoutTemp[1] = (byte)(0xff & (i16)); + inoutTemp[0] = (byte) (0xff & (i16 >> 8)); + inoutTemp[1] = (byte) (0xff & (i16)); trans_.write(inoutTemp, 0, 2); } @Override public void writeI32(int i32) throws TException { - inoutTemp[0] = (byte)(0xff & (i32 >> 24)); - inoutTemp[1] = (byte)(0xff & (i32 >> 16)); - inoutTemp[2] = (byte)(0xff & (i32 >> 8)); - inoutTemp[3] = (byte)(0xff & (i32)); + inoutTemp[0] = (byte) (0xff & (i32 >> 24)); + inoutTemp[1] = (byte) (0xff & (i32 >> 16)); + inoutTemp[2] = (byte) (0xff & (i32 >> 8)); + inoutTemp[3] = (byte) (0xff & (i32)); trans_.write(inoutTemp, 0, 4); } @Override public void writeI64(long i64) throws TException { - inoutTemp[0] = (byte)(0xff & (i64 >> 56)); - inoutTemp[1] = (byte)(0xff & (i64 >> 48)); - inoutTemp[2] = (byte)(0xff & (i64 >> 40)); - inoutTemp[3] = (byte)(0xff & (i64 >> 32)); - inoutTemp[4] = (byte)(0xff & (i64 >> 24)); - inoutTemp[5] = (byte)(0xff & (i64 >> 16)); - inoutTemp[6] = (byte)(0xff & (i64 >> 8)); - inoutTemp[7] = (byte)(0xff & (i64)); + inoutTemp[0] = (byte) (0xff & (i64 >> 56)); + inoutTemp[1] = (byte) (0xff & (i64 >> 48)); + inoutTemp[2] = (byte) (0xff & (i64 >> 40)); + inoutTemp[3] = (byte) (0xff & (i64 >> 32)); + inoutTemp[4] = (byte) (0xff & (i64 >> 24)); + inoutTemp[5] = (byte) (0xff & (i64 >> 16)); + inoutTemp[6] = (byte) (0xff & (i64 >> 8)); + inoutTemp[7] = (byte) (0xff & (i64)); trans_.write(inoutTemp, 0, 8); } @@ -236,22 +237,21 @@ public class TBinaryProtocol extends TProtocol { trans_.write(bin.array(), bin.position() + bin.arrayOffset(), length); } - /** - * Reading methods. - */ - + /** Reading methods. */ @Override public TMessage readMessageBegin() throws TException { int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { - throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); + throw new TProtocolException( + TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } - return new TMessage(readString(), (byte)(size & 0x000000ff), readI32()); + return new TMessage(readString(), (byte) (size & 0x000000ff), readI32()); } else { if (strictRead_) { - throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); + throw new TProtocolException( + TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } return new TMessage(readStringBody(size), readByte(), readI32()); } @@ -343,10 +343,7 @@ public class TBinaryProtocol extends TProtocol { readAll(inoutTemp, 0, 2); } - return - (short) - (((buf[off] & 0xff) << 8) | - ((buf[off+1] & 0xff))); + return (short) (((buf[off] & 0xff) << 8) | ((buf[off + 1] & 0xff))); } @Override @@ -361,11 +358,10 @@ public class TBinaryProtocol extends TProtocol { } else { readAll(inoutTemp, 0, 4); } - return - ((buf[off] & 0xff) << 24) | - ((buf[off+1] & 0xff) << 16) | - ((buf[off+2] & 0xff) << 8) | - ((buf[off+3] & 0xff)); + return ((buf[off] & 0xff) << 24) + | ((buf[off + 1] & 0xff) << 16) + | ((buf[off + 2] & 0xff) << 8) + | ((buf[off + 3] & 0xff)); } @Override @@ -381,15 +377,14 @@ public class TBinaryProtocol extends TProtocol { readAll(inoutTemp, 0, 8); } - return - ((long)(buf[off] & 0xff) << 56) | - ((long)(buf[off+1] & 0xff) << 48) | - ((long)(buf[off+2] & 0xff) << 40) | - ((long)(buf[off+3] & 0xff) << 32) | - ((long)(buf[off+4] & 0xff) << 24) | - ((long)(buf[off+5] & 0xff) << 16) | - ((long)(buf[off+6] & 0xff) << 8) | - ((long)(buf[off+7] & 0xff)); + return ((long) (buf[off] & 0xff) << 56) + | ((long) (buf[off + 1] & 0xff) << 48) + | ((long) (buf[off + 2] & 0xff) << 40) + | ((long) (buf[off + 3] & 0xff) << 32) + | ((long) (buf[off + 4] & 0xff) << 24) + | ((long) (buf[off + 5] & 0xff) << 16) + | ((long) (buf[off + 6] & 0xff) << 8) + | ((long) (buf[off + 7] & 0xff)); } @Override @@ -402,8 +397,8 @@ public class TBinaryProtocol extends TProtocol { int size = readI32(); if (trans_.getBytesRemainingInBuffer() >= size) { - String s = new String(trans_.getBuffer(), trans_.getBufferPosition(), - size, StandardCharsets.UTF_8); + String s = + new String(trans_.getBuffer(), trans_.getBufferPosition(), size, StandardCharsets.UTF_8); trans_.consumeBuffer(size); return s; } @@ -437,26 +432,24 @@ public class TBinaryProtocol extends TProtocol { private void checkStringReadLength(int length) throws TException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } getTransport().checkReadBytesAvailable(length); if (stringLengthLimit_ != NO_LENGTH_LIMIT && length > stringLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } private void checkContainerReadLength(int length) throws TProtocolException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } if (containerLengthLimit_ != NO_LENGTH_LIMIT && length > containerLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } @@ -464,27 +457,37 @@ public class TBinaryProtocol extends TProtocol { return trans_.readAll(buf, off, len); } - /** - * - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TTransportException { - switch (type) - { - case 0: return 0; // Stop - case 1: return 0; // Void - case 2: return 1; // Bool sizeof(byte) - case 3: return 1; // Byte sizeof(byte) - case 4: return 8; // Double sizeof(double) - case 6: return 2; // I16 sizeof(short) - case 8: return 4; // I32 sizeof(int) - case 10: return 8;// I64 sizeof(long) - case 11: return 4; // string length sizeof(int) - case 12: return 0; // empty struct - case 13: return 4; // element count Map sizeof(int) - case 14: return 4; // element count Set sizeof(int) - case 15: return 4; // element count List sizeof(int) - default: throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool sizeof(byte) + case 3: + return 1; // Byte sizeof(byte) + case 4: + return 8; // Double sizeof(double) + case 6: + return 2; // I16 sizeof(short) + case 8: + return 4; // I32 sizeof(int) + case 10: + return 8; // I64 sizeof(long) + case 11: + return 4; // string length sizeof(int) + case 12: + return 0; // empty struct + case 13: + return 4; // element count Map sizeof(int) + case 14: + return 4; // element count Set sizeof(int) + case 15: + return 4; // element count List sizeof(int) + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); } } // ----------------------------------------------------------------- diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java index 3bace8e90..8adb25e69 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TCompactProtocol.java @@ -17,36 +17,32 @@ * under the License. */ - package org.apache.thrift.protocol; -import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; - import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; /** - * TCompactProtocol2 is the Java implementation of the compact protocol specified - * in THRIFT-110. The fundamental approach to reducing the overhead of - * structures is a) use variable-length integers all over the place and b) make - * use of unused bits wherever possible. Your savings will obviously vary - * based on the specific makeup of your structs, but in general, the more - * fields, nested structures, short strings and collections, and low-value i32 - * and i64 fields you have, the more benefit you'll see. + * TCompactProtocol2 is the Java implementation of the compact protocol specified in THRIFT-110. The + * fundamental approach to reducing the overhead of structures is a) use variable-length integers + * all over the place and b) make use of unused bits wherever possible. Your savings will obviously + * vary based on the specific makeup of your structs, but in general, the more fields, nested + * structures, short strings and collections, and low-value i32 and i64 fields you have, the more + * benefit you'll see. */ public class TCompactProtocol extends TProtocol { - private final static byte[] EMPTY_BYTES = new byte[0]; - private final static ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(EMPTY_BYTES); + private static final byte[] EMPTY_BYTES = new byte[0]; + private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(EMPTY_BYTES); - private final static long NO_LENGTH_LIMIT = -1; + private static final long NO_LENGTH_LIMIT = -1; - private final static TStruct ANONYMOUS_STRUCT = new TStruct(""); - private final static TField TSTOP = new TField("", TType.STOP, (short)0); + private static final TStruct ANONYMOUS_STRUCT = new TStruct(""); + private static final TField TSTOP = new TField("", TType.STOP, (short) 0); - private final static byte[] ttypeToCompactType = new byte[16]; + private static final byte[] ttypeToCompactType = new byte[16]; static { ttypeToCompactType[TType.STOP] = TType.STOP; @@ -63,9 +59,7 @@ public class TCompactProtocol extends TProtocol { ttypeToCompactType[TType.STRUCT] = Types.STRUCT; } - /** - * TProtocolFactory that produces TCompactProtocols. - */ + /** TProtocolFactory that produces TCompactProtocols. */ public static class Factory implements TProtocolFactory { private final long stringLengthLimit_; private final long containerLengthLimit_; @@ -88,67 +82,63 @@ public class TCompactProtocol extends TProtocol { } } - private static final byte PROTOCOL_ID = (byte)0x82; + private static final byte PROTOCOL_ID = (byte) 0x82; private static final byte VERSION = 1; private static final byte VERSION_MASK = 0x1f; // 0001 1111 - private static final byte TYPE_MASK = (byte)0xE0; // 1110 0000 + private static final byte TYPE_MASK = (byte) 0xE0; // 1110 0000 private static final byte TYPE_BITS = 0x07; // 0000 0111 - private static final int TYPE_SHIFT_AMOUNT = 5; + private static final int TYPE_SHIFT_AMOUNT = 5; - /** - * All of the on-wire type codes. - */ + /** All of the on-wire type codes. */ private static class Types { - public static final byte BOOLEAN_TRUE = 0x01; - public static final byte BOOLEAN_FALSE = 0x02; - public static final byte BYTE = 0x03; - public static final byte I16 = 0x04; - public static final byte I32 = 0x05; - public static final byte I64 = 0x06; - public static final byte DOUBLE = 0x07; - public static final byte BINARY = 0x08; - public static final byte LIST = 0x09; - public static final byte SET = 0x0A; - public static final byte MAP = 0x0B; - public static final byte STRUCT = 0x0C; + public static final byte BOOLEAN_TRUE = 0x01; + public static final byte BOOLEAN_FALSE = 0x02; + public static final byte BYTE = 0x03; + public static final byte I16 = 0x04; + public static final byte I32 = 0x05; + public static final byte I64 = 0x06; + public static final byte DOUBLE = 0x07; + public static final byte BINARY = 0x08; + public static final byte LIST = 0x09; + public static final byte SET = 0x0A; + public static final byte MAP = 0x0B; + public static final byte STRUCT = 0x0C; } /** - * Used to keep track of the last field for the current and previous structs, - * so we can do the delta stuff. + * Used to keep track of the last field for the current and previous structs, so we can do the + * delta stuff. */ private final ShortStack lastField_ = new ShortStack(15); private short lastFieldId_ = 0; /** - * If we encounter a boolean field begin, save the TField here so it can - * have the value incorporated. + * If we encounter a boolean field begin, save the TField here so it can have the value + * incorporated. */ private TField booleanField_ = null; /** - * If we read a field header, and it's a boolean field, save the boolean - * value here so that readBool can use it. + * If we read a field header, and it's a boolean field, save the boolean value here so that + * readBool can use it. */ private Boolean boolValue_ = null; /** - * The maximum number of bytes to read from the transport for - * variable-length fields (such as strings or binary) or {@link #NO_LENGTH_LIMIT} for - * unlimited. + * The maximum number of bytes to read from the transport for variable-length fields (such as + * strings or binary) or {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long stringLengthLimit_; /** - * The maximum number of elements to read from the network for - * containers (maps, sets, lists), or {@link #NO_LENGTH_LIMIT} for unlimited. + * The maximum number of elements to read from the network for containers (maps, sets, lists), or + * {@link #NO_LENGTH_LIMIT} for unlimited. */ private final long containerLengthLimit_; /** - * Temporary buffer used for various operations that would otherwise require a - * small allocation. + * Temporary buffer used for various operations that would otherwise require a small allocation. */ private final byte[] temp = new byte[10]; @@ -156,10 +146,8 @@ public class TCompactProtocol extends TProtocol { * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. - * @param stringLengthLimit the maximum number of bytes to read for - * variable-length fields. - * @param containerLengthLimit the maximum number of elements to read - * for containers. + * @param stringLengthLimit the maximum number of bytes to read for variable-length fields. + * @param containerLengthLimit the maximum number of elements to read for containers. */ public TCompactProtocol(TTransport transport, long stringLengthLimit, long containerLengthLimit) { super(transport); @@ -171,8 +159,7 @@ public class TCompactProtocol extends TProtocol { * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. - * @param stringLengthLimit the maximum number of bytes to read for - * variable-length fields. + * @param stringLengthLimit the maximum number of bytes to read for variable-length fields. * @deprecated Use constructor specifying both string limit and container limit instead */ @Deprecated @@ -200,8 +187,8 @@ public class TCompactProtocol extends TProtocol { // /** - * Write a message header to the wire. Compact Protocol messages contain the - * protocol version so we can migrate forwards in the future if need be. + * Write a message header to the wire. Compact Protocol messages contain the protocol version so + * we can migrate forwards in the future if need be. */ @Override public void writeMessageBegin(TMessage message) throws TException { @@ -212,9 +199,9 @@ public class TCompactProtocol extends TProtocol { } /** - * Write a struct begin. This doesn't actually put anything on the wire. We - * use it as an opportunity to put special placeholder markers on the field - * stack so we can get the field id deltas correct. + * Write a struct begin. This doesn't actually put anything on the wire. We use it as an + * opportunity to put special placeholder markers on the field stack so we can get the field id + * deltas correct. */ @Override public void writeStructBegin(TStruct struct) throws TException { @@ -223,33 +210,30 @@ public class TCompactProtocol extends TProtocol { } /** - * Write a struct end. This doesn't actually put anything on the wire. We use - * this as an opportunity to pop the last field from the current struct off - * of the field stack. + * Write a struct end. This doesn't actually put anything on the wire. We use this as an + * opportunity to pop the last field from the current struct off of the field stack. */ public void writeStructEnd() throws TException { lastFieldId_ = lastField_.pop(); } /** - * Write a field header containing the field id and field type. If the - * difference between the current field id and the last one is small (< 15), - * then the field id will be encoded in the 4 MSB as a delta. Otherwise, the - * field id will follow the type header as a zigzag varint. + * Write a field header containing the field id and field type. If the difference between the + * current field id and the last one is small (< 15), then the field id will be encoded in the + * 4 MSB as a delta. Otherwise, the field id will follow the type header as a zigzag varint. */ public void writeFieldBegin(TField field) throws TException { if (field.type == TType.BOOL) { // we want to possibly include the value, so we'll wait. booleanField_ = field; } else { - writeFieldBeginInternal(field, (byte)-1); + writeFieldBeginInternal(field, (byte) -1); } } /** - * The workhorse of writeFieldBegin. It has the option of doing a - * 'type override' of the type header. This is used specifically in the - * boolean field case. + * The workhorse of writeFieldBegin. It has the option of doing a 'type override' of the type + * header. This is used specifically in the boolean field case. */ private void writeFieldBeginInternal(TField field, byte typeOverride) throws TException { // short lastField = lastField_.pop(); @@ -271,16 +255,14 @@ public class TCompactProtocol extends TProtocol { // lastField_.push(field.id); } - /** - * Write the STOP symbol so we know there are no more fields in this struct. - */ + /** Write the STOP symbol so we know there are no more fields in this struct. */ public void writeFieldStop() throws TException { writeByteDirect(TType.STOP); } /** - * Write a map header. If the map is empty, omit the key and value type - * headers, as we don't need any additional information to skip it. + * Write a map header. If the map is empty, omit the key and value type headers, as we don't need + * any additional information to skip it. */ public void writeMapBegin(TMap map) throws TException { if (map.size == 0) { @@ -291,25 +273,20 @@ public class TCompactProtocol extends TProtocol { } } - /** - * Write a list header. - */ + /** Write a list header. */ public void writeListBegin(TList list) throws TException { writeCollectionBegin(list.elemType, list.size); } - /** - * Write a set header. - */ + /** Write a set header. */ public void writeSetBegin(TSet set) throws TException { writeCollectionBegin(set.elemType, set.size); } /** - * Write a boolean value. Potentially, this could be a boolean field, in - * which case the field header info isn't written yet. If so, decide what the - * right type header is for the value and then write the field header. - * Otherwise, write a single byte. + * Write a boolean value. Potentially, this could be a boolean field, in which case the field + * header info isn't written yet. If so, decide what the right type header is for the value and + * then write the field header. Otherwise, write a single byte. */ public void writeBool(boolean b) throws TException { if (booleanField_ != null) { @@ -322,54 +299,40 @@ public class TCompactProtocol extends TProtocol { } } - /** - * Write a byte. Nothing to see here! - */ + /** Write a byte. Nothing to see here! */ public void writeByte(byte b) throws TException { writeByteDirect(b); } - /** - * Write an I16 as a zigzag varint. - */ + /** Write an I16 as a zigzag varint. */ public void writeI16(short i16) throws TException { writeVarint32(intToZigZag(i16)); } - /** - * Write an i32 as a zigzag varint. - */ + /** Write an i32 as a zigzag varint. */ public void writeI32(int i32) throws TException { writeVarint32(intToZigZag(i32)); } - /** - * Write an i64 as a zigzag varint. - */ + /** Write an i64 as a zigzag varint. */ public void writeI64(long i64) throws TException { writeVarint64(longToZigzag(i64)); } - /** - * Write a double to the wire as 8 bytes. - */ + /** Write a double to the wire as 8 bytes. */ public void writeDouble(double dub) throws TException { fixedLongToBytes(Double.doubleToLongBits(dub), temp, 0); trans_.write(temp, 0, 8); } - /** - * Write a string to the wire with a varint size preceding. - */ + /** Write a string to the wire with a varint size preceding. */ public void writeString(String str) throws TException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); writeVarint32(bytes.length); trans_.write(bytes, 0, bytes.length); } - /** - * Write a byte array, using a varint for the size. - */ + /** Write a byte array, using a varint for the size. */ public void writeBinary(ByteBuffer bin) throws TException { ByteBuffer bb = bin.asReadOnlyBuffer(); writeVarint32(bb.remaining()); @@ -382,9 +345,13 @@ public class TCompactProtocol extends TProtocol { // public void writeMessageEnd() throws TException {} + public void writeMapEnd() throws TException {} + public void writeListEnd() throws TException {} + public void writeSetEnd() throws TException {} + public void writeFieldEnd() throws TException {} // @@ -392,8 +359,8 @@ public class TCompactProtocol extends TProtocol { // /** - * Abstract method for writing the start of lists and sets. List and sets on - * the wire differ only by the type indicator. + * Abstract method for writing the start of lists and sets. List and sets on the wire differ only + * by the type indicator. */ protected void writeCollectionBegin(byte elemType, int size) throws TException { if (size <= 14) { @@ -405,19 +372,19 @@ public class TCompactProtocol extends TProtocol { } /** - * Write an i32 as a varint. Results in 1-5 bytes on the wire. - * TODO: make a permanent buffer like writeVarint64? + * Write an i32 as a varint. Results in 1-5 bytes on the wire. TODO: make a permanent buffer like + * writeVarint64? */ private void writeVarint32(int n) throws TException { int idx = 0; while (true) { if ((n & ~0x7F) == 0) { - temp[idx++] = (byte)n; + temp[idx++] = (byte) n; // writeByteDirect((byte)n); break; // return; } else { - temp[idx++] = (byte)((n & 0x7F) | 0x80); + temp[idx++] = (byte) ((n & 0x7F) | 0x80); // writeByteDirect((byte)((n & 0x7F) | 0x80)); n >>>= 7; } @@ -425,17 +392,15 @@ public class TCompactProtocol extends TProtocol { trans_.write(temp, 0, idx); } - /** - * Write an i64 as a varint. Results in 1-10 bytes on the wire. - */ + /** Write an i64 as a varint. Results in 1-10 bytes on the wire. */ private void writeVarint64(long n) throws TException { int idx = 0; while (true) { if ((n & ~0x7FL) == 0) { - temp[idx++] = (byte)n; + temp[idx++] = (byte) n; break; } else { - temp[idx++] = ((byte)((n & 0x7F) | 0x80)); + temp[idx++] = ((byte) ((n & 0x7F) | 0x80)); n >>>= 7; } } @@ -443,79 +408,75 @@ public class TCompactProtocol extends TProtocol { } /** - * Convert l into a zigzag long. This allows negative numbers to be - * represented compactly as a varint. + * Convert l into a zigzag long. This allows negative numbers to be represented compactly as a + * varint. */ private long longToZigzag(long l) { return (l << 1) ^ (l >> 63); } /** - * Convert n into a zigzag int. This allows negative numbers to be - * represented compactly as a varint. + * Convert n into a zigzag int. This allows negative numbers to be represented compactly as a + * varint. */ private int intToZigZag(int n) { return (n << 1) ^ (n >> 31); } - /** - * Convert a long into little-endian bytes in buf starting at off and going - * until off+7. - */ + /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedLongToBytes(long n, byte[] buf, int off) { - buf[off+0] = (byte)( n & 0xff); - buf[off+1] = (byte)((n >> 8 ) & 0xff); - buf[off+2] = (byte)((n >> 16) & 0xff); - buf[off+3] = (byte)((n >> 24) & 0xff); - buf[off+4] = (byte)((n >> 32) & 0xff); - buf[off+5] = (byte)((n >> 40) & 0xff); - buf[off+6] = (byte)((n >> 48) & 0xff); - buf[off+7] = (byte)((n >> 56) & 0xff); + buf[off + 0] = (byte) (n & 0xff); + buf[off + 1] = (byte) ((n >> 8) & 0xff); + buf[off + 2] = (byte) ((n >> 16) & 0xff); + buf[off + 3] = (byte) ((n >> 24) & 0xff); + buf[off + 4] = (byte) ((n >> 32) & 0xff); + buf[off + 5] = (byte) ((n >> 40) & 0xff); + buf[off + 6] = (byte) ((n >> 48) & 0xff); + buf[off + 7] = (byte) ((n >> 56) & 0xff); } /** - * Writes a byte without any possibility of all that field header nonsense. - * Used internally by other writing methods that know they need to write a byte. + * Writes a byte without any possibility of all that field header nonsense. Used internally by + * other writing methods that know they need to write a byte. */ private void writeByteDirect(byte b) throws TException { temp[0] = b; trans_.write(temp, 0, 1); } - /** - * Writes a byte without any possibility of all that field header nonsense. - */ + /** Writes a byte without any possibility of all that field header nonsense. */ private void writeByteDirect(int n) throws TException { - writeByteDirect((byte)n); + writeByteDirect((byte) n); } - // // Reading methods. // - /** - * Read a message header. - */ + /** Read a message header. */ public TMessage readMessageBegin() throws TException { byte protocolId = readByte(); if (protocolId != PROTOCOL_ID) { - throw new TProtocolException("Expected protocol id " + Integer.toHexString(PROTOCOL_ID) + " but got " + Integer.toHexString(protocolId)); + throw new TProtocolException( + "Expected protocol id " + + Integer.toHexString(PROTOCOL_ID) + + " but got " + + Integer.toHexString(protocolId)); } byte versionAndType = readByte(); - byte version = (byte)(versionAndType & VERSION_MASK); + byte version = (byte) (versionAndType & VERSION_MASK); if (version != VERSION) { throw new TProtocolException("Expected version " + VERSION + " but got " + version); } - byte type = (byte)((versionAndType >> TYPE_SHIFT_AMOUNT) & TYPE_BITS); + byte type = (byte) ((versionAndType >> TYPE_SHIFT_AMOUNT) & TYPE_BITS); int seqid = readVarint32(); String messageName = readString(); return new TMessage(messageName, type, seqid); } /** - * Read a struct begin. There's nothing on the wire for this, but it is our - * opportunity to push a new struct begin marker onto the field stack. + * Read a struct begin. There's nothing on the wire for this, but it is our opportunity to push a + * new struct begin marker onto the field stack. */ public TStruct readStructBegin() throws TException { lastField_.push(lastFieldId_); @@ -524,17 +485,15 @@ public class TCompactProtocol extends TProtocol { } /** - * Doesn't actually consume any wire data, just removes the last field for - * this struct from the field stack. + * Doesn't actually consume any wire data, just removes the last field for this struct from the + * field stack. */ public void readStructEnd() throws TException { // consume the last field we read off the wire. lastFieldId_ = lastField_.pop(); } - /** - * Read a field header off the wire. - */ + /** Read a field header off the wire. */ public TField readFieldBegin() throws TException { byte type = readByte(); @@ -546,21 +505,21 @@ public class TCompactProtocol extends TProtocol { short fieldId; // mask off the 4 MSB of the type header. it could contain a field id delta. - short modifier = (short)((type & 0xf0) >> 4); + short modifier = (short) ((type & 0xf0) >> 4); if (modifier == 0) { // not a delta. look ahead for the zigzag varint field id. fieldId = readI16(); } else { // has a delta. add the delta to the last read field id. - fieldId = (short)(lastFieldId_ + modifier); + fieldId = (short) (lastFieldId_ + modifier); } - TField field = new TField("", getTType((byte)(type & 0x0f)), fieldId); + TField field = new TField("", getTType((byte) (type & 0x0f)), fieldId); // if this happens to be a boolean field, the value is encoded in the type if (isBoolType(type)) { // save the boolean value in a special instance variable. - boolValue_ = (byte)(type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; + boolValue_ = (byte) (type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; } // push the new field onto the field stack so we can keep the deltas going. @@ -569,24 +528,26 @@ public class TCompactProtocol extends TProtocol { } /** - * Read a map header off the wire. If the size is zero, skip reading the key - * and value type. This means that 0-length maps will yield TMaps without the - * "correct" types. + * Read a map header off the wire. If the size is zero, skip reading the key and value type. This + * means that 0-length maps will yield TMaps without the "correct" types. */ public TMap readMapBegin() throws TException { int size = readVarint32(); checkContainerReadLength(size); byte keyAndValueType = size == 0 ? 0 : readByte(); - TMap map = new TMap(getTType((byte)(keyAndValueType >> 4)), getTType((byte)(keyAndValueType & 0xf)), size); + TMap map = + new TMap( + getTType((byte) (keyAndValueType >> 4)), + getTType((byte) (keyAndValueType & 0xf)), + size); checkReadBytesAvailable(map); return map; } /** - * Read a list header off the wire. If the list size is 0-14, the size will - * be packed into the element type header. If it's a longer list, the 4 MSB - * of the element type header will be 0xF, and a varint will follow with the - * true size. + * Read a list header off the wire. If the list size is 0-14, the size will be packed into the + * element type header. If it's a longer list, the 4 MSB of the element type header will be 0xF, + * and a varint will follow with the true size. */ public TList readListBegin() throws TException { byte size_and_type = readByte(); @@ -601,19 +562,17 @@ public class TCompactProtocol extends TProtocol { } /** - * Read a set header off the wire. If the set size is 0-14, the size will - * be packed into the element type header. If it's a longer set, the 4 MSB - * of the element type header will be 0xF, and a varint will follow with the - * true size. + * Read a set header off the wire. If the set size is 0-14, the size will be packed into the + * element type header. If it's a longer set, the 4 MSB of the element type header will be 0xF, + * and a varint will follow with the true size. */ public TSet readSetBegin() throws TException { return new TSet(readListBegin()); } /** - * Read a boolean off the wire. If this is a boolean field, the value should - * already have been read during readFieldBegin, so we'll just consume the - * pre-stored value. Otherwise, read a byte. + * Read a boolean off the wire. If this is a boolean field, the value should already have been + * read during readFieldBegin, so we'll just consume the pre-stored value. Otherwise, read a byte. */ public boolean readBool() throws TException { if (boolValue_ != null) { @@ -624,9 +583,7 @@ public class TCompactProtocol extends TProtocol { return readByte() == Types.BOOLEAN_TRUE; } - /** - * Read a single byte off the wire. Nothing interesting here. - */ + /** Read a single byte off the wire. Nothing interesting here. */ public byte readByte() throws TException { byte b; if (trans_.getBytesRemainingInBuffer() > 0) { @@ -639,38 +596,28 @@ public class TCompactProtocol extends TProtocol { return b; } - /** - * Read an i16 from the wire as a zigzag varint. - */ + /** Read an i16 from the wire as a zigzag varint. */ public short readI16() throws TException { - return (short)zigzagToInt(readVarint32()); + return (short) zigzagToInt(readVarint32()); } - /** - * Read an i32 from the wire as a zigzag varint. - */ + /** Read an i32 from the wire as a zigzag varint. */ public int readI32() throws TException { return zigzagToInt(readVarint32()); } - /** - * Read an i64 from the wire as a zigzag varint. - */ + /** Read an i64 from the wire as a zigzag varint. */ public long readI64() throws TException { return zigzagToLong(readVarint64()); } - /** - * No magic here - just read a double off the wire. - */ + /** No magic here - just read a double off the wire. */ public double readDouble() throws TException { trans_.readAll(temp, 0, 8); return Double.longBitsToDouble(bytesToLong(temp)); } - /** - * Reads a byte[] (via readBinary), and then UTF-8 decodes it. - */ + /** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */ public String readString() throws TException { int length = readVarint32(); checkStringReadLength(length); @@ -681,8 +628,9 @@ public class TCompactProtocol extends TProtocol { final String str; if (trans_.getBytesRemainingInBuffer() >= length) { - str = new String(trans_.getBuffer(), trans_.getBufferPosition(), - length, StandardCharsets.UTF_8); + str = + new String( + trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8); trans_.consumeBuffer(length); } else { str = new String(readBinary(length), StandardCharsets.UTF_8); @@ -690,9 +638,7 @@ public class TCompactProtocol extends TProtocol { return str; } - /** - * Read a ByteBuffer from the wire. - */ + /** Read a ByteBuffer from the wire. */ public ByteBuffer readBinary() throws TException { int length = readVarint32(); if (length == 0) { @@ -710,9 +656,7 @@ public class TCompactProtocol extends TProtocol { return ByteBuffer.wrap(buf); } - /** - * Read a byte[] of a known length from the wire. - */ + /** Read a byte[] of a known length from the wire. */ private byte[] readBinary(int length) throws TException { if (length == 0) return EMPTY_BYTES; @@ -723,26 +667,24 @@ public class TCompactProtocol extends TProtocol { private void checkStringReadLength(int length) throws TException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } getTransport().checkReadBytesAvailable(length); if (stringLengthLimit_ != NO_LENGTH_LIMIT && length > stringLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } private void checkContainerReadLength(int length) throws TProtocolException { if (length < 0) { - throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, - "Negative length: " + length); + throw new TProtocolException(TProtocolException.NEGATIVE_SIZE, "Negative length: " + length); } if (containerLengthLimit_ != NO_LENGTH_LIMIT && length > containerLengthLimit_) { - throw new TProtocolException(TProtocolException.SIZE_LIMIT, - "Length exceeded max allowed: " + length); + throw new TProtocolException( + TProtocolException.SIZE_LIMIT, "Length exceeded max allowed: " + length); } } @@ -752,12 +694,16 @@ public class TCompactProtocol extends TProtocol { // @Override public void readMessageEnd() throws TException {} + @Override public void readFieldEnd() throws TException {} + @Override public void readMapEnd() throws TException {} + @Override public void readListEnd() throws TException {} + @Override public void readSetEnd() throws TException {} @@ -766,8 +712,8 @@ public class TCompactProtocol extends TProtocol { // /** - * Read an i32 from the wire as a varint. The MSB of each byte is set - * if there is another byte to follow. This can read up to 5 bytes. + * Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to + * follow. This can read up to 5 bytes. */ private int readVarint32() throws TException { int result = 0; @@ -777,13 +723,13 @@ public class TCompactProtocol extends TProtocol { int pos = trans_.getBufferPosition(); int off = 0; while (true) { - byte b = buf[pos+off]; + byte b = buf[pos + off]; result |= (b & 0x7f) << shift; if ((b & 0x80) != 0x80) break; shift += 7; off++; } - trans_.consumeBuffer(off+1); + trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); @@ -796,8 +742,8 @@ public class TCompactProtocol extends TProtocol { } /** - * Read an i64 from the wire as a proper varint. The MSB of each byte is set - * if there is another byte to follow. This can read up to 10 bytes. + * Read an i64 from the wire as a proper varint. The MSB of each byte is set if there is another + * byte to follow. This can read up to 10 bytes. */ private long readVarint64() throws TException { int shift = 0; @@ -807,19 +753,19 @@ public class TCompactProtocol extends TProtocol { int pos = trans_.getBufferPosition(); int off = 0; while (true) { - byte b = buf[pos+off]; + byte b = buf[pos + off]; result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) break; shift += 7; off++; } - trans_.consumeBuffer(off+1); + trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) break; - shift +=7; + shift += 7; } } return result; @@ -829,35 +775,29 @@ public class TCompactProtocol extends TProtocol { // encoding helpers // - /** - * Convert from zigzag int to int. - */ + /** Convert from zigzag int to int. */ private int zigzagToInt(int n) { return (n >>> 1) ^ -(n & 1); } - /** - * Convert from zigzag long to long. - */ + /** Convert from zigzag long to long. */ private long zigzagToLong(long n) { return (n >>> 1) ^ -(n & 1); } /** - * Note that it's important that the mask bytes are long literals, - * otherwise they'll default to ints, and when you shift an int left 56 bits, - * you just get a messed up int. + * Note that it's important that the mask bytes are long literals, otherwise they'll default to + * ints, and when you shift an int left 56 bits, you just get a messed up int. */ private long bytesToLong(byte[] bytes) { - return - ((bytes[7] & 0xffL) << 56) | - ((bytes[6] & 0xffL) << 48) | - ((bytes[5] & 0xffL) << 40) | - ((bytes[4] & 0xffL) << 32) | - ((bytes[3] & 0xffL) << 24) | - ((bytes[2] & 0xffL) << 16) | - ((bytes[1] & 0xffL) << 8) | - ((bytes[0] & 0xffL)); + return ((bytes[7] & 0xffL) << 56) + | ((bytes[6] & 0xffL) << 48) + | ((bytes[5] & 0xffL) << 40) + | ((bytes[4] & 0xffL) << 32) + | ((bytes[3] & 0xffL) << 24) + | ((bytes[2] & 0xffL) << 16) + | ((bytes[1] & 0xffL) << 8) + | ((bytes[0] & 0xffL)); } // @@ -869,12 +809,9 @@ public class TCompactProtocol extends TProtocol { return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE; } - /** - * Given a TCompactProtocol.Types constant, convert it to its corresponding - * TType value. - */ + /** Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. */ private byte getTType(byte type) throws TProtocolException { - switch ((byte)(type & 0x0f)) { + switch ((byte) (type & 0x0f)) { case TType.STOP: return TType.STOP; case Types.BOOLEAN_FALSE: @@ -901,51 +838,47 @@ public class TCompactProtocol extends TProtocol { case Types.STRUCT: return TType.STRUCT; default: - throw new TProtocolException("don't know what type: " + (byte)(type & 0x0f)); + throw new TProtocolException("don't know what type: " + (byte) (type & 0x0f)); } } - /** - * Given a TType value, find the appropriate TCompactProtocol.Types constant. - */ + /** Given a TType value, find the appropriate TCompactProtocol.Types constant. */ private byte getCompactType(byte ttype) { return ttypeToCompactType[ttype]; } - /** - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TTransportException { - switch (type) { - case 0: - return 0; // Stop - case 1: - return 0; // Void - case 2: - return 1; // Bool sizeof(byte) - case 3: - return 1; // Byte sizeof(byte) - case 4: - return 8; // Double sizeof(double) - case 6: - return 1; // I16 sizeof(byte) - case 8: - return 1; // I32 sizeof(byte) - case 10: - return 1;// I64 sizeof(byte) - case 11: - return 1; // string length sizeof(byte) - case 12: - return 0; // empty struct - case 13: - return 1; // element count Map sizeof(byte) - case 14: - return 1; // element count Set sizeof(byte) - case 15: - return 1; // element count List sizeof(byte) - default: - throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); - } + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool sizeof(byte) + case 3: + return 1; // Byte sizeof(byte) + case 4: + return 8; // Double sizeof(double) + case 6: + return 1; // I16 sizeof(byte) + case 8: + return 1; // I32 sizeof(byte) + case 10: + return 1; // I64 sizeof(byte) + case 11: + return 1; // string length sizeof(byte) + case 12: + return 0; // empty struct + case 13: + return 1; // element count Map sizeof(byte) + case 14: + return 1; // element count Set sizeof(byte) + case 15: + return 1; // element count List sizeof(byte) + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + } } // ----------------------------------------------------------------- // Additional methods to improve performance. diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TField.java b/lib/java/src/main/java/org/apache/thrift/protocol/TField.java index 3872b008f..9fde33ca6 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TField.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TField.java @@ -21,11 +21,12 @@ package org.apache.thrift.protocol; /** * Helper class that encapsulates field metadata. - * <p>Two fields are considered equal if they have the same type and id.</p> + * + * <p>Two fields are considered equal if they have the same type and id. */ public class TField { public TField() { - this("", TType.STOP, (short)0); + this("", TType.STOP, (short) 0); } public TField(String n, byte t, short i) { @@ -35,8 +36,8 @@ public class TField { } public final String name; - public final byte type; - public final short id; + public final byte type; + public final short id; public String toString() { return "<TField name:'" + name + "' type:" + type + " field-id:" + id + ">"; @@ -53,12 +54,9 @@ public class TField { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; TField otherField = (TField) obj; return type == otherField.type && id == otherField.id; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java index 95eb62ced..53d0d715c 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java @@ -24,7 +24,6 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Stack; - import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; @@ -33,17 +32,13 @@ import org.apache.thrift.transport.TTransportException; /** * JSON protocol implementation for thrift. * - * This is a full-featured protocol supporting write and read. - * - * Please see the C++ class header for a detailed description of the - * protocol's wire format. + * <p>This is a full-featured protocol supporting write and read. * + * <p>Please see the C++ class header for a detailed description of the protocol's wire format. */ public class TJSONProtocol extends TProtocol { - /** - * Factory for JSON protocol objects - */ + /** Factory for JSON protocol objects */ public static class Factory implements TProtocolFactory { protected boolean fieldNamesAsString_ = false; @@ -56,7 +51,6 @@ public class TJSONProtocol extends TProtocol { public TProtocol getProtocol(TTransport trans) { return new TJSONProtocol(trans, fieldNamesAsString_); } - } private static final byte[] COMMA = new byte[] {','}; @@ -69,15 +63,15 @@ public class TJSONProtocol extends TProtocol { private static final byte[] BACKSLASH = new byte[] {'\\'}; private static final byte[] ZERO = new byte[] {'0'}; - private static final byte[] ESCSEQ = new byte[] {'\\','u','0','0'}; + private static final byte[] ESCSEQ = new byte[] {'\\', 'u', '0', '0'}; - private static final long VERSION = 1; + private static final long VERSION = 1; private static final byte[] JSON_CHAR_TABLE = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ - 0, 0, 0, 0, 0, 0, 0, 0,'b','t','n', 0,'f','r', 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, // 2 + 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 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, // 2 }; private static final String ESCAPE_CHARS = "\"\\/bfnrt"; @@ -86,102 +80,97 @@ public class TJSONProtocol extends TProtocol { '"', '\\', '/', '\b', '\f', '\n', '\r', '\t', }; - private static final int DEF_STRING_SIZE = 16; + private static final int DEF_STRING_SIZE = 16; private static final byte[] NAME_BOOL = new byte[] {'t', 'f'}; - private static final byte[] NAME_BYTE = new byte[] {'i','8'}; - private static final byte[] NAME_I16 = new byte[] {'i','1','6'}; - private static final byte[] NAME_I32 = new byte[] {'i','3','2'}; - private static final byte[] NAME_I64 = new byte[] {'i','6','4'}; - private static final byte[] NAME_DOUBLE = new byte[] {'d','b','l'}; - private static final byte[] NAME_STRUCT = new byte[] {'r','e','c'}; - private static final byte[] NAME_STRING = new byte[] {'s','t','r'}; - private static final byte[] NAME_MAP = new byte[] {'m','a','p'}; - private static final byte[] NAME_LIST = new byte[] {'l','s','t'}; - private static final byte[] NAME_SET = new byte[] {'s','e','t'}; + private static final byte[] NAME_BYTE = new byte[] {'i', '8'}; + private static final byte[] NAME_I16 = new byte[] {'i', '1', '6'}; + private static final byte[] NAME_I32 = new byte[] {'i', '3', '2'}; + private static final byte[] NAME_I64 = new byte[] {'i', '6', '4'}; + private static final byte[] NAME_DOUBLE = new byte[] {'d', 'b', 'l'}; + private static final byte[] NAME_STRUCT = new byte[] {'r', 'e', 'c'}; + private static final byte[] NAME_STRING = new byte[] {'s', 't', 'r'}; + private static final byte[] NAME_MAP = new byte[] {'m', 'a', 'p'}; + private static final byte[] NAME_LIST = new byte[] {'l', 's', 't'}; + private static final byte[] NAME_SET = new byte[] {'s', 'e', 't'}; private static final TStruct ANONYMOUS_STRUCT = new TStruct(); - private static final byte[] getTypeNameForTypeID(byte typeID) - throws TException { + private static final byte[] getTypeNameForTypeID(byte typeID) throws TException { switch (typeID) { - case TType.BOOL: - return NAME_BOOL; - case TType.BYTE: - return NAME_BYTE; - case TType.I16: - return NAME_I16; - case TType.I32: - return NAME_I32; - case TType.I64: - return NAME_I64; - case TType.DOUBLE: - return NAME_DOUBLE; - case TType.STRING: - return NAME_STRING; - case TType.STRUCT: - return NAME_STRUCT; - case TType.MAP: - return NAME_MAP; - case TType.SET: - return NAME_SET; - case TType.LIST: - return NAME_LIST; - default: - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Unrecognized type"); - } - } - - private static final byte getTypeIDForTypeName(byte[] name) - throws TException { + case TType.BOOL: + return NAME_BOOL; + case TType.BYTE: + return NAME_BYTE; + case TType.I16: + return NAME_I16; + case TType.I32: + return NAME_I32; + case TType.I64: + return NAME_I64; + case TType.DOUBLE: + return NAME_DOUBLE; + case TType.STRING: + return NAME_STRING; + case TType.STRUCT: + return NAME_STRUCT; + case TType.MAP: + return NAME_MAP; + case TType.SET: + return NAME_SET; + case TType.LIST: + return NAME_LIST; + default: + throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); + } + } + + private static final byte getTypeIDForTypeName(byte[] name) throws TException { byte result = TType.STOP; if (name.length > 1) { switch (name[0]) { - case 'd': - result = TType.DOUBLE; - break; - case 'i': - switch (name[1]) { - case '8': - result = TType.BYTE; + case 'd': + result = TType.DOUBLE; break; - case '1': - result = TType.I16; + case 'i': + switch (name[1]) { + case '8': + result = TType.BYTE; + break; + case '1': + result = TType.I16; + break; + case '3': + result = TType.I32; + break; + case '6': + result = TType.I64; + break; + } break; - case '3': - result = TType.I32; + case 'l': + result = TType.LIST; break; - case '6': - result = TType.I64; + case 'm': + result = TType.MAP; + break; + case 'r': + result = TType.STRUCT; + break; + case 's': + if (name[1] == 't') { + result = TType.STRING; + } else if (name[1] == 'e') { + result = TType.SET; + } + break; + case 't': + result = TType.BOOL; break; - } - break; - case 'l': - result = TType.LIST; - break; - case 'm': - result = TType.MAP; - break; - case 'r': - result = TType.STRUCT; - break; - case 's': - if (name[1] == 't') { - result = TType.STRING; - } - else if (name[1] == 'e') { - result = TType.SET; - } - break; - case 't': - result = TType.BOOL; - break; } } if (result == TType.STOP) { - throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, - "Unrecognized type"); + throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); } return result; } @@ -194,7 +183,9 @@ public class TJSONProtocol extends TProtocol { protected void read() throws TException {} - protected boolean escapeNum() { return false; } + protected boolean escapeNum() { + return false; + } } // Context for JSON lists. Will insert/read commas before each item except @@ -268,8 +259,7 @@ public class TJSONProtocol extends TProtocol { protected byte read() throws TException { if (hasData_) { hasData_ = false; - } - else { + } else { trans_.readAll(data_, 0, 1); } return data_[0]; @@ -316,9 +306,7 @@ public class TJSONProtocol extends TProtocol { } } - /** - * Constructor - */ + /** Constructor */ public TJSONProtocol(TTransport trans) { super(trans); } @@ -344,8 +332,8 @@ public class TJSONProtocol extends TProtocol { protected void readJSONSyntaxChar(byte[] b) throws TException { byte ch = reader_.read(); if (ch != b[0]) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Unexpected character:" + (char)ch); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Unexpected character:" + (char) ch); } } @@ -353,14 +341,11 @@ public class TJSONProtocol extends TProtocol { // corresponding hex value private static final byte hexVal(byte ch) throws TException { if ((ch >= '0') && (ch <= '9')) { - return (byte)((char)ch - '0'); - } - else if ((ch >= 'a') && (ch <= 'f')) { - return (byte)((char)ch - 'a' + 10); - } - else { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected hex character"); + return (byte) ((char) ch - '0'); + } else if ((ch >= 'a') && (ch <= 'f')) { + return (byte) ((char) ch - 'a' + 10); + } else { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected hex character"); } } @@ -368,10 +353,9 @@ public class TJSONProtocol extends TProtocol { private static final byte hexChar(byte val) { val &= 0x0F; if (val < 10) { - return (byte)((char)val + '0'); - } - else { - return (byte)((char)(val - 10) + 'a'); + return (byte) ((char) val + '0'); + } else { + return (byte) ((char) (val - 10) + 'a'); } } @@ -385,23 +369,19 @@ public class TJSONProtocol extends TProtocol { if (b[i] == BACKSLASH[0]) { trans_.write(BACKSLASH); trans_.write(BACKSLASH); - } - else { + } else { trans_.write(b, i, 1); } - } - else { + } else { tmpbuf_[0] = JSON_CHAR_TABLE[b[i]]; if (tmpbuf_[0] == 1) { trans_.write(b, i, 1); - } - else if (tmpbuf_[0] > 1) { + } else if (tmpbuf_[0] > 1) { trans_.write(BACKSLASH); trans_.write(tmpbuf_, 0, 1); - } - else { + } else { trans_.write(ESCSEQ); - tmpbuf_[0] = hexChar((byte)(b[i] >> 4)); + tmpbuf_[0] = hexChar((byte) (b[i] >> 4)); tmpbuf_[1] = hexChar(b[i]); trans_.write(tmpbuf_, 0, 2); } @@ -433,18 +413,18 @@ public class TJSONProtocol extends TProtocol { String str = Double.toString(num); boolean special = false; switch (str.charAt(0)) { - case 'N': // NaN - case 'I': // Infinity - special = true; - break; - case '-': - if (str.charAt(1) == 'I') { // -Infinity + case 'N': // NaN + case 'I': // Infinity special = true; - } - break; - default: - break; - } + break; + case '-': + if (str.charAt(1) == 'I') { // -Infinity + special = true; + } + break; + default: + break; + } boolean escapeNum = special || context_.escapeNum(); if (escapeNum) { @@ -587,7 +567,7 @@ public class TJSONProtocol extends TProtocol { @Override public void writeBool(boolean b) throws TException { - writeJSONInteger(b ? (long)1 : (long)0); + writeJSONInteger(b ? (long) 1 : (long) 0); } @Override @@ -623,17 +603,17 @@ public class TJSONProtocol extends TProtocol { @Override public void writeBinary(ByteBuffer bin) throws TException { - writeJSONBase64(bin.array(), bin.position() + bin.arrayOffset(), bin.limit() - bin.position() - bin.arrayOffset()); + writeJSONBase64( + bin.array(), + bin.position() + bin.arrayOffset(), + bin.limit() - bin.position() - bin.arrayOffset()); } - /** - * Reading methods. - */ + /** Reading methods. */ // Read in a JSON string, unescaping as appropriate.. Skip reading from the // context if skipContext is true. - private TByteArrayOutputStream readJSONString(boolean skipContext) - throws TException { + private TByteArrayOutputStream readJSONString(boolean skipContext) throws TException { TByteArrayOutputStream arr = new TByteArrayOutputStream(DEF_STRING_SIZE); ArrayList<Character> codeunits = new ArrayList<Character>(); if (!skipContext) { @@ -649,46 +629,42 @@ public class TJSONProtocol extends TProtocol { ch = reader_.read(); if (ch == ESCSEQ[1]) { trans_.readAll(tmpbuf_, 0, 4); - short cu = (short)( - ((short)hexVal(tmpbuf_[0]) << 12) + - ((short)hexVal(tmpbuf_[1]) << 8) + - ((short)hexVal(tmpbuf_[2]) << 4) + - (short)hexVal(tmpbuf_[3])); + short cu = + (short) + (((short) hexVal(tmpbuf_[0]) << 12) + + ((short) hexVal(tmpbuf_[1]) << 8) + + ((short) hexVal(tmpbuf_[2]) << 4) + + (short) hexVal(tmpbuf_[3])); try { - if (Character.isHighSurrogate((char)cu)) { + if (Character.isHighSurrogate((char) cu)) { if (codeunits.size() > 0) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected low surrogate char"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Expected low surrogate char"); } - codeunits.add((char)cu); - } - else if (Character.isLowSurrogate((char)cu)) { + codeunits.add((char) cu); + } else if (Character.isLowSurrogate((char) cu)) { if (codeunits.size() == 0) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected high surrogate char"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Expected high surrogate char"); } - codeunits.add((char)cu); + codeunits.add((char) cu); arr.write( - (new String(new int[] { codeunits.get(0), codeunits.get(1) }, - 0, 2)).getBytes(StandardCharsets.UTF_8)); + (new String(new int[] {codeunits.get(0), codeunits.get(1)}, 0, 2)) + .getBytes(StandardCharsets.UTF_8)); codeunits.clear(); - } - else { - arr.write((new String(new int[] { cu }, 0, 1)) - .getBytes(StandardCharsets.UTF_8)); + } else { + arr.write((new String(new int[] {cu}, 0, 1)).getBytes(StandardCharsets.UTF_8)); } continue; } catch (IOException ex) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Invalid unicode sequence"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Invalid unicode sequence"); } - } - else { + } else { int off = ESCAPE_CHARS.indexOf(ch); if (off == -1) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Expected control char"); + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char"); } ch = ESCAPE_CHAR_VALS[off]; } @@ -701,22 +677,22 @@ public class TJSONProtocol extends TProtocol { // Return true if the given byte could be a valid part of a JSON number. private boolean isJSONNumeric(byte b) { switch (b) { - case '+': - case '-': - case '.': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case 'E': - case 'e': - return true; + case '+': + case '-': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 'E': + case 'e': + return true; } return false; } @@ -730,7 +706,7 @@ public class TJSONProtocol extends TProtocol { if (!isJSONNumeric(ch)) { break; } - strbld.append((char)reader_.read()); + strbld.append((char) reader_.read()); } return strbld.toString(); } @@ -747,10 +723,9 @@ public class TJSONProtocol extends TProtocol { } try { return Long.valueOf(str); - } - catch (NumberFormatException ex) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Bad data encounted in numeric data"); + } catch (NumberFormatException ex) { + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } @@ -761,25 +736,22 @@ public class TJSONProtocol extends TProtocol { if (reader_.peek() == QUOTE[0]) { TByteArrayOutputStream arr = readJSONString(true); double dub = Double.valueOf(arr.toString(StandardCharsets.UTF_8)); - if (!context_.escapeNum() && !Double.isNaN(dub) - && !Double.isInfinite(dub)) { + if (!context_.escapeNum() && !Double.isNaN(dub) && !Double.isInfinite(dub)) { // Throw exception -- we should not be in a string in this case - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Numeric data unexpectedly quoted"); + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted"); } return dub; - } - else { + } else { if (context_.escapeNum()) { // This will throw - we should have had a quote if escapeNum == true readJSONSyntaxChar(QUOTE); } try { return Double.valueOf(readJSONNumericChars()); - } - catch (NumberFormatException ex) { - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Bad data encounted in numeric data"); + } catch (NumberFormatException ex) { + throw new TProtocolException( + TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } } @@ -811,7 +783,7 @@ public class TJSONProtocol extends TProtocol { size += len - 1; } // Sadly we must copy the byte[] (any way around this?) - byte [] result = new byte[size]; + byte[] result = new byte[size]; System.arraycopy(b, 0, result, 0, size); return result; } @@ -843,8 +815,8 @@ public class TJSONProtocol extends TProtocol { resetContext(); // THRIFT-3743 readJSONArrayStart(); if (readJSONInteger() != VERSION) { - throw new TProtocolException(TProtocolException.BAD_VERSION, - "Message contained bad version."); + throw new TProtocolException( + TProtocolException.BAD_VERSION, "Message contained bad version."); } String name = readJSONString(false).toString(StandardCharsets.UTF_8); byte type = (byte) readJSONInteger(); @@ -875,8 +847,7 @@ public class TJSONProtocol extends TProtocol { short id = 0; if (ch == RBRACE[0]) { type = TType.STOP; - } - else { + } else { id = (short) readJSONInteger(); readJSONObjectStart(); type = getTypeIDForTypeName(readJSONString(false).get()); @@ -894,7 +865,7 @@ public class TJSONProtocol extends TProtocol { readJSONArrayStart(); byte keyType = getTypeIDForTypeName(readJSONString(false).get()); byte valueType = getTypeIDForTypeName(readJSONString(false).get()); - int size = (int)readJSONInteger(); + int size = (int) readJSONInteger(); readJSONObjectStart(); TMap map = new TMap(keyType, valueType, size); @@ -912,7 +883,7 @@ public class TJSONProtocol extends TProtocol { public TList readListBegin() throws TException { readJSONArrayStart(); byte elemType = getTypeIDForTypeName(readJSONString(false).get()); - int size = (int)readJSONInteger(); + int size = (int) readJSONInteger(); TList list = new TList(elemType, size); checkReadBytesAvailable(list); @@ -928,7 +899,7 @@ public class TJSONProtocol extends TProtocol { public TSet readSetBegin() throws TException { readJSONArrayStart(); byte elemType = getTypeIDForTypeName(readJSONString(false).get()); - int size = (int)readJSONInteger(); + int size = (int) readJSONInteger(); TSet set = new TSet(elemType, size); checkReadBytesAvailable(set); @@ -980,28 +951,37 @@ public class TJSONProtocol extends TProtocol { return ByteBuffer.wrap(readJSONBase64()); } - /** - * - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TTransportException { - switch (type) - { - case 0: return 0; // Stop - case 1: return 0; // Void - case 2: return 1; // Bool - case 3: return 1; // Byte - case 4: return 1; // Double - case 6: return 1; // I16 - case 8: return 1; // I32 - case 10: return 1;// I64 - case 11: return 2; // string length - case 12: return 2; // empty struct - case 13: return 2; // element count Map - case 14: return 2; // element count Set - case 15: return 2; // element count List - default: throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool + case 3: + return 1; // Byte + case 4: + return 1; // Double + case 6: + return 1; // I16 + case 8: + return 1; // I32 + case 10: + return 1; // I64 + case 11: + return 2; // string length + case 12: + return 2; // empty struct + case 13: + return 2; // element count Map + case 14: + return 2; // element count Set + case 15: + return 2; // element count List + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); } } - } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TList.java b/lib/java/src/main/java/org/apache/thrift/protocol/TList.java index 0d36e83d9..25368916d 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TList.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TList.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates list metadata. - * - */ +/** Helper class that encapsulates list metadata. */ public final class TList { public TList() { this(TType.STOP, 0); @@ -34,5 +31,5 @@ public final class TList { } public final byte elemType; - public final int size; + public final int size; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java index 20881f7ac..72dace2cd 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMap.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates map metadata. - * - */ +/** Helper class that encapsulates map metadata. */ public final class TMap { public TMap() { this(TType.STOP, TType.STOP, 0); @@ -34,7 +31,7 @@ public final class TMap { size = s; } - public final byte keyType; - public final byte valueType; - public final int size; + public final byte keyType; + public final byte valueType; + public final int size; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java index f13b8ca50..a5468d737 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMessage.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates struct metadata. - * - */ +/** Helper class that encapsulates struct metadata. */ public final class TMessage { public TMessage() { this("", TType.STOP, 0); @@ -55,22 +52,15 @@ public final class TMessage { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; TMessage other = (TMessage) obj; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (seqid != other.seqid) - return false; - if (type != other.type) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; + if (seqid != other.seqid) return false; + if (type != other.type) return false; return true; } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java index aa3f93177..a768cb6ae 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMessageType.java @@ -19,12 +19,9 @@ package org.apache.thrift.protocol; -/** - * Message type constants in the Thrift protocol. - * - */ +/** Message type constants in the Thrift protocol. */ public final class TMessageType { - public static final byte CALL = 1; + public static final byte CALL = 1; public static final byte REPLY = 2; public static final byte EXCEPTION = 3; public static final byte ONEWAY = 4; diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java index 0ea566ba6..09343303e 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TMultiplexedProtocol.java @@ -22,72 +22,67 @@ package org.apache.thrift.protocol; import org.apache.thrift.TException; /** - * <code>TMultiplexedProtocol</code> is a protocol-independent concrete decorator - * that allows a Thrift client to communicate with a multiplexing Thrift server, - * by prepending the service name to the function name during function calls. + * <code>TMultiplexedProtocol</code> is a protocol-independent concrete decorator that allows a + * Thrift client to communicate with a multiplexing Thrift server, by prepending the service name to + * the function name during function calls. * - * <p>NOTE: THIS IS NOT USED BY SERVERS. On the server, use {@link org.apache.thrift.TMultiplexedProcessor TMultiplexedProcessor} to handle requests - * from a multiplexing client. + * <p>NOTE: THIS IS NOT USED BY SERVERS. On the server, use {@link + * org.apache.thrift.TMultiplexedProcessor TMultiplexedProcessor} to handle requests from a + * multiplexing client. * * <p>This example uses a single socket transport to invoke two services: * - * <pre> - * {@code - * TSocket transport = new TSocket("localhost", 9090); - * transport.open(); + * <pre>{@code + * TSocket transport = new TSocket("localhost", 9090); + * transport.open(); * - * TBinaryProtocol protocol = new TBinaryProtocol(transport); + * TBinaryProtocol protocol = new TBinaryProtocol(transport); * - * TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "Calculator"); - * Calculator.Client service = new Calculator.Client(mp); + * TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "Calculator"); + * Calculator.Client service = new Calculator.Client(mp); * - * TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "WeatherReport"); - * WeatherReport.Client service2 = new WeatherReport.Client(mp2); + * TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "WeatherReport"); + * WeatherReport.Client service2 = new WeatherReport.Client(mp2); * - * System.out.println(service.add(2,2)); - * System.out.println(service2.getTemperature()); - * } - * </pre> + * System.out.println(service.add(2,2)); + * System.out.println(service2.getTemperature()); + * }</pre> * * @see org.apache.thrift.protocol.TProtocolDecorator */ public class TMultiplexedProtocol extends TProtocolDecorator { - /** Used to delimit the service name from the function name */ - public static final String SEPARATOR = ":"; + /** Used to delimit the service name from the function name */ + public static final String SEPARATOR = ":"; - private final String SERVICE_NAME; + private final String SERVICE_NAME; - /** - * Wrap the specified protocol, allowing it to be used to communicate with a - * multiplexing server. The <code>serviceName</code> is required as it is - * prepended to the message header so that the multiplexing server can broker - * the function call to the proper service. - * - * @param protocol Your communication protocol of choice, e.g. <code>TBinaryProtocol</code>. - * @param serviceName The service name of the service communicating via this protocol. - */ - public TMultiplexedProtocol(TProtocol protocol, String serviceName) { - super(protocol); - SERVICE_NAME = serviceName; - } + /** + * Wrap the specified protocol, allowing it to be used to communicate with a multiplexing server. + * The <code>serviceName</code> is required as it is prepended to the message header so that the + * multiplexing server can broker the function call to the proper service. + * + * @param protocol Your communication protocol of choice, e.g. <code>TBinaryProtocol</code>. + * @param serviceName The service name of the service communicating via this protocol. + */ + public TMultiplexedProtocol(TProtocol protocol, String serviceName) { + super(protocol); + SERVICE_NAME = serviceName; + } - /** - * Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR. - * - * @param tMessage The original message. - * @throws TException Passed through from wrapped <code>TProtocol</code> instance. - */ - @Override - public void writeMessageBegin(TMessage tMessage) throws TException { - if (tMessage.type == TMessageType.CALL || tMessage.type == TMessageType.ONEWAY) { - super.writeMessageBegin(new TMessage( - SERVICE_NAME + SEPARATOR + tMessage.name, - tMessage.type, - tMessage.seqid - )); - } else { - super.writeMessageBegin(tMessage); - } + /** + * Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR. + * + * @param tMessage The original message. + * @throws TException Passed through from wrapped <code>TProtocol</code> instance. + */ + @Override + public void writeMessageBegin(TMessage tMessage) throws TException { + if (tMessage.type == TMessageType.CALL || tMessage.type == TMessageType.ONEWAY) { + super.writeMessageBegin( + new TMessage(SERVICE_NAME + SEPARATOR + tMessage.name, tMessage.type, tMessage.seqid)); + } else { + super.writeMessageBegin(tMessage); } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java index 3589b64e3..a55d9f7ed 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocol.java @@ -20,40 +20,28 @@ package org.apache.thrift.protocol; import java.nio.ByteBuffer; - import org.apache.thrift.TException; import org.apache.thrift.partial.TFieldData; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.transport.TTransport; -/** - * Protocol interface definition. - * - */ +/** Protocol interface definition. */ public abstract class TProtocol { - /** - * Prevent direct instantiation - */ + /** Prevent direct instantiation */ @SuppressWarnings("unused") private TProtocol() {} - /** - * Transport - */ + /** Transport */ protected TTransport trans_; - /** - * Constructor - */ + /** Constructor */ protected TProtocol(TTransport trans) { trans_ = trans; } - /** - * Transport accessor - */ + /** Transport accessor */ public TTransport getTransport() { return trans_; } @@ -73,16 +61,15 @@ public abstract class TProtocol { /** * Return - * @param type Returns the minimum amount of bytes needed to store the smallest possible instance of TType. + * + * @param type Returns the minimum amount of bytes needed to store the smallest possible instance + * of TType. * @return * @throws TException */ public abstract int getMinSerializedSize(byte type) throws TException; - /** - * Writing methods. - */ - + /** Writing methods. */ public abstract void writeMessageBegin(TMessage message) throws TException; public abstract void writeMessageEnd() throws TException; @@ -125,10 +112,7 @@ public abstract class TProtocol { public abstract void writeBinary(ByteBuffer buf) throws TException; - /** - * Reading methods. - */ - + /** Reading methods. */ public abstract TMessage readMessageBegin() throws TException; public abstract void readMessageEnd() throws TException; @@ -170,14 +154,12 @@ public abstract class TProtocol { public abstract ByteBuffer readBinary() throws TException; /** - * Reset any internal state back to a blank slate. This method only needs to - * be implemented for stateful protocols. + * Reset any internal state back to a blank slate. This method only needs to be implemented for + * stateful protocols. */ public void reset() {} - /** - * Scheme accessor - */ + /** Scheme accessor */ public Class<? extends IScheme> getScheme() { return StandardScheme.class; } @@ -277,10 +259,9 @@ public abstract class TProtocol { /** * The default implementation of all skip() methods calls the corresponding read() method. - * Protocols that derive from this class are strongly encouraged to provide - * a more efficient alternative. + * Protocols that derive from this class are strongly encouraged to provide a more efficient + * alternative. */ - protected void skipBool() throws TException { this.readBool(); } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java index 9d109622f..3b3205a98 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolDecorator.java @@ -19,205 +19,204 @@ package org.apache.thrift.protocol; -import org.apache.thrift.TException; - import java.nio.ByteBuffer; +import org.apache.thrift.TException; /** - * <code>TProtocolDecorator</code> forwards all requests to an enclosed - * <code>TProtocol</code> instance, providing a way to author concise - * concrete decorator subclasses. While it has no abstract methods, it - * is marked abstract as a reminder that by itself, it does not modify - * the behaviour of the enclosed <code>TProtocol</code>. + * <code>TProtocolDecorator</code> forwards all requests to an enclosed <code>TProtocol</code> + * instance, providing a way to author concise concrete decorator subclasses. While it has no + * abstract methods, it is marked abstract as a reminder that by itself, it does not modify the + * behaviour of the enclosed <code>TProtocol</code>. * - * <p>See p.175 of Design Patterns (by Gamma et al.)</p> + * <p>See p.175 of Design Patterns (by Gamma et al.) * * @see org.apache.thrift.protocol.TMultiplexedProtocol */ public abstract class TProtocolDecorator extends TProtocol { - private final TProtocol concreteProtocol; + private final TProtocol concreteProtocol; - /** - * Encloses the specified protocol. - * @param protocol All operations will be forward to this protocol. Must be non-null. - */ - public TProtocolDecorator(TProtocol protocol) { - super(protocol.getTransport()); - concreteProtocol = protocol; - } + /** + * Encloses the specified protocol. + * + * @param protocol All operations will be forward to this protocol. Must be non-null. + */ + public TProtocolDecorator(TProtocol protocol) { + super(protocol.getTransport()); + concreteProtocol = protocol; + } - public void writeMessageBegin(TMessage tMessage) throws TException { - concreteProtocol.writeMessageBegin(tMessage); - } + public void writeMessageBegin(TMessage tMessage) throws TException { + concreteProtocol.writeMessageBegin(tMessage); + } - public void writeMessageEnd() throws TException { - concreteProtocol.writeMessageEnd(); - } + public void writeMessageEnd() throws TException { + concreteProtocol.writeMessageEnd(); + } - public void writeStructBegin(TStruct tStruct) throws TException { - concreteProtocol.writeStructBegin(tStruct); - } + public void writeStructBegin(TStruct tStruct) throws TException { + concreteProtocol.writeStructBegin(tStruct); + } - public void writeStructEnd() throws TException { - concreteProtocol.writeStructEnd(); - } + public void writeStructEnd() throws TException { + concreteProtocol.writeStructEnd(); + } - public void writeFieldBegin(TField tField) throws TException { - concreteProtocol.writeFieldBegin(tField); - } + public void writeFieldBegin(TField tField) throws TException { + concreteProtocol.writeFieldBegin(tField); + } - public void writeFieldEnd() throws TException { - concreteProtocol.writeFieldEnd(); - } + public void writeFieldEnd() throws TException { + concreteProtocol.writeFieldEnd(); + } - public void writeFieldStop() throws TException { - concreteProtocol.writeFieldStop(); - } + public void writeFieldStop() throws TException { + concreteProtocol.writeFieldStop(); + } - public void writeMapBegin(TMap tMap) throws TException { - concreteProtocol.writeMapBegin(tMap); - } + public void writeMapBegin(TMap tMap) throws TException { + concreteProtocol.writeMapBegin(tMap); + } - public void writeMapEnd() throws TException { - concreteProtocol.writeMapEnd(); - } + public void writeMapEnd() throws TException { + concreteProtocol.writeMapEnd(); + } - public void writeListBegin(TList tList) throws TException { - concreteProtocol.writeListBegin(tList); - } + public void writeListBegin(TList tList) throws TException { + concreteProtocol.writeListBegin(tList); + } - public void writeListEnd() throws TException { - concreteProtocol.writeListEnd(); - } + public void writeListEnd() throws TException { + concreteProtocol.writeListEnd(); + } - public void writeSetBegin(TSet tSet) throws TException { - concreteProtocol.writeSetBegin(tSet); - } + public void writeSetBegin(TSet tSet) throws TException { + concreteProtocol.writeSetBegin(tSet); + } - public void writeSetEnd() throws TException { - concreteProtocol.writeSetEnd(); - } + public void writeSetEnd() throws TException { + concreteProtocol.writeSetEnd(); + } - public void writeBool(boolean b) throws TException { - concreteProtocol.writeBool(b); - } + public void writeBool(boolean b) throws TException { + concreteProtocol.writeBool(b); + } - public void writeByte(byte b) throws TException { - concreteProtocol.writeByte(b); - } + public void writeByte(byte b) throws TException { + concreteProtocol.writeByte(b); + } - public void writeI16(short i) throws TException { - concreteProtocol.writeI16(i); - } + public void writeI16(short i) throws TException { + concreteProtocol.writeI16(i); + } - public void writeI32(int i) throws TException { - concreteProtocol.writeI32(i); - } - - public void writeI64(long l) throws TException { - concreteProtocol.writeI64(l); - } - - public void writeDouble(double v) throws TException { - concreteProtocol.writeDouble(v); - } - - public void writeString(String s) throws TException { - concreteProtocol.writeString(s); - } - - public void writeBinary(ByteBuffer buf) throws TException { - concreteProtocol.writeBinary(buf); - } - - public TMessage readMessageBegin() throws TException { - return concreteProtocol.readMessageBegin(); - } - - public void readMessageEnd() throws TException { - concreteProtocol.readMessageEnd(); - } - - public TStruct readStructBegin() throws TException { - return concreteProtocol.readStructBegin(); - } - - public void readStructEnd() throws TException { - concreteProtocol.readStructEnd(); - } - - public TField readFieldBegin() throws TException { - return concreteProtocol.readFieldBegin(); - } - - public void readFieldEnd() throws TException { - concreteProtocol.readFieldEnd(); - } - - public TMap readMapBegin() throws TException { - return concreteProtocol.readMapBegin(); - } - - public void readMapEnd() throws TException { - concreteProtocol.readMapEnd(); - } - - public TList readListBegin() throws TException { - return concreteProtocol.readListBegin(); - } - - public void readListEnd() throws TException { - concreteProtocol.readListEnd(); - } - - public TSet readSetBegin() throws TException { - return concreteProtocol.readSetBegin(); - } - - public void readSetEnd() throws TException { - concreteProtocol.readSetEnd(); - } - - public boolean readBool() throws TException { - return concreteProtocol.readBool(); - } - - public byte readByte() throws TException { - return concreteProtocol.readByte(); - } - - public short readI16() throws TException { - return concreteProtocol.readI16(); - } - - public int readI32() throws TException { - return concreteProtocol.readI32(); - } - - public long readI64() throws TException { - return concreteProtocol.readI64(); - } - - public double readDouble() throws TException { - return concreteProtocol.readDouble(); - } - - public String readString() throws TException { - return concreteProtocol.readString(); - } - - public ByteBuffer readBinary() throws TException { - return concreteProtocol.readBinary(); - } - - /** - * - * @param type Returns the minimum amount of bytes needed to store the smallest possible instance of TType. - * @return - * @throws TException - */ - public int getMinSerializedSize(byte type) throws TException { - return concreteProtocol.getMinSerializedSize(type); - } + public void writeI32(int i) throws TException { + concreteProtocol.writeI32(i); + } + + public void writeI64(long l) throws TException { + concreteProtocol.writeI64(l); + } + + public void writeDouble(double v) throws TException { + concreteProtocol.writeDouble(v); + } + + public void writeString(String s) throws TException { + concreteProtocol.writeString(s); + } + + public void writeBinary(ByteBuffer buf) throws TException { + concreteProtocol.writeBinary(buf); + } + + public TMessage readMessageBegin() throws TException { + return concreteProtocol.readMessageBegin(); + } + + public void readMessageEnd() throws TException { + concreteProtocol.readMessageEnd(); + } + + public TStruct readStructBegin() throws TException { + return concreteProtocol.readStructBegin(); + } + + public void readStructEnd() throws TException { + concreteProtocol.readStructEnd(); + } + + public TField readFieldBegin() throws TException { + return concreteProtocol.readFieldBegin(); + } + + public void readFieldEnd() throws TException { + concreteProtocol.readFieldEnd(); + } + + public TMap readMapBegin() throws TException { + return concreteProtocol.readMapBegin(); + } + + public void readMapEnd() throws TException { + concreteProtocol.readMapEnd(); + } + + public TList readListBegin() throws TException { + return concreteProtocol.readListBegin(); + } + + public void readListEnd() throws TException { + concreteProtocol.readListEnd(); + } + + public TSet readSetBegin() throws TException { + return concreteProtocol.readSetBegin(); + } + + public void readSetEnd() throws TException { + concreteProtocol.readSetEnd(); + } + + public boolean readBool() throws TException { + return concreteProtocol.readBool(); + } + + public byte readByte() throws TException { + return concreteProtocol.readByte(); + } + + public short readI16() throws TException { + return concreteProtocol.readI16(); + } + + public int readI32() throws TException { + return concreteProtocol.readI32(); + } + + public long readI64() throws TException { + return concreteProtocol.readI64(); + } + + public double readDouble() throws TException { + return concreteProtocol.readDouble(); + } + + public String readString() throws TException { + return concreteProtocol.readString(); + } + + public ByteBuffer readBinary() throws TException { + return concreteProtocol.readBinary(); + } + + /** + * @param type Returns the minimum amount of bytes needed to store the smallest possible instance + * of TType. + * @return + * @throws TException + */ + public int getMinSerializedSize(byte type) throws TException { + return concreteProtocol.getMinSerializedSize(type); + } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java index 870f1b939..3d645c47f 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolException.java @@ -21,13 +21,9 @@ package org.apache.thrift.protocol; import org.apache.thrift.TException; -/** - * Protocol exceptions. - * - */ +/** Protocol exceptions. */ public class TProtocolException extends TException { - private static final long serialVersionUID = 1L; public static final int UNKNOWN = 0; public static final int INVALID_DATA = 1; @@ -78,5 +74,4 @@ public class TProtocolException extends TException { public int getType() { return type_; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java index b72e87b38..b99725320 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolFactory.java @@ -20,12 +20,9 @@ package org.apache.thrift.protocol; import java.io.Serializable; - import org.apache.thrift.transport.TTransport; -/** - * Factory interface for constructing protocol instances. - */ +/** Factory interface for constructing protocol instances. */ public interface TProtocolFactory extends Serializable { public TProtocol getProtocol(TTransport trans); } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java index cdaa30b87..86cfb459a 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TProtocolUtil.java @@ -21,29 +21,20 @@ package org.apache.thrift.protocol; import org.apache.thrift.TException; -/** - * Utility class with static methods for interacting with protocol data - * streams. - * - */ +/** Utility class with static methods for interacting with protocol data streams. */ public class TProtocolUtil { - /** - * The maximum recursive depth the skip() function will traverse before - * throwing a TException. - */ + /** The maximum recursive depth the skip() function will traverse before throwing a TException. */ private static int maxSkipDepth = Integer.MAX_VALUE; /** - * Specifies the maximum recursive depth that the skip function will - * traverse before throwing a TException. This is a global setting, so - * any call to skip in this JVM will enforce this value. + * Specifies the maximum recursive depth that the skip function will traverse before throwing a + * TException. This is a global setting, so any call to skip in this JVM will enforce this value. * - * @param depth the maximum recursive depth. A value of 2 would allow - * the skip function to skip a structure or collection with basic children, - * but it would not permit skipping a struct that had a field containing - * a child struct. A value of 1 would only allow skipping of simple - * types and empty structs/collections. + * @param depth the maximum recursive depth. A value of 2 would allow the skip function to skip a + * structure or collection with basic children, but it would not permit skipping a struct that + * had a field containing a child struct. A value of 1 would only allow skipping of simple + * types and empty structs/collections. */ public static void setMaxSkipDepth(int depth) { maxSkipDepth = depth; @@ -52,24 +43,22 @@ public class TProtocolUtil { /** * Skips over the next data element from the provided input TProtocol object. * - * @param prot the protocol object to read from - * @param type the next value will be interpreted as this TType value. + * @param prot the protocol object to read from + * @param type the next value will be interpreted as this TType value. */ - public static void skip(TProtocol prot, byte type) - throws TException { + public static void skip(TProtocol prot, byte type) throws TException { skip(prot, type, maxSkipDepth); } /** * Skips over the next data element from the provided input TProtocol object. * - * @param prot the protocol object to read from - * @param type the next value will be interpreted as this TType value. - * @param maxDepth this function will only skip complex objects to this - * recursive depth, to prevent Java stack overflow. + * @param prot the protocol object to read from + * @param type the next value will be interpreted as this TType value. + * @param maxDepth this function will only skip complex objects to this recursive depth, to + * prevent Java stack overflow. */ - public static void skip(TProtocol prot, byte type, int maxDepth) - throws TException { + public static void skip(TProtocol prot, byte type, int maxDepth) throws TException { if (maxDepth <= 0) { throw new TException("Maximum skip depth exceeded"); } @@ -141,19 +130,16 @@ public class TProtocolUtil { break; default: - throw new TProtocolException(TProtocolException.INVALID_DATA, - "Unrecognized type " + type); + throw new TProtocolException(TProtocolException.INVALID_DATA, "Unrecognized type " + type); } } /** * Attempt to determine the protocol used to serialize some data. * - * The guess is based on known specificities of supported protocols. - * In some cases, no guess can be done, in that case we return the - * fallback TProtocolFactory. - * To be certain to correctly detect the protocol, the first encoded - * field should have a field id < 256 + * <p>The guess is based on known specificities of supported protocols. In some cases, no guess + * can be done, in that case we return the fallback TProtocolFactory. To be certain to correctly + * detect the protocol, the first encoded field should have a field id < 256 * * @param data The serialized data to guess the protocol for. * @param fallback The TProtocol to return if no guess can be made. diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java b/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java index 38be9a991..1d1651e7f 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TSet.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates set metadata. - * - */ +/** Helper class that encapsulates set metadata. */ public final class TSet { public TSet() { this(TType.STOP, 0); @@ -38,5 +35,5 @@ public final class TSet { } public final byte elemType; - public final int size; + public final int size; } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java index 6a3ee55d9..506572b59 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java @@ -22,7 +22,6 @@ package org.apache.thrift.protocol; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Stack; - import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; @@ -30,16 +29,12 @@ import org.apache.thrift.transport.TTransportException; /** * JSON protocol implementation for thrift. * - * This protocol is write-only and produces a simple output format - * suitable for parsing by scripting languages. It should not be - * confused with the full-featured TJSONProtocol. - * + * <p>This protocol is write-only and produces a simple output format suitable for parsing by + * scripting languages. It should not be confused with the full-featured TJSONProtocol. */ public class TSimpleJSONProtocol extends TProtocol { - /** - * Factory - */ + /** Factory */ public static class Factory implements TProtocolFactory { public TProtocol getProtocol(TTransport trans) { return new TSimpleJSONProtocol(trans); @@ -67,10 +62,10 @@ public class TSimpleJSONProtocol extends TProtocol { protected class Context { protected void write() throws TException {} - /** - * Returns whether the current value is a key in a map - */ - protected boolean isMapKey() { return false; } + /** Returns whether the current value is a key in a map */ + protected boolean isMapKey() { + return false; + } } protected class ListContext extends Context { @@ -118,52 +113,39 @@ public class TSimpleJSONProtocol extends TProtocol { protected final Context BASE_CONTEXT = new Context(); - /** - * Stack of nested contexts that we may be in. - */ + /** Stack of nested contexts that we may be in. */ protected Stack<Context> writeContextStack_ = new Stack<Context>(); - /** - * Current context that we are in - */ + /** Current context that we are in */ protected Context writeContext_ = BASE_CONTEXT; - /** - * Push a new write context onto the stack. - */ + /** Push a new write context onto the stack. */ protected void pushWriteContext(Context c) { writeContextStack_.push(writeContext_); writeContext_ = c; } - /** - * Pop the last write context off the stack - */ + /** Pop the last write context off the stack */ protected void popWriteContext() { writeContext_ = writeContextStack_.pop(); } - /** - * Reset the write context stack to its initial state. - */ + /** Reset the write context stack to its initial state. */ protected void resetWriteContext() { while (!writeContextStack_.isEmpty()) { popWriteContext(); } } - /** - * Used to make sure that we are not encountering a map whose keys are containers - */ + /** Used to make sure that we are not encountering a map whose keys are containers */ protected void assertContextIsNotMapKey(String invalidKeyType) throws CollectionMapKeyException { if (writeContext_.isMapKey()) { - throw new CollectionMapKeyException("Cannot serialize a map with keys that are of type " + invalidKeyType); + throw new CollectionMapKeyException( + "Cannot serialize a map with keys that are of type " + invalidKeyType); } } - /** - * Constructor - */ + /** Constructor */ public TSimpleJSONProtocol(TTransport trans) { super(trans); } @@ -256,7 +238,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeBool(boolean b) throws TException { - writeByte(b ? (byte)1 : (byte)0); + writeByte(b ? (byte) 1 : (byte) 0); } @Override @@ -271,7 +253,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeI32(int i32) throws TException { - if(writeContext_.isMapKey()) { + if (writeContext_.isMapKey()) { writeString(Integer.toString(i32)); } else { writeContext_.write(); @@ -286,7 +268,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeI64(long i64) throws TException { - if(writeContext_.isMapKey()) { + if (writeContext_.isMapKey()) { writeString(Long.toString(i64)); } else { writeContext_.write(); @@ -296,7 +278,7 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeDouble(double dub) throws TException { - if(writeContext_.isMapKey()) { + if (writeContext_.isMapKey()) { writeString(Double.toString(dub)); } else { writeContext_.write(); @@ -313,45 +295,45 @@ public class TSimpleJSONProtocol extends TProtocol { for (int i = 0; i < length; ++i) { char c = str.charAt(i); switch (c) { - case '"': - case '\\': - escape.append('\\'); - escape.append(c); - break; - case '\b': - escape.append('\\'); - escape.append('b'); - break; - case '\f': - escape.append('\\'); - escape.append('f'); - break; - case '\n': - escape.append('\\'); - escape.append('n'); - break; - case '\r': - escape.append('\\'); - escape.append('r'); - break; - case '\t': - escape.append('\\'); - escape.append('t'); - break; - default: - // Control characters! According to JSON RFC u0020 (space) - if (c < ' ') { - String hex = Integer.toHexString(c); + case '"': + case '\\': escape.append('\\'); - escape.append('u'); - for (int j = 4; j > hex.length(); --j) { - escape.append('0'); - } - escape.append(hex); - } else { escape.append(c); - } - break; + break; + case '\b': + escape.append('\\'); + escape.append('b'); + break; + case '\f': + escape.append('\\'); + escape.append('f'); + break; + case '\n': + escape.append('\\'); + escape.append('n'); + break; + case '\r': + escape.append('\\'); + escape.append('r'); + break; + case '\t': + escape.append('\\'); + escape.append('t'); + break; + default: + // Control characters! According to JSON RFC u0020 (space) + if (c < ' ') { + String hex = Integer.toHexString(c); + escape.append('\\'); + escape.append('u'); + for (int j = 4; j > hex.length(); --j) { + escape.append('0'); + } + escape.append(hex); + } else { + escape.append(c); + } + break; } } escape.append(QUOTE); @@ -361,19 +343,20 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void writeBinary(ByteBuffer bin) throws TException { // TODO(mcslee): Fix this - writeString(new String(bin.array(), bin.position() + bin.arrayOffset(), - bin.limit() - bin.position() - bin.arrayOffset(), - StandardCharsets.UTF_8)); + writeString( + new String( + bin.array(), + bin.position() + bin.arrayOffset(), + bin.limit() - bin.position() - bin.arrayOffset(), + StandardCharsets.UTF_8)); } /** * Reading methods. * - * simplejson is not meant to be read back into thrift - * - see http://wiki.apache.org/thrift/ThriftUsageJava - * - use JSON instead + * <p>simplejson is not meant to be read back into thrift - see + * http://wiki.apache.org/thrift/ThriftUsageJava - use JSON instead */ - @Override public TMessage readMessageBegin() throws TException { throw new TException("Not implemented"); @@ -381,7 +364,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readMessageEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TStruct readStructBegin() throws TException { @@ -390,7 +374,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readStructEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TField readFieldBegin() throws TException { @@ -399,7 +384,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readFieldEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TMap readMapBegin() throws TException { @@ -408,7 +394,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readMapEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TList readListBegin() throws TException { @@ -417,7 +404,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readListEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public TSet readSetBegin() throws TException { @@ -426,7 +414,8 @@ public class TSimpleJSONProtocol extends TProtocol { @Override public void readSetEnd() throws TException { - throw new TException("Not implemented");} + throw new TException("Not implemented"); + } @Override public boolean readBool() throws TException { @@ -478,27 +467,37 @@ public class TSimpleJSONProtocol extends TProtocol { } } - /** - * - * Return the minimum number of bytes a type will consume on the wire - */ + /** Return the minimum number of bytes a type will consume on the wire */ public int getMinSerializedSize(byte type) throws TException { - switch (type) - { - case 0: return 0; // Stop - case 1: return 0; // Void - case 2: return 1; // Bool - case 3: return 1; // Byte - case 4: return 1; // Double - case 6: return 1; // I16 - case 8: return 1; // I32 - case 10: return 1;// I64 - case 11: return 2; // string length - case 12: return 2; // empty struct - case 13: return 2; // element count Map - case 14: return 2; // element count Set - case 15: return 2; // element count List - default: throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); + switch (type) { + case 0: + return 0; // Stop + case 1: + return 0; // Void + case 2: + return 1; // Bool + case 3: + return 1; // Byte + case 4: + return 1; // Double + case 6: + return 1; // I16 + case 8: + return 1; // I32 + case 10: + return 1; // I64 + case 11: + return 2; // string length + case 12: + return 2; // empty struct + case 13: + return 2; // element count Map + case 14: + return 2; // element count Set + case 15: + return 2; // element count List + default: + throw new TTransportException(TTransportException.UNKNOWN, "unrecognized type code"); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java b/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java index a0f79012a..559c61413 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TStruct.java @@ -19,10 +19,7 @@ package org.apache.thrift.protocol; -/** - * Helper class that encapsulates struct metadata. - * - */ +/** Helper class that encapsulates struct metadata. */ public final class TStruct { public TStruct() { this(""); diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java b/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java index 67d00edb7..de47d6f0a 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TTupleProtocol.java @@ -19,7 +19,6 @@ package org.apache.thrift.protocol; import java.util.BitSet; - import org.apache.thrift.TException; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.TupleScheme; @@ -51,7 +50,7 @@ public final class TTupleProtocol extends TCompactProtocol { } public BitSet readBitSet(int i) throws TException { - int length = (int) Math.ceil(i/8.0); + int length = (int) Math.ceil(i / 8.0); byte[] bytes = new byte[length]; for (int j = 0; j < length; j++) { bytes[j] = readByte(); @@ -60,10 +59,7 @@ public final class TTupleProtocol extends TCompactProtocol { return bs; } - /** - * Returns a bitset containing the values in bytes. The byte-ordering must be - * big-endian. - */ + /** Returns a bitset containing the values in bytes. The byte-ordering must be big-endian. */ public static BitSet fromByteArray(byte[] bytes) { BitSet bits = new BitSet(); for (int i = 0; i < bytes.length * 8; i++) { @@ -75,18 +71,17 @@ public final class TTupleProtocol extends TCompactProtocol { } /** - * Returns a byte array of at least length 1. The most significant bit in the - * result is guaranteed not to be a 1 (since BitSet does not support sign - * extension). The byte-ordering of the result is big-endian which means the - * most significant bit is in element 0. The bit at index 0 of the bit set is - * assumed to be the least significant bit. + * Returns a byte array of at least length 1. The most significant bit in the result is guaranteed + * not to be a 1 (since BitSet does not support sign extension). The byte-ordering of the result + * is big-endian which means the most significant bit is in element 0. The bit at index 0 of the + * bit set is assumed to be the least significant bit. * * @param bits * @param vectorWidth * @return a byte array of at least length 1 */ public static byte[] toByteArray(BitSet bits, int vectorWidth) { - byte[] bytes = new byte[(int) Math.ceil(vectorWidth/8.0)]; + byte[] bytes = new byte[(int) Math.ceil(vectorWidth / 8.0)]; for (int i = 0; i < bits.length(); i++) { if (bits.get(i)) { bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8); @@ -116,6 +111,8 @@ public final class TTupleProtocol extends TCompactProtocol { } public void readMapEnd() throws TException {} + public void readListEnd() throws TException {} + public void readSetEnd() throws TException {} } diff --git a/lib/java/src/main/java/org/apache/thrift/protocol/TType.java b/lib/java/src/main/java/org/apache/thrift/protocol/TType.java index c3c1a0abd..4b70bb2b7 100644 --- a/lib/java/src/main/java/org/apache/thrift/protocol/TType.java +++ b/lib/java/src/main/java/org/apache/thrift/protocol/TType.java @@ -19,22 +19,20 @@ package org.apache.thrift.protocol; -/** - * Type constants in the Thrift protocol. - */ +/** Type constants in the Thrift protocol. */ public final class TType { - public static final byte STOP = 0; - public static final byte VOID = 1; - public static final byte BOOL = 2; - public static final byte BYTE = 3; + public static final byte STOP = 0; + public static final byte VOID = 1; + public static final byte BOOL = 2; + public static final byte BYTE = 3; public static final byte DOUBLE = 4; - public static final byte I16 = 6; - public static final byte I32 = 8; - public static final byte I64 = 10; + public static final byte I16 = 6; + public static final byte I32 = 8; + public static final byte I64 = 10; public static final byte STRING = 11; public static final byte STRUCT = 12; - public static final byte MAP = 13; - public static final byte SET = 14; - public static final byte LIST = 15; - public static final byte ENUM = 16; + public static final byte MAP = 13; + public static final byte SET = 14; + public static final byte LIST = 15; + public static final byte ENUM = 16; } diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java b/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java index aa3550705..c4a85b95e 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/IScheme.java @@ -22,8 +22,9 @@ import org.apache.thrift.TBase; public interface IScheme<T extends TBase> { - public void read(org.apache.thrift.protocol.TProtocol iproto, T struct) throws org.apache.thrift.TException; - - public void write(org.apache.thrift.protocol.TProtocol oproto, T struct) throws org.apache.thrift.TException; + public void read(org.apache.thrift.protocol.TProtocol iproto, T struct) + throws org.apache.thrift.TException; + public void write(org.apache.thrift.protocol.TProtocol oproto, T struct) + throws org.apache.thrift.TException; } diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java b/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java index 006a66805..e9d76406d 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java @@ -21,5 +21,4 @@ package org.apache.thrift.scheme; public interface SchemeFactory { public <S extends IScheme> S getScheme(); - } diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java b/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java index ffab04db6..2d2683bea 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/StandardScheme.java @@ -20,6 +20,4 @@ package org.apache.thrift.scheme; import org.apache.thrift.TBase; -public abstract class StandardScheme<T extends TBase> implements IScheme<T> { - -} +public abstract class StandardScheme<T extends TBase> implements IScheme<T> {} diff --git a/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java b/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java index 365242b11..0efa4cf2a 100644 --- a/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java +++ b/lib/java/src/main/java/org/apache/thrift/scheme/TupleScheme.java @@ -20,6 +20,4 @@ package org.apache.thrift.scheme; import org.apache.thrift.TBase; -public abstract class TupleScheme<T extends TBase> implements IScheme<T> { - -} +public abstract class TupleScheme<T extends TBase> implements IScheme<T> {} diff --git a/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java b/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java index beef954ef..44341d909 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/AbstractNonblockingServer.java @@ -19,37 +19,35 @@ package org.apache.thrift.server; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.SelectorProvider; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; import org.apache.thrift.TAsyncProcessor; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TException; import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TMemoryInputTransport; import org.apache.thrift.transport.TNonblockingServerTransport; import org.apache.thrift.transport.TNonblockingTransport; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; +import org.apache.thrift.transport.layered.TFramedTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.SelectorProvider; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Provides common methods and classes used by nonblocking TServer - * implementations. - */ +/** Provides common methods and classes used by nonblocking TServer implementations. */ public abstract class AbstractNonblockingServer extends TServer { protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); - public static abstract class AbstractNonblockingServerArgs<T extends AbstractNonblockingServerArgs<T>> extends AbstractServerArgs<T> { + public abstract static class AbstractNonblockingServerArgs< + T extends AbstractNonblockingServerArgs<T>> + extends AbstractServerArgs<T> { public long maxReadBufferBytes = 256 * 1024 * 1024; public AbstractNonblockingServerArgs(TNonblockingServerTransport transport) { @@ -59,15 +57,13 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * The maximum amount of memory we will allocate to client IO buffers at a - * time. Without this limit, the server will gladly allocate client buffers - * right into an out of memory exception, rather than waiting. + * The maximum amount of memory we will allocate to client IO buffers at a time. Without this + * limit, the server will gladly allocate client buffers right into an out of memory exception, + * rather than waiting. */ final long MAX_READ_BUFFER_BYTES; - /** - * How many bytes are currently allocated to read buffers. - */ + /** How many bytes are currently allocated to read buffers. */ final AtomicLong readBufferBytesAllocated = new AtomicLong(0); public AbstractNonblockingServer(AbstractNonblockingServerArgs args) { @@ -75,9 +71,7 @@ public abstract class AbstractNonblockingServer extends TServer { MAX_READ_BUFFER_BYTES = args.maxReadBufferBytes; } - /** - * Begin accepting connections and processing invocations. - */ + /** Begin accepting connections and processing invocations. */ public void serve() { // start any IO threads if (!startThreads()) { @@ -107,17 +101,13 @@ public abstract class AbstractNonblockingServer extends TServer { */ protected abstract boolean startThreads(); - /** - * A method that will block until when threads handling the serving have been - * shut down. - */ + /** A method that will block until when threads handling the serving have been shut down. */ protected abstract void waitForShutdown(); /** * Have the server transport start accepting connections. * - * @return true if we started listening successfully, false if something went - * wrong. + * @return true if we started listening successfully, false if something went wrong. */ protected boolean startListening() { try { @@ -129,27 +119,23 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Stop listening for connections. - */ + /** Stop listening for connections. */ protected void stopListening() { serverTransport_.close(); } /** - * Perform an invocation. This method could behave several different ways - - * invoke immediately inline, queue for separate execution, etc. + * Perform an invocation. This method could behave several different ways - invoke immediately + * inline, queue for separate execution, etc. * - * @return true if invocation was successfully requested, which is not a - * guarantee that invocation has completed. False if the request - * failed. + * @return true if invocation was successfully requested, which is not a guarantee that invocation + * has completed. False if the request failed. */ protected abstract boolean requestInvoke(FrameBuffer frameBuffer); /** - * An abstract thread that handles selecting on a set of transports and - * {@link FrameBuffer FrameBuffers} associated with selected keys - * corresponding to requests. + * An abstract thread that handles selecting on a set of transports and {@link FrameBuffer + * FrameBuffers} associated with selected keys corresponding to requests. */ protected abstract class AbstractSelectThread extends Thread { protected Selector selector; @@ -161,17 +147,15 @@ public abstract class AbstractNonblockingServer extends TServer { this.selector = SelectorProvider.provider().openSelector(); } - /** - * If the selector is blocked, wake it up. - */ + /** If the selector is blocked, wake it up. */ public void wakeupSelector() { selector.wakeup(); } /** - * Add FrameBuffer to the list of select interest changes and wake up the - * selector if it's blocked. When the select() call exits, it'll give the - * FrameBuffer a chance to change its interests. + * Add FrameBuffer to the list of select interest changes and wake up the selector if it's + * blocked. When the select() call exits, it'll give the FrameBuffer a chance to change its + * interests. */ public void requestSelectInterestChange(FrameBuffer frameBuffer) { synchronized (selectInterestChanges) { @@ -182,8 +166,8 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * Check to see if there are any FrameBuffers that have switched their - * interest type from read to write or vice versa. + * Check to see if there are any FrameBuffers that have switched their interest type from read + * to write or vice versa. */ protected void processInterestChanges() { synchronized (selectInterestChanges) { @@ -195,8 +179,8 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * Do the work required to read from a readable client. If the frame is - * fully read, then invoke the method call. + * Do the work required to read from a readable client. If the frame is fully read, then invoke + * the method call. */ protected void handleRead(SelectionKey key) { FrameBuffer buffer = (FrameBuffer) key.attachment(); @@ -213,9 +197,7 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Let a writable client get written, if there's data to be written. - */ + /** Let a writable client get written, if there's data to be written. */ protected void handleWrite(SelectionKey key) { FrameBuffer buffer = (FrameBuffer) key.attachment(); if (!buffer.write()) { @@ -223,9 +205,7 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Do connection-close cleanup on a given SelectionKey. - */ + /** Do connection-close cleanup on a given SelectionKey. */ protected void cleanupSelectionKey(SelectionKey key) { // remove the records from the two maps FrameBuffer buffer = (FrameBuffer) key.attachment(); @@ -238,9 +218,7 @@ public abstract class AbstractNonblockingServer extends TServer { } } // SelectThread - /** - * Possible states for the FrameBuffer state machine. - */ + /** Possible states for the FrameBuffer state machine. */ private enum FrameBufferState { // in the midst of reading the frame size off the wire READING_FRAME_SIZE, @@ -260,13 +238,12 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * Class that implements a sort of state machine around the interaction with a - * client and an invoker. It manages reading the frame size and frame data, - * getting it handed off as wrapped transports, and then the writing of - * response data back to the client. In the process it manages flipping the - * read and write bits on the selection key for its client. + * Class that implements a sort of state machine around the interaction with a client and an + * invoker. It manages reading the frame size and frame data, getting it handed off as wrapped + * transports, and then the writing of response data back to the client. In the process it manages + * flipping the read and write bits on the selection key for its client. */ - public class FrameBuffer { + public class FrameBuffer { private final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); // the actual transport hooked up to the client. @@ -303,9 +280,11 @@ public abstract class AbstractNonblockingServer extends TServer { // context associated with this connection protected final ServerContext context_; - public FrameBuffer(final TNonblockingTransport trans, + public FrameBuffer( + final TNonblockingTransport trans, final SelectionKey selectionKey, - final AbstractSelectThread selectThread) throws TTransportException { + final AbstractSelectThread selectThread) + throws TTransportException { trans_ = trans; selectionKey_ = selectionKey; selectThread_ = selectThread; @@ -321,16 +300,15 @@ public abstract class AbstractNonblockingServer extends TServer { if (eventHandler_ != null) { context_ = eventHandler_.createContext(inProt_, outProt_); } else { - context_ = null; + context_ = null; } } /** - * Give this FrameBuffer a chance to read. The selector loop should have - * received a read event for this FrameBuffer. + * Give this FrameBuffer a chance to read. The selector loop should have received a read event + * for this FrameBuffer. * - * @return true if the connection should live on, false if it should be - * closed + * @return true if the connection should live on, false if it should be closed */ public boolean read() { if (state_ == FrameBufferState.READING_FRAME_SIZE) { @@ -345,17 +323,22 @@ public abstract class AbstractNonblockingServer extends TServer { // pull out the frame size as an integer. int frameSize = buffer_.getInt(0); if (frameSize <= 0) { - LOGGER.error("Read an invalid frame size of " + frameSize - + ". Are you using TFramedTransport on the client side?"); + LOGGER.error( + "Read an invalid frame size of " + + frameSize + + ". Are you using TFramedTransport on the client side?"); return false; } // if this frame will always be too large for this server, log the // error and close the connection. if (frameSize > trans_.getMaxFrameSize()) { - LOGGER.error("Read a frame size of " + frameSize - + ", which is bigger than the maximum allowable frame size " - + trans_.getMaxFrameSize() + " for ALL connections."); + LOGGER.error( + "Read a frame size of " + + frameSize + + ", which is bigger than the maximum allowable frame size " + + trans_.getMaxFrameSize() + + " for ALL connections."); return false; } @@ -406,9 +389,7 @@ public abstract class AbstractNonblockingServer extends TServer { return false; } - /** - * Give this FrameBuffer a chance to write its output to the final client. - */ + /** Give this FrameBuffer a chance to write its output to the final client. */ public boolean write() { if (state_ == FrameBufferState.WRITING) { try { @@ -431,40 +412,33 @@ public abstract class AbstractNonblockingServer extends TServer { return false; } - /** - * Give this FrameBuffer a chance to set its interest to write, once data - * has come in. - */ + /** Give this FrameBuffer a chance to set its interest to write, once data has come in. */ public void changeSelectInterests() { switch (state_) { - case AWAITING_REGISTER_WRITE: - // set the OP_WRITE interest - selectionKey_.interestOps(SelectionKey.OP_WRITE); - state_ = FrameBufferState.WRITING; - break; - case AWAITING_REGISTER_READ: - prepareRead(); - break; - case AWAITING_CLOSE: - close(); - selectionKey_.cancel(); - break; - default: - LOGGER.error( - "changeSelectInterest was called, but state is invalid ({})", - state_); + case AWAITING_REGISTER_WRITE: + // set the OP_WRITE interest + selectionKey_.interestOps(SelectionKey.OP_WRITE); + state_ = FrameBufferState.WRITING; + break; + case AWAITING_REGISTER_READ: + prepareRead(); + break; + case AWAITING_CLOSE: + close(); + selectionKey_.cancel(); + break; + default: + LOGGER.error("changeSelectInterest was called, but state is invalid ({})", state_); } } - /** - * Shut the connection down. - */ + /** Shut the connection down. */ public void close() { // if we're being closed due to an error, we might have allocated a // buffer that we need to subtract for our memory accounting. - if (state_ == FrameBufferState.READING_FRAME || - state_ == FrameBufferState.READ_FRAME_COMPLETE || - state_ == FrameBufferState.AWAITING_CLOSE) { + if (state_ == FrameBufferState.READING_FRAME + || state_ == FrameBufferState.READ_FRAME_COMPLETE + || state_ == FrameBufferState.AWAITING_CLOSE) { readBufferBytesAllocated.addAndGet(-buffer_.array().length); } trans_.close(); @@ -473,19 +447,16 @@ public abstract class AbstractNonblockingServer extends TServer { } } - /** - * Check if this FrameBuffer has a full frame read. - */ + /** Check if this FrameBuffer has a full frame read. */ public boolean isFrameFullyRead() { return state_ == FrameBufferState.READ_FRAME_COMPLETE; } /** - * After the processor has processed the invocation, whatever thread is - * managing invocations should call this method on this FrameBuffer so we - * know it's time to start trying to write again. Also, if it turns out that - * there actually isn't any data in the response buffer, we'll skip trying - * to write and instead go back to reading. + * After the processor has processed the invocation, whatever thread is managing invocations + * should call this method on this FrameBuffer so we know it's time to start trying to write + * again. Also, if it turns out that there actually isn't any data in the response buffer, we'll + * skip trying to write and instead go back to reading. */ public void responseReady() { // the read buffer is definitely no longer in use, so we will decrement @@ -511,9 +482,7 @@ public abstract class AbstractNonblockingServer extends TServer { requestSelectInterestChange(); } - /** - * Actually invoke the method signified by this FrameBuffer. - */ + /** Actually invoke the method signified by this FrameBuffer. */ public void invoke() { frameTrans_.reset(buffer_.array()); response_.reset(); @@ -538,22 +507,18 @@ public abstract class AbstractNonblockingServer extends TServer { /** * Perform a read into buffer. * - * @return true if the read succeeded, false if there was an error or the - * connection closed. + * @return true if the read succeeded, false if there was an error or the connection closed. */ private boolean internalRead() { try { - return trans_.read(buffer_) >= 0; + return trans_.read(buffer_) >= 0; } catch (TTransportException e) { LOGGER.warn("Got an Exception in internalRead", e); return false; } } - /** - * We're done writing, so reset our interest ops and change state - * accordingly. - */ + /** We're done writing, so reset our interest ops and change state accordingly. */ private void prepareRead() { // we can set our interest directly without using the queue because // we're in the select thread. @@ -564,11 +529,10 @@ public abstract class AbstractNonblockingServer extends TServer { } /** - * When this FrameBuffer needs to change its select interests and execution - * might not be in its select thread, then this method will make sure the - * interest change gets done when the select thread wakes back up. When the - * current thread is this FrameBuffer's select thread, then it just does the - * interest change immediately. + * When this FrameBuffer needs to change its select interests and execution might not be in its + * select thread, then this method will make sure the interest change gets done when the select + * thread wakes back up. When the current thread is this FrameBuffer's select thread, then it + * just does the interest change immediately. */ protected void requestSelectInterestChange() { if (Thread.currentThread() == this.selectThread_) { @@ -580,19 +544,20 @@ public abstract class AbstractNonblockingServer extends TServer { } // FrameBuffer public class AsyncFrameBuffer extends FrameBuffer { - public AsyncFrameBuffer(TNonblockingTransport trans, SelectionKey selectionKey, AbstractSelectThread selectThread) throws TTransportException { + public AsyncFrameBuffer( + TNonblockingTransport trans, SelectionKey selectionKey, AbstractSelectThread selectThread) + throws TTransportException { super(trans, selectionKey, selectThread); } public TProtocol getInputProtocol() { - return inProt_; + return inProt_; } public TProtocol getOutputProtocol() { return outProt_; } - public void invoke() { frameTrans_.reset(buffer_.array()); response_.reset(); @@ -601,7 +566,7 @@ public abstract class AbstractNonblockingServer extends TServer { if (eventHandler_ != null) { eventHandler_.processContext(context_, inTrans_, outTrans_); } - ((TAsyncProcessor)processorFactory_.getProcessor(inTrans_)).process(this); + ((TAsyncProcessor) processorFactory_.getProcessor(inTrans_)).process(this); return; } catch (TException te) { LOGGER.warn("Exception while invoking!", te); diff --git a/lib/java/src/main/java/org/apache/thrift/server/Invocation.java b/lib/java/src/main/java/org/apache/thrift/server/Invocation.java index e8210f419..64f896927 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/Invocation.java +++ b/lib/java/src/main/java/org/apache/thrift/server/Invocation.java @@ -3,9 +3,9 @@ package org.apache.thrift.server; import org.apache.thrift.server.AbstractNonblockingServer.FrameBuffer; /** - * An Invocation represents a method call that is prepared to execute, given - * an idle worker thread. It contains the input and output protocols the - * thread's processor should use to perform the usual Thrift invocation. + * An Invocation represents a method call that is prepared to execute, given an idle worker thread. + * It contains the input and output protocols the thread's processor should use to perform the usual + * Thrift invocation. */ class Invocation implements Runnable { private final FrameBuffer frameBuffer; @@ -17,4 +17,4 @@ class Invocation implements Runnable { public void run() { frameBuffer.invoke(); } -}
\ No newline at end of file +} diff --git a/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java b/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java index b7c587f37..adf2a438b 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java +++ b/lib/java/src/main/java/org/apache/thrift/server/ServerContext.java @@ -17,33 +17,29 @@ * under the License. */ -/** - * Interface for storing server's connection context. - */ +/** Interface for storing server's connection context. */ package org.apache.thrift.server; public interface ServerContext { /** - * Returns an object that implements the given interface to allow access to - * application specific contexts. + * Returns an object that implements the given interface to allow access to application specific + * contexts. * * @param iface A Class defining an interface that the result must implement * @return an object that implements the interface - * @throws RuntimeException If the context cannot be unwrapped to the provided - * class + * @throws RuntimeException If the context cannot be unwrapped to the provided class */ <T> T unwrap(Class<T> iface); /** - * Returns true if this server context is a wrapper for the provided - * application specific context interface argument or returns false otherwise. + * Returns true if this server context is a wrapper for the provided application specific context + * interface argument or returns false otherwise. * * @param iface a Class defining the underlying context - * @return true if this implements the interface can be unwrapped to the - * provided class - * @throws RuntimeException if an error occurs while determining whether the - * provided class can be unwrapped from this context. + * @return true if this implements the interface can be unwrapped to the provided class + * @throws RuntimeException if an error occurs while determining whether the provided class can be + * unwrapped from this context. */ boolean isWrapperFor(Class<?> iface); } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java b/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java index 75082c0f7..5773e9c3c 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TExtensibleServlet.java @@ -25,14 +25,12 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Map; - import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -41,12 +39,11 @@ import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TTransport; /** - * Servlet implementation class ThriftServer, that allows {@link TProcessor} and - * {@link TProtocolFactory} to be supplied after the {@link #init()} method has - * finished. <br> - * Subclasses must implement the abstract methods that return the TProcessor and - * two TProtocolFactory. Those methods are guaranteed to be called exactly once, - * and that {@link ServletContext} is available. + * Servlet implementation class ThriftServer, that allows {@link TProcessor} and {@link + * TProtocolFactory} to be supplied after the {@link #init()} method has finished. <br> + * Subclasses must implement the abstract methods that return the TProcessor and two + * TProtocolFactory. Those methods are guaranteed to be called exactly once, and that {@link + * ServletContext} is available. */ public abstract class TExtensibleServlet extends HttpServlet { private static final long serialVersionUID = 1L; @@ -60,32 +57,32 @@ public abstract class TExtensibleServlet extends HttpServlet { private Collection<Map.Entry<String, String>> customHeaders; /** - * Returns the appropriate {@link TProcessor}. This will be called <b>once</b> just - * after the {@link #init()} method - * + * Returns the appropriate {@link TProcessor}. This will be called <b>once</b> just after the + * {@link #init()} method + * * @return the appropriate {@link TProcessor} */ protected abstract TProcessor getProcessor(); /** - * Returns the appropriate in {@link TProtocolFactory}. This will be called - * <b>once</b> just after the {@link #init()} method - * + * Returns the appropriate in {@link TProtocolFactory}. This will be called <b>once</b> just after + * the {@link #init()} method + * * @return the appropriate in {@link TProtocolFactory} */ protected abstract TProtocolFactory getInProtocolFactory(); /** - * Returns the appropriate out {@link TProtocolFactory}. This will be called - * <b>once</b> just after the {@link #init()} method - * + * Returns the appropriate out {@link TProtocolFactory}. This will be called <b>once</b> just + * after the {@link #init()} method + * * @return the appropriate out {@link TProtocolFactory} */ protected abstract TProtocolFactory getOutProtocolFactory(); @Override public final void init(ServletConfig config) throws ServletException { - super.init(config); //no-args init() happens here + super.init(config); // no-args init() happens here this.processor = getProcessor(); this.inFactory = getInProtocolFactory(); this.outFactory = getOutProtocolFactory(); @@ -102,10 +99,7 @@ public abstract class TExtensibleServlet extends HttpServlet { } } - /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -116,9 +110,9 @@ public abstract class TExtensibleServlet extends HttpServlet { response.setContentType("application/x-thrift"); if (null != this.customHeaders) { - for (Map.Entry<String, String> header : this.customHeaders) { - response.addHeader(header.getKey(), header.getValue()); - } + for (Map.Entry<String, String> header : this.customHeaders) { + response.addHeader(header.getKey(), header.getValue()); + } } InputStream in = request.getInputStream(); @@ -138,10 +132,7 @@ public abstract class TExtensibleServlet extends HttpServlet { } } - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { @@ -149,19 +140,20 @@ public abstract class TExtensibleServlet extends HttpServlet { } public void addCustomHeader(final String key, final String value) { - this.customHeaders.add(new Map.Entry<String, String>() { - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - - public String setValue(String value) { - return null; - } - }); + this.customHeaders.add( + new Map.Entry<String, String>() { + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + + public String setValue(String value) { + return null; + } + }); } public void setCustomHeaders(Collection<Map.Entry<String, String>> headers) { diff --git a/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java b/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java index 4c5d7b5b5..6e59638a5 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/THsHaServer.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.server; import java.util.concurrent.ExecutorService; @@ -25,12 +24,11 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; - import org.apache.thrift.transport.TNonblockingServerTransport; /** - * An extension of the TNonblockingServer to a Half-Sync/Half-Async server. - * Like TNonblockingServer, it relies on the use of TFramedTransport. + * An extension of the TNonblockingServer to a Half-Sync/Half-Async server. Like TNonblockingServer, + * it relies on the use of TFramedTransport. */ public class THsHaServer extends TNonblockingServer { @@ -45,11 +43,10 @@ public class THsHaServer extends TNonblockingServer { super(transport); } - /** * Sets the min and max threads. * - * @deprecated use {@link #minWorkerThreads(int)} and {@link #maxWorkerThreads(int)} instead. + * @deprecated use {@link #minWorkerThreads(int)} and {@link #maxWorkerThreads(int)} instead. */ @Deprecated public Args workerThreads(int n) { @@ -113,16 +110,13 @@ public class THsHaServer extends TNonblockingServer { } } - // This wraps all the functionality of queueing and thread pool management // for the passing of Invocations from the Selector to workers. private final ExecutorService invoker; private final Args args; - /** - * Create the server with the specified Args configuration - */ + /** Create the server with the specified Args configuration */ public THsHaServer(Args args) { super(args); @@ -130,18 +124,14 @@ public class THsHaServer extends TNonblockingServer { this.args = args; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override protected void waitForShutdown() { joinSelector(); gracefullyShutdownInvokerPool(); } - /** - * Helper to create an invoker pool - */ + /** Helper to create an invoker pool */ protected static ExecutorService createInvokerPool(Args options) { int minWorkerThreads = options.minWorkerThreads; int maxWorkerThreads = options.maxWorkerThreads; @@ -149,8 +139,9 @@ public class THsHaServer extends TNonblockingServer { TimeUnit stopTimeoutUnit = options.stopTimeoutUnit; LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(); - ExecutorService invoker = new ThreadPoolExecutor(minWorkerThreads, - maxWorkerThreads, stopTimeoutVal, stopTimeoutUnit, queue); + ExecutorService invoker = + new ThreadPoolExecutor( + minWorkerThreads, maxWorkerThreads, stopTimeoutVal, stopTimeoutUnit, queue); return invoker; } @@ -182,9 +173,8 @@ public class THsHaServer extends TNonblockingServer { } /** - * We override the standard invoke method here to queue the invocation for - * invoker service instead of immediately invoking. The thread pool takes care - * of the rest. + * We override the standard invoke method here to queue the invocation for invoker service instead + * of immediately invoking. The thread pool takes care of the rest. */ @Override protected boolean requestInvoke(FrameBuffer frameBuffer) { @@ -198,7 +188,7 @@ public class THsHaServer extends TNonblockingServer { } } - protected Runnable getRunnable(FrameBuffer frameBuffer){ + protected Runnable getRunnable(FrameBuffer frameBuffer) { return new Invocation(frameBuffer); } } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java b/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java index eac05a876..fa75569d9 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java @@ -17,27 +17,25 @@ * under the License. */ - package org.apache.thrift.server; -import org.apache.thrift.transport.TNonblockingServerTransport; -import org.apache.thrift.transport.TNonblockingTransport; -import org.apache.thrift.transport.TTransportException; - import java.io.IOException; import java.nio.channels.SelectionKey; import java.util.Iterator; +import org.apache.thrift.transport.TNonblockingServerTransport; +import org.apache.thrift.transport.TNonblockingTransport; +import org.apache.thrift.transport.TTransportException; /** - * A nonblocking TServer implementation. This allows for fairness amongst all - * connected clients in terms of invocations. + * A nonblocking TServer implementation. This allows for fairness amongst all connected clients in + * terms of invocations. * - * This server is inherently single-threaded. If you want a limited thread pool - * coupled with invocation-fairness, see THsHaServer. + * <p>This server is inherently single-threaded. If you want a limited thread pool coupled with + * invocation-fairness, see THsHaServer. * - * To use this server, you MUST use a TFramedTransport at the outermost - * transport, otherwise this server will be unable to determine when a whole - * method call has been read off the wire. Clients must also use TFramedTransport. + * <p>To use this server, you MUST use a TFramedTransport at the outermost transport, otherwise this + * server will be unable to determine when a whole method call has been read off the wire. Clients + * must also use TFramedTransport. */ public class TNonblockingServer extends AbstractNonblockingServer { @@ -53,18 +51,16 @@ public class TNonblockingServer extends AbstractNonblockingServer { super(args); } - /** * Start the selector thread to deal with accepts and client messages. * - * @return true if everything went ok, false if we couldn't start for some - * reason. + * @return true if everything went ok, false if we couldn't start for some reason. */ @Override protected boolean startThreads() { // start the selector try { - selectAcceptThread_ = new SelectAcceptThread((TNonblockingServerTransport)serverTransport_); + selectAcceptThread_ = new SelectAcceptThread((TNonblockingServerTransport) serverTransport_); selectAcceptThread_.start(); return true; } catch (IOException e) { @@ -78,9 +74,7 @@ public class TNonblockingServer extends AbstractNonblockingServer { joinSelector(); } - /** - * Block until the selector thread exits. - */ + /** Block until the selector thread exits. */ protected void joinSelector() { // wait until the selector thread exits try { @@ -91,9 +85,7 @@ public class TNonblockingServer extends AbstractNonblockingServer { } } - /** - * Stop serving and shut everything down. - */ + /** Stop serving and shut everything down. */ @Override public void stop() { stopped_ = true; @@ -103,8 +95,8 @@ public class TNonblockingServer extends AbstractNonblockingServer { } /** - * Perform an invocation. This method could behave several different ways - * - invoke immediately inline, queue for separate execution, etc. + * Perform an invocation. This method could behave several different ways - invoke immediately + * inline, queue for separate execution, etc. */ @Override protected boolean requestInvoke(FrameBuffer frameBuffer) { @@ -112,26 +104,22 @@ public class TNonblockingServer extends AbstractNonblockingServer { return true; } - public boolean isStopped() { return selectAcceptThread_.isStopped(); } /** - * The thread that will be doing all the selecting, managing new connections - * and those that still need to be read. + * The thread that will be doing all the selecting, managing new connections and those that still + * need to be read. */ protected class SelectAcceptThread extends AbstractSelectThread { // The server transport on which new client transports will be accepted private final TNonblockingServerTransport serverTransport; - /** - * Set up the thread that will handle the non-blocking accepts, reads, and - * writes. - */ + /** Set up the thread that will handle the non-blocking accepts, reads, and writes. */ public SelectAcceptThread(final TNonblockingServerTransport serverTransport) - throws IOException { + throws IOException { this.serverTransport = serverTransport; serverTransport.registerSelector(selector); } @@ -141,8 +129,8 @@ public class TNonblockingServer extends AbstractNonblockingServer { } /** - * The work loop. Handles both selecting (all IO operations) and managing - * the selection preferences of all existing connections. + * The work loop. Handles both selecting (all IO operations) and managing the selection + * preferences of all existing connections. */ public void run() { try { @@ -170,12 +158,10 @@ public class TNonblockingServer extends AbstractNonblockingServer { } /** - * Select and process IO events appropriately: - * If there are connections to be accepted, accept them. - * If there are existing connections with data waiting to be read, read it, - * buffering until a whole frame has been read. - * If there are any pending responses, buffer them until their target client - * is available, and then send the data. + * Select and process IO events appropriately: If there are connections to be accepted, accept + * them. If there are existing connections with data waiting to be read, read it, buffering + * until a whole frame has been read. If there are any pending responses, buffer them until + * their target client is available, and then send the data. */ private void select() { try { @@ -213,17 +199,17 @@ public class TNonblockingServer extends AbstractNonblockingServer { } } - protected FrameBuffer createFrameBuffer(final TNonblockingTransport trans, + protected FrameBuffer createFrameBuffer( + final TNonblockingTransport trans, final SelectionKey selectionKey, - final AbstractSelectThread selectThread) throws TTransportException { - return processorFactory_.isAsyncProcessor() ? - new AsyncFrameBuffer(trans, selectionKey, selectThread) : - new FrameBuffer(trans, selectionKey, selectThread); + final AbstractSelectThread selectThread) + throws TTransportException { + return processorFactory_.isAsyncProcessor() + ? new AsyncFrameBuffer(trans, selectionKey, selectThread) + : new FrameBuffer(trans, selectionKey, selectThread); } - /** - * Accept a new connection. - */ + /** Accept a new connection. */ private void handleAccept() throws IOException { SelectionKey clientKey = null; TNonblockingTransport client = null; @@ -233,9 +219,9 @@ public class TNonblockingServer extends AbstractNonblockingServer { clientKey = client.registerSelector(selector, SelectionKey.OP_READ); // add this key to the map - FrameBuffer frameBuffer = createFrameBuffer(client, clientKey, SelectAcceptThread.this); + FrameBuffer frameBuffer = createFrameBuffer(client, clientKey, SelectAcceptThread.this); - clientKey.attach(frameBuffer); + clientKey.attach(frameBuffer); } catch (TTransportException tte) { // something went wrong accepting. LOGGER.warn("Exception trying to accept!", tte); diff --git a/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java b/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java index 89dbb7872..6f22d8bb4 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TSaslNonblockingServer.java @@ -32,9 +32,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; - import javax.security.auth.callback.CallbackHandler; - import org.apache.thrift.TProcessor; import org.apache.thrift.transport.TNonblockingServerSocket; import org.apache.thrift.transport.TNonblockingServerTransport; @@ -48,9 +46,7 @@ import org.apache.thrift.transport.sasl.TSaslServerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * TServer with sasl support, using asynchronous execution and nonblocking io. - */ +/** TServer with sasl support, using asynchronous execution and nonblocking io. */ public class TSaslNonblockingServer extends TServer { private static final Logger LOGGER = LoggerFactory.getLogger(TSaslNonblockingServer.class); @@ -85,9 +81,7 @@ public class TSaslNonblockingServer extends TServer { setServing(true); } - /** - * Trigger a graceful shutdown, but it does not block to wait for the shutdown to finish. - */ + /** Trigger a graceful shutdown, but it does not block to wait for the shutdown to finish. */ @Override public void stop() { if (!stopped_) { @@ -202,8 +196,10 @@ public class TSaslNonblockingServer extends TServer { } private class NetworkThread extends Thread { - private final BlockingQueue<TNonblockingTransport> incomingConnections = new LinkedBlockingQueue<>(); - private final BlockingQueue<NonblockingSaslHandler> stateTransitions = new LinkedBlockingQueue<>(); + private final BlockingQueue<TNonblockingTransport> incomingConnections = + new LinkedBlockingQueue<>(); + private final BlockingQueue<NonblockingSaslHandler> stateTransitions = + new LinkedBlockingQueue<>(); private final Selector ioSelector; NetworkThread(String name) throws IOException { @@ -285,9 +281,15 @@ public class TSaslNonblockingServer extends TServer { try { SelectionKey selectionKey = connection.registerSelector(ioSelector, SelectionKey.OP_READ); if (selectionKey.isValid()) { - NonblockingSaslHandler saslHandler = new NonblockingSaslHandler(selectionKey, connection, - saslServerFactory, saslProcessorFactory, inputProtocolFactory_, outputProtocolFactory_, - eventHandler_); + NonblockingSaslHandler saslHandler = + new NonblockingSaslHandler( + selectionKey, + connection, + saslServerFactory, + saslProcessorFactory, + inputProtocolFactory_, + outputProtocolFactory_, + eventHandler_); selectionKey.attach(saslHandler); } } catch (IOException e) { @@ -407,7 +409,7 @@ public class TSaslNonblockingServer extends TServer { * @return true if the incoming connection is accepted by network thread pool. */ boolean acceptNewConnection(TNonblockingTransport connection) { - return networkThreads.get((accepted ++) % networkThreads.size()).accept(connection); + return networkThreads.get((accepted++) % networkThreads.size()).accept(connection); } public void start() { @@ -441,12 +443,14 @@ public class TSaslNonblockingServer extends TServer { } public Args saslThreads(int authenticationThreads) { - this.saslThreads = authenticationThreads <= 0 ? DEFAULT_AUTHENTICATION_THREADS : authenticationThreads; + this.saslThreads = + authenticationThreads <= 0 ? DEFAULT_AUTHENTICATION_THREADS : authenticationThreads; return this; } public Args processingThreads(int processingThreads) { - this.processingThreads = processingThreads <= 0 ? DEFAULT_PROCESSING_THREADS : processingThreads; + this.processingThreads = + processingThreads <= 0 ? DEFAULT_PROCESSING_THREADS : processingThreads; return this; } @@ -463,8 +467,12 @@ public class TSaslNonblockingServer extends TServer { return this; } - public Args addSaslMechanism(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { + public Args addSaslMechanism( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { saslServerFactory.addSaslMechanism(mechanism, protocol, serverName, props, cbh); return this; } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TServer.java b/lib/java/src/main/java/org/apache/thrift/server/TServer.java index bac06b26b..1a4f1983e 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TServer.java @@ -26,10 +26,7 @@ import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TTransportFactory; -/** - * Generic interface for a Thrift server. - * - */ +/** Generic interface for a Thrift server. */ public abstract class TServer { public static class Args extends AbstractServerArgs<Args> { @@ -38,7 +35,7 @@ public abstract class TServer { } } - public static abstract class AbstractServerArgs<T extends AbstractServerArgs<T>> { + public abstract static class AbstractServerArgs<T extends AbstractServerArgs<T>> { final TServerTransport serverTransport; TProcessorFactory processorFactory; TTransportFactory inputTransportFactory = new TTransportFactory(); @@ -93,34 +90,22 @@ public abstract class TServer { } } - /** - * Core processor - */ + /** Core processor */ protected TProcessorFactory processorFactory_; - /** - * Server transport - */ + /** Server transport */ protected TServerTransport serverTransport_; - /** - * Input Transport Factory - */ + /** Input Transport Factory */ protected TTransportFactory inputTransportFactory_; - /** - * Output Transport Factory - */ + /** Output Transport Factory */ protected TTransportFactory outputTransportFactory_; - /** - * Input Protocol Factory - */ + /** Input Protocol Factory */ protected TProtocolFactory inputProtocolFactory_; - /** - * Output Protocol Factory - */ + /** Output Protocol Factory */ protected TProtocolFactory outputProtocolFactory_; private volatile boolean isServing; @@ -140,14 +125,12 @@ public abstract class TServer { outputProtocolFactory_ = args.outputProtocolFactory; } - /** - * The run method fires up the server and gets things going. - */ + /** The run method fires up the server and gets things going. */ public abstract void serve(); /** - * Stop the server. This is optional on a per-implementation basis. Not - * all servers are required to be cleanly stoppable. + * Stop the server. This is optional on a per-implementation basis. Not all servers are required + * to be cleanly stoppable. */ public void stop() {} diff --git a/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java b/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java index 3bd795986..4ff043a58 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TServerEventHandler.java @@ -23,41 +23,27 @@ import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TTransport; /** - * Interface that can handle events from the server core. To - * use this you should subclass it and implement the methods that you care - * about. Your subclass can also store local data that you may care about, - * such as additional "arguments" to these methods (stored in the object - * instance's state). + * Interface that can handle events from the server core. To use this you should subclass it and + * implement the methods that you care about. Your subclass can also store local data that you may + * care about, such as additional "arguments" to these methods (stored in the object instance's + * state). * - * TODO: It seems this is a custom code entry point created for some resource management purpose in hive. - * But when looking into hive code, we see that the argments of TProtocol and TTransport are never used. - * We probably should remove these arguments from all the methods. + * <p>TODO: It seems this is a custom code entry point created for some resource management purpose + * in hive. But when looking into hive code, we see that the argments of TProtocol and TTransport + * are never used. We probably should remove these arguments from all the methods. */ public interface TServerEventHandler { - /** - * Called before the server begins. - */ + /** Called before the server begins. */ void preServe(); - /** - * Called when a new client has connected and is about to being processing. - */ - ServerContext createContext(TProtocol input, - TProtocol output); + /** Called when a new client has connected and is about to being processing. */ + ServerContext createContext(TProtocol input, TProtocol output); - /** - * Called when a client has finished request-handling to delete server - * context. - */ - void deleteContext(ServerContext serverContext, - TProtocol input, - TProtocol output); - - /** - * Called when a client is about to call the processor. - */ - void processContext(ServerContext serverContext, - TTransport inputTransport, TTransport outputTransport); + /** Called when a client has finished request-handling to delete server context. */ + void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output); + /** Called when a client is about to call the processor. */ + void processContext( + ServerContext serverContext, TTransport inputTransport, TTransport outputTransport); } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TServlet.java b/lib/java/src/main/java/org/apache/thrift/server/TServlet.java index c1ab9df55..0f233fac4 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TServlet.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TServlet.java @@ -6,12 +6,10 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Map; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -19,9 +17,7 @@ import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TTransport; -/** - * Servlet implementation class ThriftServer - */ +/** Servlet implementation class ThriftServer */ public class TServlet extends HttpServlet { private final TProcessor processor; @@ -32,10 +28,10 @@ public class TServlet extends HttpServlet { private final Collection<Map.Entry<String, String>> customHeaders; - /** - * @see HttpServlet#HttpServlet() - */ - public TServlet(TProcessor processor, TProtocolFactory inProtocolFactory, + /** @see HttpServlet#HttpServlet() */ + public TServlet( + TProcessor processor, + TProtocolFactory inProtocolFactory, TProtocolFactory outProtocolFactory) { super(); this.processor = processor; @@ -44,17 +40,12 @@ public class TServlet extends HttpServlet { this.customHeaders = new ArrayList<Map.Entry<String, String>>(); } - /** - * @see HttpServlet#HttpServlet() - */ + /** @see HttpServlet#HttpServlet() */ public TServlet(TProcessor processor, TProtocolFactory protocolFactory) { this(processor, protocolFactory, protocolFactory); } - /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -87,29 +78,27 @@ public class TServlet extends HttpServlet { } } - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse - * response) - */ + /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void addCustomHeader(final String key, final String value) { - this.customHeaders.add(new Map.Entry<String, String>() { - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - - public String setValue(String value) { - return null; - } - }); + this.customHeaders.add( + new Map.Entry<String, String>() { + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + + public String setValue(String value) { + return null; + } + }); } public void setCustomHeaders(Collection<Map.Entry<String, String>> headers) { diff --git a/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java b/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java index 70cc3d776..3530d6d8c 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TSimpleServer.java @@ -27,10 +27,7 @@ import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Simple singlethreaded server for testing. - * - */ +/** Simple singlethreaded server for testing. */ public class TSimpleServer extends TServer { private static final Logger LOGGER = LoggerFactory.getLogger(TSimpleServer.class.getName()); @@ -104,7 +101,6 @@ public class TSimpleServer extends TServer { if (outputTransport != null) { outputTransport.close(); } - } setServing(false); } diff --git a/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java b/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java index e19041568..cc5843869 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TThreadPoolServer.java @@ -27,7 +27,6 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -38,8 +37,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Server which uses Java's built in ThreadPool management to spawn off - * a worker pool that deals with client connections in blocking way. + * Server which uses Java's built in ThreadPool management to spawn off a worker pool that deals + * with client connections in blocking way. */ public class TThreadPoolServer extends TServer { private static final Logger LOGGER = LoggerFactory.getLogger(TThreadPoolServer.class); @@ -94,19 +93,26 @@ public class TThreadPoolServer extends TServer { stopTimeoutUnit = args.stopTimeoutUnit; stopTimeoutVal = args.stopTimeoutVal; - executorService_ = args.executorService != null ? - args.executorService : createDefaultExecutorService(args); + executorService_ = + args.executorService != null ? args.executorService : createDefaultExecutorService(args); } private static ExecutorService createDefaultExecutorService(Args args) { - return new ThreadPoolExecutor(args.minWorkerThreads, args.maxWorkerThreads, 60L, TimeUnit.SECONDS, - new SynchronousQueue<>(), new ThreadFactory() { + return new ThreadPoolExecutor( + args.minWorkerThreads, + args.maxWorkerThreads, + 60L, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + new ThreadFactory() { final AtomicLong count = new AtomicLong(); + @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); - thread.setName(String.format("TThreadPoolServer WorkerProcess-%d", count.getAndIncrement())); + thread.setName( + String.format("TThreadPoolServer WorkerProcess-%d", count.getAndIncrement())); return thread; } }); @@ -157,7 +163,8 @@ public class TThreadPoolServer extends TServer { executorService_.execute(new WorkerProcess(client)); } catch (RejectedExecutionException ree) { if (!stopped_) { - LOGGER.warn("ThreadPool is saturated with incoming requests. Closing latest connection."); + LOGGER.warn( + "ThreadPool is saturated with incoming requests. Closing latest connection."); } client.close(); } @@ -195,9 +202,7 @@ public class TThreadPoolServer extends TServer { private class WorkerProcess implements Runnable { - /** - * Client that this services. - */ + /** Client that this services. */ private TTransport client_; /** @@ -209,9 +214,7 @@ public class TThreadPoolServer extends TServer { client_ = client; } - /** - * Loops on processing a client forever - */ + /** Loops on processing a client forever */ public void run() { TProcessor processor = null; TTransport inputTransport = null; @@ -257,7 +260,10 @@ public class TThreadPoolServer extends TServer { // Ignore err-logging all transport-level/type exceptions if (!isIgnorableException(x)) { // Log the exception at error level and continue - LOGGER.error((x instanceof TException ? "Thrift " : "") + "Error occurred during processing of message.", x); + LOGGER.error( + (x instanceof TException ? "Thrift " : "") + + "Error occurred during processing of message.", + x); } } finally { if (eventHandler.isPresent()) { @@ -285,7 +291,7 @@ public class TThreadPoolServer extends TServer { } if (tTransportException != null) { - switch(tTransportException.getType()) { + switch (tTransportException.getType()) { case TTransportException.END_OF_FILE: case TTransportException.TIMED_OUT: return true; diff --git a/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java b/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java index 095aacbc5..0a4d8575f 100644 --- a/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java +++ b/lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java @@ -19,12 +19,6 @@ package org.apache.thrift.server; -import org.apache.thrift.transport.TNonblockingServerTransport; -import org.apache.thrift.transport.TNonblockingTransport; -import org.apache.thrift.transport.TTransportException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectableChannel; @@ -44,58 +38,61 @@ import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import org.apache.thrift.transport.TNonblockingServerTransport; +import org.apache.thrift.transport.TNonblockingTransport; +import org.apache.thrift.transport.TTransportException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * A Half-Sync/Half-Async server with a separate pool of threads to handle - * non-blocking I/O. Accepts are handled on a single thread, and a configurable - * number of nonblocking selector threads manage reading and writing of client - * connections. A synchronous worker thread pool handles processing of requests. + * A Half-Sync/Half-Async server with a separate pool of threads to handle non-blocking I/O. Accepts + * are handled on a single thread, and a configurable number of nonblocking selector threads manage + * reading and writing of client connections. A synchronous worker thread pool handles processing of + * requests. * - * Performs better than TNonblockingServer/THsHaServer in multi-core - * environments when the the bottleneck is CPU on the single selector thread - * handling I/O. In addition, because the accept handling is decoupled from - * reads/writes and invocation, the server has better ability to handle back- - * pressure from new connections (e.g. stop accepting when busy). + * <p>Performs better than TNonblockingServer/THsHaServer in multi-core environments when the the + * bottleneck is CPU on the single selector thread handling I/O. In addition, because the accept + * handling is decoupled from reads/writes and invocation, the server has better ability to handle + * back- pressure from new connections (e.g. stop accepting when busy). * - * Like TNonblockingServer, it relies on the use of TFramedTransport. + * <p>Like TNonblockingServer, it relies on the use of TFramedTransport. */ public class TThreadedSelectorServer extends AbstractNonblockingServer { - private static final Logger LOGGER = LoggerFactory.getLogger(TThreadedSelectorServer.class.getName()); + private static final Logger LOGGER = + LoggerFactory.getLogger(TThreadedSelectorServer.class.getName()); public static class Args extends AbstractNonblockingServerArgs<Args> { /** The number of threads for selecting on already-accepted connections */ public int selectorThreads = 2; /** - * The size of the executor service (if none is specified) that will handle - * invocations. This may be set to 0, in which case invocations will be - * handled directly on the selector threads (as is in TNonblockingServer) + * The size of the executor service (if none is specified) that will handle invocations. This + * may be set to 0, in which case invocations will be handled directly on the selector threads + * (as is in TNonblockingServer) */ private int workerThreads = 5; /** Time to wait for server to stop gracefully */ private int stopTimeoutVal = 60; + private TimeUnit stopTimeoutUnit = TimeUnit.SECONDS; /** The ExecutorService for handling dispatched requests */ private ExecutorService executorService = null; /** - * The size of the blocking queue per selector thread for passing accepted - * connections to the selector thread + * The size of the blocking queue per selector thread for passing accepted connections to the + * selector thread */ private int acceptQueueSizePerThread = 4; - /** - * Determines the strategy for handling new accepted connections. - */ + /** Determines the strategy for handling new accepted connections. */ public static enum AcceptPolicy { /** - * Require accepted connection registration to be handled by the executor. - * If the worker pool is saturated, further accepts will be closed - * immediately. Slightly increases latency due to an extra scheduling. + * Require accepted connection registration to be handled by the executor. If the worker pool + * is saturated, further accepts will be closed immediately. Slightly increases latency due to + * an extra scheduling. */ FAIR_ACCEPT, /** - * Handle the accepts as fast as possible, disregarding the status of the - * executor service. + * Handle the accepts as fast as possible, disregarding the status of the executor service. */ FAST_ACCEPT } @@ -195,9 +192,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { private final Args args; - /** - * Create the server with the specified Args configuration - */ + /** Create the server with the specified Args configuration */ public TThreadedSelectorServer(Args args) { super(args); args.validate(); @@ -208,8 +203,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Start the accept and selector threads running to deal with clients. * - * @return true if everything went ok, false if we couldn't start for some - * reason. + * @return true if everything went ok, false if we couldn't start for some reason. */ @Override protected boolean startThreads() { @@ -217,8 +211,10 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { for (int i = 0; i < args.selectorThreads; ++i) { selectorThreads.add(new SelectorThread(args.acceptQueueSizePerThread)); } - acceptThread = new AcceptThread((TNonblockingServerTransport) serverTransport_, - createSelectorThreadLoadBalancer(selectorThreads)); + acceptThread = + new AcceptThread( + (TNonblockingServerTransport) serverTransport_, + createSelectorThreadLoadBalancer(selectorThreads)); for (SelectorThread thread : selectorThreads) { thread.start(); } @@ -230,9 +226,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * Joins the accept and selector threads and shuts down the executor service. - */ + /** Joins the accept and selector threads and shuts down the executor service. */ @Override protected void waitForShutdown() { try { @@ -252,9 +246,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * Stop serving and shut everything down. - */ + /** Stop serving and shut everything down. */ @Override public void stop() { stopped_ = true; @@ -267,8 +259,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } if (selectorThreads != null) { for (SelectorThread thread : selectorThreads) { - if (thread != null) - thread.wakeupSelector(); + if (thread != null) thread.wakeupSelector(); } } } @@ -296,9 +287,9 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * We override the standard invoke method here to queue the invocation for - * invoker service instead of immediately invoking. If there is no thread - * pool, handle the invocation inline on this thread + * We override the standard invoke method here to queue the invocation for invoker service instead + * of immediately invoking. If there is no thread pool, handle the invocation inline on this + * thread */ @Override protected boolean requestInvoke(FrameBuffer frameBuffer) { @@ -322,9 +313,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { return new Invocation(frameBuffer); } - /** - * Helper to create the invoker if one is not specified - */ + /** Helper to create the invoker if one is not specified */ protected static ExecutorService createDefaultExecutor(Args options) { return (options.workerThreads > 0) ? Executors.newFixedThreadPool(options.workerThreads) : null; } @@ -338,8 +327,8 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * The thread that selects on the server transport (listen socket) and accepts - * new connections to hand off to the IO selector threads + * The thread that selects on the server transport (listen socket) and accepts new connections to + * hand off to the IO selector threads */ protected class AcceptThread extends Thread { @@ -354,8 +343,9 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { * * @throws IOException */ - public AcceptThread(TNonblockingServerTransport serverTransport, - SelectorThreadLoadBalancer threadChooser) throws IOException { + public AcceptThread( + TNonblockingServerTransport serverTransport, SelectorThreadLoadBalancer threadChooser) + throws IOException { this.serverTransport = serverTransport; this.threadChooser = threadChooser; this.acceptSelector = SelectorProvider.provider().openSelector(); @@ -363,9 +353,9 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * The work loop. Selects on the server transport and accepts. If there was - * a server transport that had blocking accepts, and returned on blocking - * client transports, that should be used instead + * The work loop. Selects on the server transport and accepts. If there was a server transport + * that had blocking accepts, and returned on blocking client transports, that should be used + * instead */ public void run() { try { @@ -389,16 +379,14 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * If the selector is blocked, wake it up. - */ + /** If the selector is blocked, wake it up. */ public void wakeupSelector() { acceptSelector.wakeup(); } /** - * Select and process IO events appropriately: If there are connections to - * be accepted, accept them. + * Select and process IO events appropriately: If there are connections to be accepted, accept + * them. */ private void select() { try { @@ -427,9 +415,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - /** - * Accept a new connection. - */ + /** Accept a new connection. */ private void handleAccept() { final TNonblockingTransport client = doAccept(); if (client != null) { @@ -441,11 +427,12 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } else { // FAIR_ACCEPT try { - invoker.submit(new Runnable() { - public void run() { - doAddAccept(targetThread, client); - } - }); + invoker.submit( + new Runnable() { + public void run() { + doAddAccept(targetThread, client); + } + }); } catch (RejectedExecutionException rx) { LOGGER.warn("ExecutorService rejected accept registration!", rx); // close immediately @@ -472,10 +459,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } // AcceptThread - /** - * The SelectorThread(s) will be doing all the selecting on accepted active - * connections. - */ + /** The SelectorThread(s) will be doing all the selecting on accepted active connections. */ protected class SelectorThread extends AbstractSelectThread { // Accepted connections added by the accept thread. @@ -487,8 +471,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with an unbounded queue for incoming accepts. * - * @throws IOException - * if a selector cannot be created + * @throws IOException if a selector cannot be created */ public SelectorThread() throws IOException { this(new LinkedBlockingQueue<TNonblockingTransport>()); @@ -497,8 +480,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with an bounded queue for incoming accepts. * - * @throws IOException - * if a selector cannot be created + * @throws IOException if a selector cannot be created */ public SelectorThread(int maxPendingAccepts) throws IOException { this(createDefaultAcceptQueue(maxPendingAccepts)); @@ -507,22 +489,19 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with a specified queue for connections. * - * @param acceptedQueue - * The BlockingQueue implementation for holding incoming accepted - * connections. - * @throws IOException - * if a selector cannot be created. + * @param acceptedQueue The BlockingQueue implementation for holding incoming accepted + * connections. + * @throws IOException if a selector cannot be created. */ public SelectorThread(BlockingQueue<TNonblockingTransport> acceptedQueue) throws IOException { this.acceptedQueue = acceptedQueue; } /** - * Hands off an accepted connection to be handled by this thread. This - * method will block if the queue for new connections is at capacity. + * Hands off an accepted connection to be handled by this thread. This method will block if the + * queue for new connections is at capacity. * - * @param accepted - * The connection that has been accepted. + * @param accepted The connection that has been accepted. * @return true if the connection has been successfully added. */ public boolean addAcceptedConnection(TNonblockingTransport accepted) { @@ -537,8 +516,8 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * The work loop. Handles selecting (read/write IO), dispatching, and - * managing the selection preferences of all existing connections. + * The work loop. Handles selecting (read/write IO), dispatching, and managing the selection + * preferences of all existing connections. */ public void run() { try { @@ -564,10 +543,10 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * Select and process IO events appropriately: If there are existing - * connections with data waiting to be read, read it, buffering until a - * whole frame has been read. If there are any pending responses, buffer - * them until their target client is available, and then send the data. + * Select and process IO events appropriately: If there are existing connections with data + * waiting to be read, read it, buffering until a whole frame has been read. If there are any + * pending responses, buffer them until their target client is available, and then send the + * data. */ private void select() { try { @@ -602,8 +581,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } /** - * Do select and judge epoll bug happen. - * See : https://issues.apache.org/jira/browse/THRIFT-4251 + * Do select and judge epoll bug happen. See : https://issues.apache.org/jira/browse/THRIFT-4251 */ private void doSelect() throws IOException { long beforeSelect = System.currentTimeMillis(); @@ -620,12 +598,12 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { if (selectedTime >= MONITOR_PERIOD) { jvmBug = 0; } else if (jvmBug > SELECTOR_AUTO_REBUILD_THRESHOLD) { - LOGGER.warn("In {} ms happen {} times jvm bug; rebuilding selector.", MONITOR_PERIOD, jvmBug); + LOGGER.warn( + "In {} ms happen {} times jvm bug; rebuilding selector.", MONITOR_PERIOD, jvmBug); rebuildSelector(); selector.selectNow(); jvmBug = 0; } - } /** @@ -646,8 +624,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } for (SelectionKey key : oldSelector.selectedKeys()) { - if (!key.isValid() && key.readyOps() == 0) - continue; + if (!key.isValid() && key.readyOps() == 0) continue; SelectableChannel channel = key.channel(); Object attachment = key.attachment(); @@ -660,7 +637,6 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } catch (ClosedChannelException e) { LOGGER.error("Register new selector key error.", e); } - } selector = newSelector; @@ -683,12 +659,14 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } - protected FrameBuffer createFrameBuffer(final TNonblockingTransport trans, + protected FrameBuffer createFrameBuffer( + final TNonblockingTransport trans, final SelectionKey selectionKey, - final AbstractSelectThread selectThread) throws TTransportException { - return processorFactory_.isAsyncProcessor() ? - new AsyncFrameBuffer(trans, selectionKey, selectThread) : - new FrameBuffer(trans, selectionKey, selectThread); + final AbstractSelectThread selectThread) + throws TTransportException { + return processorFactory_.isAsyncProcessor() + ? new AsyncFrameBuffer(trans, selectionKey, selectThread) + : new FrameBuffer(trans, selectionKey, selectThread); } private void registerAccepted(TNonblockingTransport accepted) { @@ -710,17 +688,15 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } // SelectorThread /** - * Creates a SelectorThreadLoadBalancer to be used by the accept thread for - * assigning newly accepted connections across the threads. + * Creates a SelectorThreadLoadBalancer to be used by the accept thread for assigning newly + * accepted connections across the threads. */ - protected SelectorThreadLoadBalancer createSelectorThreadLoadBalancer(Collection<? extends SelectorThread> threads) { + protected SelectorThreadLoadBalancer createSelectorThreadLoadBalancer( + Collection<? extends SelectorThread> threads) { return new SelectorThreadLoadBalancer(threads); } - /** - * A round robin load balancer for choosing selector threads for new - * connections. - */ + /** A round robin load balancer for choosing selector threads for new connections. */ protected static class SelectorThreadLoadBalancer { private final Collection<? extends SelectorThread> threads; private Iterator<? extends SelectorThread> nextThreadIterator; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java index b355d11ca..b1c815f88 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBuffer.java @@ -21,11 +21,10 @@ package org.apache.thrift.transport; import java.util.Arrays; /** - * Helper class that wraps a byte[] so that it can expand and be reused. Users - * should call resizeIfNecessary to make sure the buffer has suitable capacity, - * and then use the array as needed. Note that the internal array will grow at a - * rate slightly faster than the requested capacity with the (untested) - * objective of avoiding expensive buffer allocations and copies. + * Helper class that wraps a byte[] so that it can expand and be reused. Users should call + * resizeIfNecessary to make sure the buffer has suitable capacity, and then use the array as + * needed. Note that the internal array will grow at a rate slightly faster than the requested + * capacity with the (untested) objective of avoiding expensive buffer allocations and copies. */ public class AutoExpandingBuffer { private byte[] array; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java index 6fd4075b9..d59c657db 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferReadTransport.java @@ -20,9 +20,7 @@ package org.apache.thrift.transport; import org.apache.thrift.TConfiguration; -/** - * TTransport for reading from an AutoExpandingBuffer. - */ +/** TTransport for reading from an AutoExpandingBuffer. */ public class AutoExpandingBufferReadTransport extends TEndpointTransport { private final AutoExpandingBuffer buf; @@ -30,7 +28,8 @@ public class AutoExpandingBufferReadTransport extends TEndpointTransport { private int pos = 0; private int limit = 0; - public AutoExpandingBufferReadTransport(TConfiguration config, int initialCapacity) throws TTransportException { + public AutoExpandingBufferReadTransport(TConfiguration config, int initialCapacity) + throws TTransportException { super(config); this.buf = new AutoExpandingBuffer(initialCapacity); } @@ -46,7 +45,9 @@ public class AutoExpandingBufferReadTransport extends TEndpointTransport { public void close() {} @Override - public boolean isOpen() { return true; } + public boolean isOpen() { + return true; + } @Override public void open() throws TTransportException {} @@ -54,7 +55,7 @@ public class AutoExpandingBufferReadTransport extends TEndpointTransport { @Override public final int read(byte[] target, int off, int len) throws TTransportException { int amtToRead = Math.min(len, getBytesRemainingInBuffer()); - if(amtToRead > 0){ + if (amtToRead > 0) { System.arraycopy(buf.array(), pos, target, off, amtToRead); consumeBuffer(amtToRead); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java index 84b28b4c4..741d629ae 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java @@ -20,9 +20,7 @@ package org.apache.thrift.transport; import org.apache.thrift.TConfiguration; -/** - * TTransport for writing to an AutoExpandingBuffer. - */ +/** TTransport for writing to an AutoExpandingBuffer. */ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport { private final AutoExpandingBuffer buf; @@ -31,17 +29,18 @@ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport /** * Constructor. + * * @param config the configuration to use. Currently used for defining the maximum message size. * @param initialCapacity the initial capacity of the buffer - * @param frontReserve space, if any, to reserve at the beginning such - * that the first write is after this reserve. - * This allows framed transport to reserve space - * for the frame buffer length. + * @param frontReserve space, if any, to reserve at the beginning such that the first write is + * after this reserve. This allows framed transport to reserve space for the frame buffer + * length. * @throws IllegalArgumentException if initialCapacity is less than one * @throws IllegalArgumentException if frontReserve is less than zero * @throws IllegalArgumentException if frontReserve is greater than initialCapacity */ - public AutoExpandingBufferWriteTransport(TConfiguration config, int initialCapacity, int frontReserve) throws TTransportException { + public AutoExpandingBufferWriteTransport( + TConfiguration config, int initialCapacity, int frontReserve) throws TTransportException { super(config); if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity"); @@ -58,7 +57,9 @@ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport public void close() {} @Override - public boolean isOpen() {return true;} + public boolean isOpen() { + return true; + } @Override public void open() throws TTransportException {} @@ -79,9 +80,7 @@ public final class AutoExpandingBufferWriteTransport extends TEndpointTransport return buf; } - /** - * @return length of the buffer, including any front reserve - */ + /** @return length of the buffer, including any front reserve */ public int getLength() { return pos; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java b/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java index 72d10c53d..fa296e7c4 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TByteBuffer.java @@ -1,14 +1,11 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; +import org.apache.thrift.TConfiguration; -/** - * ByteBuffer-backed implementation of TTransport. - */ +/** ByteBuffer-backed implementation of TTransport. */ public final class TByteBuffer extends TEndpointTransport { private final ByteBuffer byteBuffer; @@ -30,12 +27,10 @@ public final class TByteBuffer extends TEndpointTransport { } @Override - public void open() { - } + public void open() {} @Override - public void close() { - } + public void close() {} @Override public int read(byte[] buf, int off, int len) throws TTransportException { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java b/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java index b5ae6eff4..52a5cf709 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TEOFException.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport; -/** - * End of file, especially, the underlying socket is closed. - */ +/** End of file, especially, the underlying socket is closed. */ public class TEOFException extends TTransportException { public TEOFException(String message) { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java index f33b8b72d..72bf95391 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TEndpointTransport.java @@ -18,88 +18,93 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.util.Objects; +import org.apache.thrift.TConfiguration; -public abstract class TEndpointTransport extends TTransport{ - - protected long getMaxMessageSize() { return getConfiguration().getMaxMessageSize(); } - - public int getMaxFrameSize() { return getConfiguration().getMaxFrameSize(); } +public abstract class TEndpointTransport extends TTransport { - public void setMaxFrameSize(int maxFrameSize) { getConfiguration().setMaxFrameSize(maxFrameSize); } + protected long getMaxMessageSize() { + return getConfiguration().getMaxMessageSize(); + } - protected long knownMessageSize; - protected long remainingMessageSize; + public int getMaxFrameSize() { + return getConfiguration().getMaxFrameSize(); + } - private TConfiguration _configuration; + public void setMaxFrameSize(int maxFrameSize) { + getConfiguration().setMaxFrameSize(maxFrameSize); + } - public TConfiguration getConfiguration() { - return _configuration; - } + protected long knownMessageSize; + protected long remainingMessageSize; - public TEndpointTransport(TConfiguration config) throws TTransportException { - _configuration = Objects.isNull(config) ? new TConfiguration() : config; + private TConfiguration _configuration; - resetConsumedMessageSize(-1); - } + public TConfiguration getConfiguration() { + return _configuration; + } - /** - * Resets RemainingMessageSize to the configured maximum - * @param newSize - */ - protected void resetConsumedMessageSize(long newSize) throws TTransportException { - // full reset - if (newSize < 0) - { - knownMessageSize = getMaxMessageSize(); - remainingMessageSize = getMaxMessageSize(); - return; - } - - // update only: message size can shrink, but not grow - if (newSize > knownMessageSize) - throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); - - knownMessageSize = newSize; - remainingMessageSize = newSize; - } + public TEndpointTransport(TConfiguration config) throws TTransportException { + _configuration = Objects.isNull(config) ? new TConfiguration() : config; - /** - * Updates RemainingMessageSize to reflect then known real message size (e.g. framed transport). - * Will throw if we already consumed too many bytes or if the new size is larger than allowed. - * @param size - */ - public void updateKnownMessageSize(long size) throws TTransportException { - long consumed = knownMessageSize - remainingMessageSize; - resetConsumedMessageSize(size == 0 ? -1 : size); - countConsumedMessageBytes(consumed); - } + resetConsumedMessageSize(-1); + } - /** - * Throws if there are not enough bytes in the input stream to satisfy a read of numBytes bytes of data - * @param numBytes - */ - public void checkReadBytesAvailable(long numBytes) throws TTransportException { - if (remainingMessageSize < numBytes) - throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); + /** + * Resets RemainingMessageSize to the configured maximum + * + * @param newSize + */ + protected void resetConsumedMessageSize(long newSize) throws TTransportException { + // full reset + if (newSize < 0) { + knownMessageSize = getMaxMessageSize(); + remainingMessageSize = getMaxMessageSize(); + return; } - /** - * Consumes numBytes from the RemainingMessageSize. - * @param numBytes - */ - protected void countConsumedMessageBytes(long numBytes) throws TTransportException { - if (remainingMessageSize >= numBytes) - { - remainingMessageSize -= numBytes; - } - else - { - remainingMessageSize = 0; - throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); - } + // update only: message size can shrink, but not grow + if (newSize > knownMessageSize) + throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); + + knownMessageSize = newSize; + remainingMessageSize = newSize; + } + + /** + * Updates RemainingMessageSize to reflect then known real message size (e.g. framed transport). + * Will throw if we already consumed too many bytes or if the new size is larger than allowed. + * + * @param size + */ + public void updateKnownMessageSize(long size) throws TTransportException { + long consumed = knownMessageSize - remainingMessageSize; + resetConsumedMessageSize(size == 0 ? -1 : size); + countConsumedMessageBytes(consumed); + } + + /** + * Throws if there are not enough bytes in the input stream to satisfy a read of numBytes bytes of + * data + * + * @param numBytes + */ + public void checkReadBytesAvailable(long numBytes) throws TTransportException { + if (remainingMessageSize < numBytes) + throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); + } + + /** + * Consumes numBytes from the RemainingMessageSize. + * + * @param numBytes + */ + protected void countConsumedMessageBytes(long numBytes) throws TTransportException { + if (remainingMessageSize >= numBytes) { + remainingMessageSize -= numBytes; + } else { + remainingMessageSize = 0; + throw new TTransportException(TTransportException.END_OF_FILE, "MaxMessageSize reached"); } - + } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java b/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java index e36a5f384..e447aca0f 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TFileProcessor.java @@ -19,14 +19,14 @@ package org.apache.thrift.transport; -import org.apache.thrift.TProcessor; import org.apache.thrift.TException; +import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; /** - * FileProcessor: helps in processing files generated by TFileTransport. - * Port of original cpp implementation + * FileProcessor: helps in processing files generated by TFileTransport. Port of original cpp + * implementation */ public class TFileProcessor { @@ -36,20 +36,23 @@ public class TFileProcessor { private TFileTransport inputTransport_; private TTransport outputTransport_; - public TFileProcessor(TProcessor processor, TProtocolFactory protocolFactory, - TFileTransport inputTransport, - TTransport outputTransport) { + public TFileProcessor( + TProcessor processor, + TProtocolFactory protocolFactory, + TFileTransport inputTransport, + TTransport outputTransport) { processor_ = processor; inputProtocolFactory_ = outputProtocolFactory_ = protocolFactory; inputTransport_ = inputTransport; outputTransport_ = outputTransport; } - public TFileProcessor(TProcessor processor, - TProtocolFactory inputProtocolFactory, - TProtocolFactory outputProtocolFactory, - TFileTransport inputTransport, - TTransport outputTransport) { + public TFileProcessor( + TProcessor processor, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + TFileTransport inputTransport, + TTransport outputTransport) { processor_ = processor; inputProtocolFactory_ = inputProtocolFactory; outputProtocolFactory_ = outputProtocolFactory; @@ -71,8 +74,7 @@ public class TFileProcessor { } catch (TTransportException e) { // if we are processing the last chunk - we could have just hit EOF // on EOF - trap the error and stop processing. - if(e.getType() != TTransportException.END_OF_FILE) - throw e; + if (e.getType() != TTransportException.END_OF_FILE) throw e; else { return; } @@ -81,20 +83,18 @@ public class TFileProcessor { /** * Process from start to last chunk both inclusive where chunks begin from 0 - + * * @param startChunkNum first chunk to be processed * @param endChunkNum last chunk to be processed * @throws TException if endChunkNum is less than startChunkNum. */ public void processChunk(int startChunkNum, int endChunkNum) throws TException { int numChunks = inputTransport_.getNumChunks(); - if(endChunkNum < 0) - endChunkNum += numChunks; + if (endChunkNum < 0) endChunkNum += numChunks; - if(startChunkNum < 0) - startChunkNum += numChunks; + if (startChunkNum < 0) startChunkNum += numChunks; - if(endChunkNum < startChunkNum) + if (endChunkNum < startChunkNum) throw new TException("endChunkNum " + endChunkNum + " is less than " + startChunkNum); inputTransport_.seekToChunk(startChunkNum); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java index 61b68d279..713d52103 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java @@ -21,22 +21,21 @@ package org.apache.thrift.transport; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; import java.util.Random; - import org.apache.thrift.TConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * FileTransport implementation of the TTransport interface. - * Currently this is a straightforward port of the cpp implementation + * FileTransport implementation of the TTransport interface. Currently this is a straightforward + * port of the cpp implementation * - * It may make better sense to provide a basic stream access on top of the framed file format - * The FileTransport can then be a user of this framed file format with some additional logic - * for chunking. + * <p>It may make better sense to provide a basic stream access on top of the framed file format The + * FileTransport can then be a user of this framed file format with some additional logic for + * chunking. */ public class TFileTransport extends TTransport { @@ -46,15 +45,16 @@ public class TFileTransport extends TTransport { public void trunc() { pos = count = 0; } + public TruncableBufferedInputStream(InputStream in) { super(in); } + public TruncableBufferedInputStream(InputStream in, int size) { super(in, size); } } - public static class Event { private byte[] buf_; private int nread_; @@ -70,64 +70,81 @@ public class TFileTransport extends TTransport { nread_ = navailable_ = 0; } - public byte[] getBuf() { return buf_;} - public int getSize() { return buf_.length; } + public byte[] getBuf() { + return buf_; + } + public int getSize() { + return buf_.length; + } - public void setAvailable(int sz) { nread_ = 0; navailable_=sz;} - public int getRemaining() { return (navailable_ - nread_); } + public void setAvailable(int sz) { + nread_ = 0; + navailable_ = sz; + } + + public int getRemaining() { + return (navailable_ - nread_); + } public int emit(byte[] buf, int offset, int ndesired) { - if((ndesired == 0) || (ndesired > getRemaining())) - ndesired = getRemaining(); + if ((ndesired == 0) || (ndesired > getRemaining())) ndesired = getRemaining(); - if(ndesired <= 0) - return (ndesired); + if (ndesired <= 0) return (ndesired); System.arraycopy(buf_, nread_, buf, offset, ndesired); nread_ += ndesired; - return(ndesired); + return (ndesired); } } - public static class ChunkState { - /** - * Chunk Size. Must be same across all implementations - */ + public static class ChunkState { + /** Chunk Size. Must be same across all implementations */ public static final int DEFAULT_CHUNK_SIZE = 16 * 1024 * 1024; private int chunk_size_ = DEFAULT_CHUNK_SIZE; private long offset_ = 0; public ChunkState() {} - public ChunkState(int chunk_size) { chunk_size_ = chunk_size; } - public void skip(int size) {offset_ += size; } - public void seek(long offset) {offset_ = offset;} + public ChunkState(int chunk_size) { + chunk_size_ = chunk_size; + } - public int getChunkSize() { return chunk_size_;} - public int getChunkNum() { return ((int)(offset_/chunk_size_));} - public int getRemaining() { return (chunk_size_ - ((int)(offset_ % chunk_size_)));} - public long getOffset() { return (offset_);} + public void skip(int size) { + offset_ += size; + } + + public void seek(long offset) { + offset_ = offset; + } + + public int getChunkSize() { + return chunk_size_; + } + + public int getChunkNum() { + return ((int) (offset_ / chunk_size_)); + } + + public int getRemaining() { + return (chunk_size_ - ((int) (offset_ % chunk_size_))); + } + + public long getOffset() { + return (offset_); + } } public enum TailPolicy { - NOWAIT(0, 0), - WAIT_FOREVER(500, -1); + WAIT_FOREVER(500, -1); - /** - * Time in milliseconds to sleep before next read - * If 0, no sleep - */ + /** Time in milliseconds to sleep before next read If 0, no sleep */ public final int timeout_; - /** - * Number of retries before giving up - * if 0, no retries - * if -1, retry forever - */ + /** Number of retries before giving up if 0, no retries if -1, retry forever */ public final int retries_; /** @@ -136,48 +153,31 @@ public class TFileTransport extends TTransport { * @param timeout sleep time for this particular policy * @param retries number of retries */ - TailPolicy(int timeout, int retries) { timeout_ = timeout; retries_ = retries; } } - /** - * Current tailing policy - */ + /** Current tailing policy */ TailPolicy currentPolicy_ = TailPolicy.NOWAIT; - - /** - * Underlying file being read - */ + /** Underlying file being read */ protected TSeekableFile inputFile_ = null; - /** - * Underlying outputStream - */ + /** Underlying outputStream */ protected OutputStream outputStream_ = null; - - /** - * Event currently read in - */ + /** Event currently read in */ Event currentEvent_ = null; - /** - * InputStream currently being used for reading - */ + /** InputStream currently being used for reading */ InputStream inputStream_ = null; - /** - * current Chunk state - */ + /** current Chunk state */ ChunkState cs = null; - /** - * is read only? - */ + /** is read only? */ private boolean readOnly_ = false; /** @@ -201,7 +201,6 @@ public class TFileTransport extends TTransport { return (old); } - /** * Initialize read input stream * @@ -210,8 +209,8 @@ public class TFileTransport extends TTransport { private InputStream createInputStream() throws TTransportException { InputStream is; try { - if(inputStream_ != null) { - ((TruncableBufferedInputStream)inputStream_).trunc(); + if (inputStream_ != null) { + ((TruncableBufferedInputStream) inputStream_).trunc(); is = inputStream_; } else { is = new TruncableBufferedInputStream(inputFile_.getInputStream()); @@ -219,7 +218,7 @@ public class TFileTransport extends TTransport { } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); } - return(is); + return (is); } /** @@ -229,18 +228,17 @@ public class TFileTransport extends TTransport { * @param buf Buffer to read into * @param off Offset in buffer to read into * @param len Number of bytes to read - * @param tp policy to use if we hit EOF - * + * @param tp policy to use if we hit EOF * @return number of bytes read */ - private int tailRead(InputStream is, byte[] buf, - int off, int len, TailPolicy tp) throws TTransportException { + private int tailRead(InputStream is, byte[] buf, int off, int len, TailPolicy tp) + throws TTransportException { int orig_len = len; try { int retries = 0; - while(len > 0) { + while (len > 0) { int cnt = is.read(buf, off, len); - if(cnt > 0) { + if (cnt > 0) { off += cnt; len -= cnt; retries = 0; @@ -249,40 +247,40 @@ public class TFileTransport extends TTransport { // EOF retries++; - if((tp.retries_ != -1) && tp.retries_ < retries) - return (orig_len - len); + if ((tp.retries_ != -1) && tp.retries_ < retries) return (orig_len - len); - if(tp.timeout_ > 0) { - try {Thread.sleep(tp.timeout_);} catch(InterruptedException e) {} + if (tp.timeout_ > 0) { + try { + Thread.sleep(tp.timeout_); + } catch (InterruptedException e) { + } } } else { // either non-zero or -1 is what the contract says! - throw new - TTransportException("Unexpected return from InputStream.read = " - + cnt); + throw new TTransportException("Unexpected return from InputStream.read = " + cnt); } } } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); } - return(orig_len - len); + return (orig_len - len); } /** * Event is corrupted. Do recovery * - * @return true if recovery could be performed and we can read more data - * false is returned only when nothing more can be read + * @return true if recovery could be performed and we can read more data false is returned only + * when nothing more can be read */ private boolean performRecovery() throws TTransportException { int numChunks = getNumChunks(); int curChunk = cs.getChunkNum(); - if(curChunk >= (numChunks-1)) { + if (curChunk >= (numChunks - 1)) { return false; } - seekToChunk(curChunk+1); + seekToChunk(curChunk + 1); return true; } @@ -301,27 +299,27 @@ public class TFileTransport extends TTransport { do { // corner case. read to end of chunk nrequested = cs.getRemaining(); - if(nrequested < 4) { + if (nrequested < 4) { nread = tailRead(inputStream_, ebytes, 0, nrequested, currentPolicy_); - if(nread != nrequested) { - return(false); + if (nread != nrequested) { + return (false); } } // assuming serialized on little endian machine nread = tailRead(inputStream_, ebytes, 0, 4, currentPolicy_); - if(nread != 4) { - return(false); + if (nread != 4) { + return (false); } - esize=0; - for(int i=3; i>=0; i--) { - int val = (0x000000ff & (int)ebytes[i]); - esize |= (val << (i*8)); + esize = 0; + for (int i = 3; i >= 0; i--) { + int val = (0x000000ff & (int) ebytes[i]); + esize |= (val << (i * 8)); } // check if event is corrupted and do recovery as required - if(esize > cs.getRemaining()) { + if (esize > cs.getRemaining()) { throw new TTransportException("FileTransport error: bad event size"); /* if(performRecovery()) { @@ -334,17 +332,16 @@ public class TFileTransport extends TTransport { } while (esize == 0); // reset existing event or get a larger one - if(currentEvent_.getSize() < esize) - currentEvent_ = new Event(new byte [esize]); + if (currentEvent_.getSize() < esize) currentEvent_ = new Event(new byte[esize]); // populate the event byte[] buf = currentEvent_.getBuf(); nread = tailRead(inputStream_, buf, 0, esize, currentPolicy_); - if(nread != esize) { - return(false); + if (nread != esize) { + return (false); } currentEvent_.setAvailable(esize); - return(true); + return (true); } /** @@ -356,37 +353,31 @@ public class TFileTransport extends TTransport { return ((inputStream_ != null) && (readOnly_ || (outputStream_ != null))); } - /** - * Diverging from the cpp model and sticking to the TSocket model - * Files are not opened in ctor - but in explicit open call + * Diverging from the cpp model and sticking to the TSocket model Files are not opened in ctor - + * but in explicit open call */ public void open() throws TTransportException { - if (isOpen()) - throw new TTransportException(TTransportException.ALREADY_OPEN); + if (isOpen()) throw new TTransportException(TTransportException.ALREADY_OPEN); try { inputStream_ = createInputStream(); cs = new ChunkState(); - currentEvent_ = new Event(new byte [256]); + currentEvent_ = new Event(new byte[256]); - if(!readOnly_) - outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream()); + if (!readOnly_) outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream()); } catch (IOException iox) { throw new TTransportException(TTransportException.NOT_OPEN, iox); } } - /** - * Closes the transport. - */ + /** Closes the transport. */ public void close() { if (inputFile_ != null) { try { inputFile_.close(); } catch (IOException iox) { - LOGGER.warn("WARNING: Error closing input file: " + - iox.getMessage()); + LOGGER.warn("WARNING: Error closing input file: " + iox.getMessage()); } inputFile_ = null; } @@ -394,14 +385,12 @@ public class TFileTransport extends TTransport { try { outputStream_.close(); } catch (IOException iox) { - LOGGER.warn("WARNING: Error closing output stream: " + - iox.getMessage()); + LOGGER.warn("WARNING: Error closing output stream: " + iox.getMessage()); } outputStream_ = null; } } - /** * File Transport ctor * @@ -425,30 +414,26 @@ public class TFileTransport extends TTransport { readOnly_ = readOnly; } - /** - * Cloned from TTransport.java:readAll(). Only difference is throwing an EOF exception - * where one is detected. + * Cloned from TTransport.java:readAll(). Only difference is throwing an EOF exception where one + * is detected. */ - public int readAll(byte[] buf, int off, int len) - throws TTransportException { + public int readAll(byte[] buf, int off, int len) throws TTransportException { int got = 0; int ret = 0; while (got < len) { - ret = read(buf, off+got, len-got); + ret = read(buf, off + got, len - got); if (ret < 0) { throw new TTransportException("Error in reading from file"); } - if(ret == 0) { - throw new TTransportException(TTransportException.END_OF_FILE, - "End of File reached"); + if (ret == 0) { + throw new TTransportException(TTransportException.END_OF_FILE, "End of File reached"); } got += ret; } return got; } - /** * Reads up to len bytes into buffer buf, starting at offset off. * @@ -459,13 +444,11 @@ public class TFileTransport extends TTransport { * @throws TTransportException if there was an error reading data */ public int read(byte[] buf, int off, int len) throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before reading"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before reading"); - if(currentEvent_.getRemaining() == 0) { - if(!readEvent()) - return(0); + if (currentEvent_.getRemaining() == 0) { + if (!readEvent()) return (0); } int nread = currentEvent_.emit(buf, off, len); @@ -473,15 +456,12 @@ public class TFileTransport extends TTransport { } public int getNumChunks() throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before getNumChunks"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getNumChunks"); try { long len = inputFile_.length(); - if(len == 0) - return 0; - else - return (((int)(len/cs.getChunkSize())) + 1); + if (len == 0) return 0; + else return (((int) (len / cs.getChunkSize())) + 1); } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); @@ -489,18 +469,14 @@ public class TFileTransport extends TTransport { } public int getCurChunk() throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before getCurChunk"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getCurChunk"); return (cs.getChunkNum()); - } - public void seekToChunk(int chunk) throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before seeking"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking"); int numChunks = getNumChunks(); @@ -519,45 +495,47 @@ public class TFileTransport extends TTransport { chunk = 0; } - long eofOffset=0; + long eofOffset = 0; boolean seekToEnd = (chunk >= numChunks); - if(seekToEnd) { + if (seekToEnd) { chunk = chunk - 1; - try { eofOffset = inputFile_.length(); } - catch (IOException iox) {throw new TTransportException(iox.getMessage(), - iox);} + try { + eofOffset = inputFile_.length(); + } catch (IOException iox) { + throw new TTransportException(iox.getMessage(), iox); + } } - if(chunk*cs.getChunkSize() != cs.getOffset()) { - try { inputFile_.seek((long)chunk*cs.getChunkSize()); } - catch (IOException iox) { - throw new TTransportException("Seek to chunk " + - chunk + " " +iox.getMessage(), iox); + if (chunk * cs.getChunkSize() != cs.getOffset()) { + try { + inputFile_.seek((long) chunk * cs.getChunkSize()); + } catch (IOException iox) { + throw new TTransportException("Seek to chunk " + chunk + " " + iox.getMessage(), iox); } - cs.seek((long)chunk*cs.getChunkSize()); + cs.seek((long) chunk * cs.getChunkSize()); currentEvent_.setAvailable(0); inputStream_ = createInputStream(); } - if(seekToEnd) { + if (seekToEnd) { // waiting forever here - otherwise we can hit EOF and end up // having consumed partial data from the data stream. TailPolicy old = setTailPolicy(TailPolicy.WAIT_FOREVER); - while(cs.getOffset() < eofOffset) { readEvent(); } + while (cs.getOffset() < eofOffset) { + readEvent(); + } currentEvent_.setAvailable(0); setTailPolicy(old); } } public void seekToEnd() throws TTransportException { - if(!isOpen()) - throw new TTransportException(TTransportException.NOT_OPEN, - "Must open before seeking"); + if (!isOpen()) + throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking"); seekToChunk(getNumChunks()); } - /** * Writes up to len bytes from the buffer. * @@ -579,36 +557,30 @@ public class TFileTransport extends TTransport { throw new TTransportException("Not Supported"); } - @Override public TConfiguration getConfiguration() { return null; } @Override - public void updateKnownMessageSize(long size) throws TTransportException { - - } + public void updateKnownMessageSize(long size) throws TTransportException {} @Override - public void checkReadBytesAvailable(long numBytes) throws TTransportException { - - } + public void checkReadBytesAvailable(long numBytes) throws TTransportException {} - /** - * test program - * - */ + /** test program */ public static void main(String[] args) throws Exception { int num_chunks = 10; - if((args.length < 1) || args[0].equals("--help") - || args[0].equals("-h") || args[0].equals("-?")) { + if ((args.length < 1) + || args[0].equals("--help") + || args[0].equals("-h") + || args[0].equals("-?")) { printUsage(); } - if(args.length > 1) { + if (args.length > 1) { try { num_chunks = Integer.parseInt(args[1]); } catch (Exception e) { @@ -619,15 +591,15 @@ public class TFileTransport extends TTransport { TFileTransport t = new TFileTransport(args[0], true); t.open(); - LOGGER.info("NumChunks="+t.getNumChunks()); + LOGGER.info("NumChunks=" + t.getNumChunks()); Random r = new Random(); - for(int j=0; j<num_chunks; j++) { + for (int j = 0; j < num_chunks; j++) { byte[] buf = new byte[4096]; - int cnum = r.nextInt(t.getNumChunks()-1); - LOGGER.info("Reading chunk "+cnum); + int cnum = r.nextInt(t.getNumChunks() - 1); + LOGGER.info("Reading chunk " + cnum); t.seekToChunk(cnum); - for(int i=0; i<4096; i++) { + for (int i = 0; i < 4096; i++) { t.read(buf, 0, 4096); } } @@ -638,5 +610,4 @@ public class TFileTransport extends TTransport { LOGGER.error(" (Opens and reads num_chunks chunks from file randomly)"); System.exit(1); } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java b/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java index 574682248..e514dd54e 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/THttpClient.java @@ -28,7 +28,6 @@ import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; - import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; @@ -40,32 +39,26 @@ import org.apache.http.entity.ByteArrayEntity; import org.apache.thrift.TConfiguration; /** - * HTTP implementation of the TTransport interface. Used for working with a - * Thrift web services implementation (using for example TServlet). + * HTTP implementation of the TTransport interface. Used for working with a Thrift web services + * implementation (using for example TServlet). * - * This class offers two implementations of the HTTP transport. - * One uses HttpURLConnection instances, the other HttpClient from Apache - * Http Components. - * The chosen implementation depends on the constructor used to - * create the THttpClient instance. - * Using the THttpClient(String url) constructor or passing null as the - * HttpClient to THttpClient(String url, HttpClient client) will create an - * instance which will use HttpURLConnection. + * <p>This class offers two implementations of the HTTP transport. One uses HttpURLConnection + * instances, the other HttpClient from Apache Http Components. The chosen implementation depends on + * the constructor used to create the THttpClient instance. Using the THttpClient(String url) + * constructor or passing null as the HttpClient to THttpClient(String url, HttpClient client) will + * create an instance which will use HttpURLConnection. * - * When using HttpClient, the following configuration leads to 5-15% - * better performance than the HttpURLConnection implementation: + * <p>When using HttpClient, the following configuration leads to 5-15% better performance than the + * HttpURLConnection implementation: * - * http.protocol.version=HttpVersion.HTTP_1_1 - * http.protocol.content-charset=UTF-8 - * http.protocol.expect-continue=false - * http.connection.stalecheck=false + * <p>http.protocol.version=HttpVersion.HTTP_1_1 http.protocol.content-charset=UTF-8 + * http.protocol.expect-continue=false http.connection.stalecheck=false * - * Also note that under high load, the HttpURLConnection implementation - * may exhaust the open file descriptor limit. + * <p>Also note that under high load, the HttpURLConnection implementation may exhaust the open file + * descriptor limit. * * @see <a href="https://issues.apache.org/jira/browse/THRIFT-970">THRIFT-970</a> */ - public class THttpClient extends TEndpointTransport { private final URL url_; @@ -78,13 +71,14 @@ public class THttpClient extends TEndpointTransport { private int readTimeout_ = 0; - private Map<String,String> customHeaders_ = null; + private Map<String, String> customHeaders_ = null; private final HttpHost host; private final HttpClient client; - private static final Map<String, String> DEFAULT_HEADERS = Collections.unmodifiableMap(getDefaultHeaders()); + private static final Map<String, String> DEFAULT_HEADERS = + Collections.unmodifiableMap(getDefaultHeaders()); public static class Factory extends TTransportFactory { @@ -137,12 +131,17 @@ public class THttpClient extends TEndpointTransport { } } - public THttpClient(TConfiguration config, String url, HttpClient client) throws TTransportException { + public THttpClient(TConfiguration config, String url, HttpClient client) + throws TTransportException { super(config); try { url_ = new URL(url); this.client = client; - this.host = new HttpHost(url_.getHost(), -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), url_.getProtocol()); + this.host = + new HttpHost( + url_.getHost(), + -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), + url_.getProtocol()); } catch (IOException iox) { throw new TTransportException(iox); } @@ -153,7 +152,11 @@ public class THttpClient extends TEndpointTransport { try { url_ = new URL(url); this.client = client; - this.host = new HttpHost(url_.getHost(), -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), url_.getProtocol()); + this.host = + new HttpHost( + url_.getHost(), + -1 == url_.getPort() ? url_.getDefaultPort() : url_.getPort(), + url_.getProtocol()); } catch (IOException iox) { throw new TTransportException(iox); } @@ -167,7 +170,7 @@ public class THttpClient extends TEndpointTransport { readTimeout_ = timeout; } - public void setCustomHeaders(Map<String,String> headers) { + public void setCustomHeaders(Map<String, String> headers) { customHeaders_ = new HashMap<>(headers); } @@ -226,7 +229,8 @@ public class THttpClient extends TEndpointTransport { private RequestConfig getRequestConfig() { RequestConfig requestConfig = RequestConfig.DEFAULT; if (connectTimeout_ > 0) { - requestConfig = RequestConfig.copy(requestConfig).setConnectionRequestTimeout(connectTimeout_).build(); + requestConfig = + RequestConfig.copy(requestConfig).setConnectionRequestTimeout(connectTimeout_).build(); } if (readTimeout_ > 0) { requestConfig = RequestConfig.copy(requestConfig).setSocketTimeout(readTimeout_).build(); @@ -243,19 +247,19 @@ public class THttpClient extends TEndpointTransport { } /** - * copy from org.apache.http.util.EntityUtils#consume. Android has it's own httpcore - * that doesn't have a consume. + * copy from org.apache.http.util.EntityUtils#consume. Android has it's own httpcore that doesn't + * have a consume. */ private static void consume(final HttpEntity entity) throws IOException { - if (entity == null) { - return; - } - if (entity.isStreaming()) { - InputStream instream = entity.getContent(); - if (instream != null) { - instream.close(); - } + if (entity == null) { + return; + } + if (entity.isStreaming()) { + InputStream instream = entity.getContent(); + if (instream != null) { + instream.close(); } + } } private void flushUsingHttpClient() throws TTransportException { @@ -311,12 +315,10 @@ public class THttpClient extends TEndpointTransport { } /** - * Read the responses into a byte array so we can release the connection - * early. This implies that the whole content will have to be read in - * memory, and that momentarily we might use up twice the memory (while the - * thrift struct is being read up the chain). - * Proceeding differently might lead to exhaustion of connections and thus - * to app failure. + * Read the responses into a byte array so we can release the connection early. This implies that + * the whole content will have to be read in memory, and that momentarily we might use up twice + * the memory (while the thrift struct is being read up the chain). Proceeding differently might + * lead to exhaustion of connections and thus to app failure. * * @param is input stream * @return read bytes @@ -348,7 +350,7 @@ public class THttpClient extends TEndpointTransport { try { // Create connection object - HttpURLConnection connection = (HttpURLConnection)url_.openConnection(); + HttpURLConnection connection = (HttpURLConnection) url_.openConnection(); // Timeouts, only if explicitly set if (connectTimeout_ > 0) { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java index d5b459c13..edfd1f414 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TIOStreamTransport.java @@ -19,21 +19,18 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketTimeoutException; +import org.apache.thrift.TConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * This is the most commonly used base transport. It takes an InputStream or - * an OutputStream or both and uses it/them to perform transport operations. - * This allows for compatibility with all the nice constructs Java already - * has to provide a variety of types of streams. - * + * This is the most commonly used base transport. It takes an InputStream or an OutputStream or both + * and uses it/them to perform transport operations. This allows for compatibility with all the nice + * constructs Java already has to provide a variety of types of streams. */ public class TIOStreamTransport extends TEndpointTransport { @@ -46,16 +43,16 @@ public class TIOStreamTransport extends TEndpointTransport { protected OutputStream outputStream_ = null; /** - * Subclasses can invoke the default constructor and then assign the input - * streams in the open method. + * Subclasses can invoke the default constructor and then assign the input streams in the open + * method. */ protected TIOStreamTransport(TConfiguration config) throws TTransportException { super(config); } /** - * Subclasses can invoke the default constructor and then assign the input - * streams in the open method. + * Subclasses can invoke the default constructor and then assign the input streams in the open + * method. */ protected TIOStreamTransport() throws TTransportException { super(new TConfiguration()); @@ -109,7 +106,8 @@ public class TIOStreamTransport extends TEndpointTransport { * @param is Input stream to read from * @param os Output stream to read from */ - public TIOStreamTransport(TConfiguration config, InputStream is, OutputStream os) throws TTransportException { + public TIOStreamTransport(TConfiguration config, InputStream is, OutputStream os) + throws TTransportException { super(config); inputStream_ = is; outputStream_ = os; @@ -127,22 +125,15 @@ public class TIOStreamTransport extends TEndpointTransport { outputStream_ = os; } - /** - * - * @return false after close is called. - */ + /** @return false after close is called. */ public boolean isOpen() { return inputStream_ != null || outputStream_ != null; } - /** - * The streams must already be open. This method does nothing. - */ + /** The streams must already be open. This method does nothing. */ public void open() throws TTransportException {} - /** - * Closes both the input and output streams. - */ + /** Closes both the input and output streams. */ public void close() { try { if (inputStream_ != null) { @@ -165,12 +156,11 @@ public class TIOStreamTransport extends TEndpointTransport { } } - /** - * Reads from the underlying input stream if not null. - */ + /** Reads from the underlying input stream if not null. */ public int read(byte[] buf, int off, int len) throws TTransportException { if (inputStream_ == null) { - throw new TTransportException(TTransportException.NOT_OPEN, "Cannot read from null inputStream"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot read from null inputStream"); } int bytesRead; try { @@ -186,12 +176,11 @@ public class TIOStreamTransport extends TEndpointTransport { return bytesRead; } - /** - * Writes to the underlying output stream if not null. - */ + /** Writes to the underlying output stream if not null. */ public void write(byte[] buf, int off, int len) throws TTransportException { if (outputStream_ == null) { - throw new TTransportException(TTransportException.NOT_OPEN, "Cannot write to null outputStream"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot write to null outputStream"); } try { outputStream_.write(buf, off, len); @@ -200,9 +189,7 @@ public class TIOStreamTransport extends TEndpointTransport { } } - /** - * Flushes the underlying output stream if not null. - */ + /** Flushes the underlying output stream if not null. */ public void flush() throws TTransportException { if (outputStream_ == null) { throw new TTransportException(TTransportException.NOT_OPEN, "Cannot flush null outputStream"); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java index d9a3cc928..9ce1b2122 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryBuffer.java @@ -19,19 +19,15 @@ package org.apache.thrift.transport; +import java.nio.charset.Charset; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; -import java.nio.charset.Charset; - -/** - * Memory buffer-based implementation of the TTransport interface. - */ +/** Memory buffer-based implementation of the TTransport interface. */ public class TMemoryBuffer extends TEndpointTransport { /** - * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The - * internal buffer will grow as necessary to accommodate the size of the data - * being written to it. + * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The internal buffer will + * grow as necessary to accommodate the size of the data being written to it. * * @param size the initial size of the buffer * @throws TTransportException on error initializing the underlying transport. @@ -43,9 +39,8 @@ public class TMemoryBuffer extends TEndpointTransport { } /** - * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The - * internal buffer will grow as necessary to accommodate the size of the data - * being written to it. + * Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The internal buffer will + * grow as necessary to accommodate the size of the data being written to it. * * @param config the configuration to use. * @param size the initial size of the buffer @@ -91,8 +86,8 @@ public class TMemoryBuffer extends TEndpointTransport { } /** - * Output the contents of the memory buffer as a String, using the supplied - * encoding + * Output the contents of the memory buffer as a String, using the supplied encoding + * * @param charset the encoding to use * @return the contents of the memory buffer as a String */ @@ -104,7 +99,7 @@ public class TMemoryBuffer extends TEndpointTransport { StringBuilder buf = new StringBuilder(); byte[] bytes = arr_.toByteArray(); for (int i = 0; i < bytes.length; i++) { - buf.append(pos_ == i ? "==>" : "" ).append(Integer.toHexString(bytes[i] & 0xff)).append(" "); + buf.append(pos_ == i ? "==>" : "").append(Integer.toHexString(bytes[i] & 0xff)).append(" "); } return buf.toString(); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java index 6cb06fc37..375e2b72a 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryInputTransport.java @@ -38,7 +38,8 @@ public final class TMemoryInputTransport extends TEndpointTransport { this(new TConfiguration(), buf); } - public TMemoryInputTransport(TConfiguration _configuration, byte[] buf) throws TTransportException { + public TMemoryInputTransport(TConfiguration _configuration, byte[] buf) + throws TTransportException { this(_configuration, buf, 0, buf.length); } @@ -46,7 +47,8 @@ public final class TMemoryInputTransport extends TEndpointTransport { this(new TConfiguration(), buf, offset, length); } - public TMemoryInputTransport(TConfiguration _configuration, byte[] buf, int offset, int length) throws TTransportException { + public TMemoryInputTransport(TConfiguration _configuration, byte[] buf, int offset, int length) + throws TTransportException { super(_configuration); reset(buf, offset, length); updateKnownMessageSize(length); @@ -120,5 +122,4 @@ public final class TMemoryInputTransport extends TEndpointTransport { public void consumeBuffer(int len) { pos_ += len; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java index 0172ca816..2e38588e5 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TMemoryTransport.java @@ -20,13 +20,10 @@ package org.apache.thrift.transport; import java.nio.ByteBuffer; - import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; -/** - * In memory transport with separate buffers for input and output. - */ +/** In memory transport with separate buffers for input and output. */ public class TMemoryTransport extends TEndpointTransport { private final ByteBuffer inputBuffer; @@ -51,9 +48,7 @@ public class TMemoryTransport extends TEndpointTransport { return true; } - /** - * Opening on an in memory transport should have no effect. - */ + /** Opening on an in memory transport should have no effect. */ @Override public void open() { // Do nothing. @@ -69,7 +64,8 @@ public class TMemoryTransport extends TEndpointTransport { checkReadBytesAvailable(len); int remaining = inputBuffer.remaining(); if (remaining < len) { - throw new TTransportException(TTransportException.END_OF_FILE, + throw new TTransportException( + TTransportException.END_OF_FILE, "There's only " + remaining + "bytes, but it asks for " + len); } inputBuffer.get(buf, off, len); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java index 535fd6f51..998379746 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerSocket.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.transport; import java.io.IOException; @@ -29,72 +28,69 @@ import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; - import org.apache.thrift.TConfiguration; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Wrapper around ServerSocketChannel - */ +/** Wrapper around ServerSocketChannel */ public class TNonblockingServerSocket extends TNonblockingServerTransport { - private static final Logger LOGGER = LoggerFactory.getLogger(TNonblockingServerSocket.class.getName()); + private static final Logger LOGGER = + LoggerFactory.getLogger(TNonblockingServerSocket.class.getName()); - /** - * This channel is where all the nonblocking magic happens. - */ + /** This channel is where all the nonblocking magic happens. */ private ServerSocketChannel serverSocketChannel = null; - /** - * Underlying ServerSocket object - */ + /** Underlying ServerSocket object */ private ServerSocket serverSocket_ = null; - /** - * Timeout for client sockets from accept - */ + /** Timeout for client sockets from accept */ private int clientTimeout_ = 0; - /** - * Limit for client sockets request size - */ + /** Limit for client sockets request size */ private int maxFrameSize_ = 0; - public static class NonblockingAbstractServerSocketArgs extends - AbstractServerTransportArgs<NonblockingAbstractServerSocketArgs> {} + public static class NonblockingAbstractServerSocketArgs + extends AbstractServerTransportArgs<NonblockingAbstractServerSocketArgs> {} - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TNonblockingServerSocket(int port) throws TTransportException { this(port, 0); } - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TNonblockingServerSocket(int port, int clientTimeout) throws TTransportException { this(port, clientTimeout, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } - public TNonblockingServerSocket(int port, int clientTimeout, int maxFrameSize) throws TTransportException { - this(new NonblockingAbstractServerSocketArgs().port(port).clientTimeout(clientTimeout).maxFrameSize(maxFrameSize)); + public TNonblockingServerSocket(int port, int clientTimeout, int maxFrameSize) + throws TTransportException { + this( + new NonblockingAbstractServerSocketArgs() + .port(port) + .clientTimeout(clientTimeout) + .maxFrameSize(maxFrameSize)); } public TNonblockingServerSocket(InetSocketAddress bindAddr) throws TTransportException { this(bindAddr, 0); } - public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout) throws TTransportException { + public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout) + throws TTransportException { this(bindAddr, clientTimeout, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } - public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout, int maxFrameSize) throws TTransportException { - this(new NonblockingAbstractServerSocketArgs().bindAddr(bindAddr).clientTimeout(clientTimeout).maxFrameSize(maxFrameSize)); + public TNonblockingServerSocket(InetSocketAddress bindAddr, int clientTimeout, int maxFrameSize) + throws TTransportException { + this( + new NonblockingAbstractServerSocketArgs() + .bindAddr(bindAddr) + .clientTimeout(clientTimeout) + .maxFrameSize(maxFrameSize)); } - public TNonblockingServerSocket(NonblockingAbstractServerSocketArgs args) throws TTransportException { + public TNonblockingServerSocket(NonblockingAbstractServerSocketArgs args) + throws TTransportException { clientTimeout_ = args.clientTimeout; maxFrameSize_ = args.maxFrameSize; try { @@ -109,7 +105,8 @@ public class TNonblockingServerSocket extends TNonblockingServerTransport { serverSocket_.bind(args.bindAddr, args.backlog); } catch (IOException ioe) { serverSocket_ = null; - throw new TTransportException("Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); + throw new TTransportException( + "Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); } } @@ -173,8 +170,7 @@ public class TNonblockingServerSocket extends TNonblockingServerTransport { } public int getPort() { - if (serverSocket_ == null) - return -1; + if (serverSocket_ == null) return -1; return serverSocket_.getLocalPort(); } @@ -182,5 +178,4 @@ public class TNonblockingServerSocket extends TNonblockingServerTransport { ServerSocketChannel getServerSocketChannel() { return serverSocketChannel; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java index 53d084281..8dfdefb9b 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingServerTransport.java @@ -17,20 +17,16 @@ * under the License. */ - package org.apache.thrift.transport; import java.nio.channels.Selector; -/** - * Server transport that can be operated in a nonblocking fashion. - */ +/** Server transport that can be operated in a nonblocking fashion. */ public abstract class TNonblockingServerTransport extends TServerTransport { public abstract void registerSelector(Selector selector); /** - * * @return an incoming connection or null if there is none. * @throws TTransportException on error during this operation. */ diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java index 13c858648..0f4076c8d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingSocket.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.transport; import java.io.IOException; @@ -29,21 +28,16 @@ import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; - import org.apache.thrift.TConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Transport for use with async client. - */ +/** Transport for use with async client. */ public class TNonblockingSocket extends TNonblockingTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TNonblockingSocket.class.getName()); - /** - * Host and port if passed in, used for lazy non-blocking connect. - */ + /** Host and port if passed in, used for lazy non-blocking connect. */ private final SocketAddress socketAddress_; private final SocketChannel socketChannel_; @@ -54,11 +48,13 @@ public class TNonblockingSocket extends TNonblockingTransport { /** * Create a new nonblocking socket transport that will be connected to host:port. + * * @param host * @param port * @throws IOException */ - public TNonblockingSocket(String host, int port, int timeout) throws IOException, TTransportException { + public TNonblockingSocket(String host, int port, int timeout) + throws IOException, TTransportException { this(SocketChannel.open(), timeout, new InetSocketAddress(host, port)); } @@ -74,12 +70,13 @@ public class TNonblockingSocket extends TNonblockingTransport { } private TNonblockingSocket(SocketChannel socketChannel, int timeout, SocketAddress socketAddress) - throws IOException, TTransportException { + throws IOException, TTransportException { this(new TConfiguration(), socketChannel, timeout, socketAddress); } - private TNonblockingSocket(TConfiguration config, SocketChannel socketChannel, int timeout, SocketAddress socketAddress) - throws IOException, TTransportException { + private TNonblockingSocket( + TConfiguration config, SocketChannel socketChannel, int timeout, SocketAddress socketAddress) + throws IOException, TTransportException { super(config); socketChannel_ = socketChannel; socketAddress_ = socketAddress; @@ -96,8 +93,8 @@ public class TNonblockingSocket extends TNonblockingTransport { } /** - * Register the new SocketChannel with our Selector, indicating - * we'd like to be notified when it's ready for I/O. + * Register the new SocketChannel with our Selector, indicating we'd like to be notified when it's + * ready for I/O. * * @param selector * @return the selection key for this socket. @@ -107,7 +104,8 @@ public class TNonblockingSocket extends TNonblockingTransport { } /** - * Sets the socket timeout, although this implementation never uses blocking operations so it is unused. + * Sets the socket timeout, although this implementation never uses blocking operations so it is + * unused. * * @param timeout Milliseconds timeout */ @@ -119,31 +117,23 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Returns a reference to the underlying SocketChannel. - */ + /** Returns a reference to the underlying SocketChannel. */ public SocketChannel getSocketChannel() { return socketChannel_; } - /** - * Checks whether the socket is connected. - */ + /** Checks whether the socket is connected. */ public boolean isOpen() { // isConnected() does not return false after close(), but isOpen() does return socketChannel_.isOpen() && socketChannel_.isConnected(); } - /** - * Do not call, the implementation provides its own lazy non-blocking connect. - */ + /** Do not call, the implementation provides its own lazy non-blocking connect. */ public void open() throws TTransportException { throw new RuntimeException("open() is not implemented for TNonblockingSocket"); } - /** - * Perform a nonblocking read into buffer. - */ + /** Perform a nonblocking read into buffer. */ public int read(ByteBuffer buffer) throws TTransportException { try { return socketChannel_.read(buffer); @@ -152,13 +142,11 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Reads from the underlying input stream if not null. - */ + /** Reads from the underlying input stream if not null. */ public int read(byte[] buf, int off, int len) throws TTransportException { if ((socketChannel_.validOps() & SelectionKey.OP_READ) != SelectionKey.OP_READ) { - throw new TTransportException(TTransportException.NOT_OPEN, - "Cannot read from write-only socket channel"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot read from write-only socket channel"); } try { return socketChannel_.read(ByteBuffer.wrap(buf, off, len)); @@ -167,9 +155,7 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Perform a nonblocking write of the data in buffer; - */ + /** Perform a nonblocking write of the data in buffer; */ public int write(ByteBuffer buffer) throws TTransportException { try { return socketChannel_.write(buffer); @@ -178,27 +164,21 @@ public class TNonblockingSocket extends TNonblockingTransport { } } - /** - * Writes to the underlying output stream if not null. - */ + /** Writes to the underlying output stream if not null. */ public void write(byte[] buf, int off, int len) throws TTransportException { if ((socketChannel_.validOps() & SelectionKey.OP_WRITE) != SelectionKey.OP_WRITE) { - throw new TTransportException(TTransportException.NOT_OPEN, - "Cannot write to write-only socket channel"); + throw new TTransportException( + TTransportException.NOT_OPEN, "Cannot write to write-only socket channel"); } write(ByteBuffer.wrap(buf, off, len)); } - /** - * Noop. - */ + /** Noop. */ public void flush() throws TTransportException { // Not supported by SocketChannel. } - /** - * Closes the socket. - */ + /** Closes the socket. */ public void close() { try { socketChannel_.close(); @@ -219,7 +199,10 @@ public class TNonblockingSocket extends TNonblockingTransport { @Override public String toString() { - return "[remote: " + socketChannel_.socket().getRemoteSocketAddress() + - ", local: " + socketChannel_.socket().getLocalAddress() + "]" ; + return "[remote: " + + socketChannel_.socket().getRemoteSocketAddress() + + ", local: " + + socketChannel_.socket().getLocalAddress() + + "]"; } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java index 30ec9d25c..ab3028ca1 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TNonblockingTransport.java @@ -19,12 +19,11 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; +import org.apache.thrift.TConfiguration; public abstract class TNonblockingTransport extends TEndpointTransport { @@ -34,16 +33,18 @@ public abstract class TNonblockingTransport extends TEndpointTransport { /** * Non-blocking connection initialization. + * * @see java.nio.channels.SocketChannel#connect(SocketAddress remote) */ public abstract boolean startConnect() throws IOException; /** * Non-blocking connection completion. + * * @see java.nio.channels.SocketChannel#finishConnect() */ public abstract boolean finishConnect() throws IOException; - public abstract SelectionKey registerSelector(Selector selector, int interests) throws IOException; - + public abstract SelectionKey registerSelector(Selector selector, int interests) + throws IOException; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java b/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java index 3389e4d2a..917f4c95d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSSLTransportFactory.java @@ -21,14 +21,13 @@ package org.apache.thrift.transport; import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.net.InetAddress; -import java.net.URL; import java.net.MalformedURLException; +import java.net.URL; import java.security.KeyStore; import java.util.Arrays; - import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocket; @@ -36,28 +35,22 @@ import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A Factory for providing and setting up Client and Server SSL wrapped - * TSocket and TServerSocket + * A Factory for providing and setting up Client and Server SSL wrapped TSocket and TServerSocket */ public class TSSLTransportFactory { - private static final Logger LOGGER = - LoggerFactory.getLogger(TSSLTransportFactory.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TSSLTransportFactory.class); /** - * Get a SSL wrapped TServerSocket bound to the specified port. In this - * configuration the default settings are used. Default settings are retrieved - * from System properties that are set. + * Get a SSL wrapped TServerSocket bound to the specified port. In this configuration the default + * settings are used. Default settings are retrieved from System properties that are set. * - * Example system properties: - * -Djavax.net.ssl.trustStore=<truststore location> - * -Djavax.net.ssl.trustStorePassword=password - * -Djavax.net.ssl.keyStore=<keystore location> + * <p>Example system properties: -Djavax.net.ssl.trustStore=<truststore location> + * -Djavax.net.ssl.trustStorePassword=password -Djavax.net.ssl.keyStore=<keystore location> * -Djavax.net.ssl.keyStorePassword=password * * @param port @@ -76,7 +69,8 @@ public class TSSLTransportFactory { * @return A SSL wrapped TServerSocket * @throws TTransportException */ - public static TServerSocket getServerSocket(int port, int clientTimeout) throws TTransportException { + public static TServerSocket getServerSocket(int port, int clientTimeout) + throws TTransportException { return getServerSocket(port, clientTimeout, false, null); } @@ -89,15 +83,17 @@ public class TSSLTransportFactory { * @return A SSL wrapped TServerSocket * @throws TTransportException */ - public static TServerSocket getServerSocket(int port, int clientTimeout, boolean clientAuth, InetAddress ifAddress) throws TTransportException { + public static TServerSocket getServerSocket( + int port, int clientTimeout, boolean clientAuth, InetAddress ifAddress) + throws TTransportException { SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); return createServer(factory, port, clientTimeout, clientAuth, ifAddress, null); } /** - * Get a configured SSL wrapped TServerSocket bound to the specified port and interface. - * Here the TSSLTransportParameters are used to set the values for the algorithms, keystore, - * truststore and other settings + * Get a configured SSL wrapped TServerSocket bound to the specified port and interface. Here the + * TSSLTransportParameters are used to set the values for the algorithms, keystore, truststore and + * other settings * * @param port * @param clientTimeout @@ -106,35 +102,47 @@ public class TSSLTransportFactory { * @return A SSL wrapped TServerSocket * @throws TTransportException */ - public static TServerSocket getServerSocket(int port, int clientTimeout, InetAddress ifAddress, TSSLTransportParameters params) throws TTransportException { + public static TServerSocket getServerSocket( + int port, int clientTimeout, InetAddress ifAddress, TSSLTransportParameters params) + throws TTransportException { if (params == null || !(params.isKeyStoreSet || params.isTrustStoreSet)) { - throw new TTransportException("Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); + throw new TTransportException( + "Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); } SSLContext ctx = createSSLContext(params); - return createServer(ctx.getServerSocketFactory(), port, clientTimeout, params.clientAuth, ifAddress, params); + return createServer( + ctx.getServerSocketFactory(), port, clientTimeout, params.clientAuth, ifAddress, params); } - private static TServerSocket createServer(SSLServerSocketFactory factory, int port, int timeout, boolean clientAuth, - InetAddress ifAddress, TSSLTransportParameters params) throws TTransportException { + private static TServerSocket createServer( + SSLServerSocketFactory factory, + int port, + int timeout, + boolean clientAuth, + InetAddress ifAddress, + TSSLTransportParameters params) + throws TTransportException { try { - SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(port, 100, ifAddress); + SSLServerSocket serverSocket = + (SSLServerSocket) factory.createServerSocket(port, 100, ifAddress); serverSocket.setSoTimeout(timeout); serverSocket.setNeedClientAuth(clientAuth); if (params != null && params.cipherSuites != null) { serverSocket.setEnabledCipherSuites(params.cipherSuites); } - return new TServerSocket(new TServerSocket.ServerSocketTransportArgs(). - serverSocket(serverSocket).clientTimeout(timeout)); + return new TServerSocket( + new TServerSocket.ServerSocketTransportArgs() + .serverSocket(serverSocket) + .clientTimeout(timeout)); } catch (Exception e) { throw new TTransportException("Could not bind to port " + port, e); } } /** - * Get a default SSL wrapped TSocket connected to the specified host and port. All - * the client methods return a bound connection. So there is no need to call open() on the - * TTransport. + * Get a default SSL wrapped TSocket connected to the specified host and port. All the client + * methods return a bound connection. So there is no need to call open() on the TTransport. * * @param host * @param port @@ -142,7 +150,8 @@ public class TSSLTransportFactory { * @return A SSL wrapped TSocket * @throws TTransportException */ - public static TSocket getClientSocket(String host, int port, int timeout) throws TTransportException { + public static TSocket getClientSocket(String host, int port, int timeout) + throws TTransportException { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); return createClient(factory, host, port, timeout); } @@ -160,8 +169,8 @@ public class TSSLTransportFactory { } /** - * Get a custom configured SSL wrapped TSocket. The SSL settings are obtained from the - * passed in TSSLTransportParameters. + * Get a custom configured SSL wrapped TSocket. The SSL settings are obtained from the passed in + * TSSLTransportParameters. * * @param host * @param port @@ -170,16 +179,21 @@ public class TSSLTransportFactory { * @return A SSL wrapped TSocket * @throws TTransportException */ - public static TSocket getClientSocket(String host, int port, int timeout, TSSLTransportParameters params) throws TTransportException { + public static TSocket getClientSocket( + String host, int port, int timeout, TSSLTransportParameters params) + throws TTransportException { if (params == null || !(params.isKeyStoreSet || params.isTrustStoreSet)) { - throw new TTransportException(TTransportException.NOT_OPEN, "Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); + throw new TTransportException( + TTransportException.NOT_OPEN, + "Either one of the KeyStore or TrustStore must be set for SSLTransportParameters"); } SSLContext ctx = createSSLContext(params); return createClient(ctx.getSocketFactory(), host, port, timeout); } - private static SSLContext createSSLContext(TSSLTransportParameters params) throws TTransportException { + private static SSLContext createSSLContext(TSSLTransportParameters params) + throws TTransportException { SSLContext ctx; InputStream in = null; InputStream is = null; @@ -197,8 +211,7 @@ public class TSSLTransportFactory { } else { in = getStoreAsStream(params.trustStore); } - ts.load(in, - (params.trustPass != null ? params.trustPass.toCharArray() : null)); + ts.load(in, (params.trustPass != null ? params.trustPass.toCharArray() : null)); tmf.init(ts); } @@ -206,9 +219,9 @@ public class TSSLTransportFactory { kmf = KeyManagerFactory.getInstance(params.keyManagerType); KeyStore ks = KeyStore.getInstance(params.keyStoreType); if (params.keyStoreStream != null) { - is = params.keyStoreStream; + is = params.keyStoreStream; } else { - is = getStoreAsStream(params.keyStore); + is = getStoreAsStream(params.keyStore); } ks.load(is, params.keyPass.toCharArray()); kmf.init(ks, params.keyPass.toCharArray()); @@ -216,16 +229,15 @@ public class TSSLTransportFactory { if (params.isKeyStoreSet && params.isTrustStoreSet) { ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - } - else if (params.isKeyStoreSet) { + } else if (params.isKeyStoreSet) { ctx.init(kmf.getKeyManagers(), null, null); - } - else { + } else { ctx.init(null, tmf.getTrustManagers(), null); } } catch (Exception e) { - throw new TTransportException(TTransportException.NOT_OPEN, "Error creating the transport", e); + throw new TTransportException( + TTransportException.NOT_OPEN, "Error creating the transport", e); } finally { if (in != null) { try { @@ -249,7 +261,7 @@ public class TSSLTransportFactory { private static InputStream getStoreAsStream(String store) throws IOException { try { return new FileInputStream(store); - } catch(FileNotFoundException e) { + } catch (FileNotFoundException e) { } InputStream storeStream = null; @@ -258,7 +270,7 @@ public class TSSLTransportFactory { if (storeStream != null) { return storeStream; } - } catch(MalformedURLException e) { + } catch (MalformedURLException e) { } storeStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(store); @@ -270,7 +282,8 @@ public class TSSLTransportFactory { } } - private static TSocket createClient(SSLSocketFactory factory, String host, int port, int timeout) throws TTransportException { + private static TSocket createClient(SSLSocketFactory factory, String host, int port, int timeout) + throws TTransportException { try { SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(timeout); @@ -278,14 +291,12 @@ public class TSSLTransportFactory { } catch (TTransportException tte) { throw tte; } catch (Exception e) { - throw new TTransportException(TTransportException.NOT_OPEN, "Could not connect to " + host + " on port " + port, e); + throw new TTransportException( + TTransportException.NOT_OPEN, "Could not connect to " + host + " on port " + port, e); } } - - /** - * A Class to hold all the SSL parameters - */ + /** A Class to hold all the SSL parameters */ public static class TSSLTransportParameters { protected String protocol = "TLS"; protected String keyStore; @@ -316,8 +327,8 @@ public class TSSLTransportFactory { } /** - * Create parameters specifying the protocol, cipher suites and if client authentication - * is required + * Create parameters specifying the protocol, cipher suites and if client authentication is + * required * * @param protocol The specific protocol (TLS/SSL) can be specified with versions * @param cipherSuites @@ -327,7 +338,8 @@ public class TSSLTransportFactory { if (protocol != null) { this.protocol = protocol; } - this.cipherSuites = cipherSuites != null ? Arrays.copyOf(cipherSuites, cipherSuites.length) : null; + this.cipherSuites = + cipherSuites != null ? Arrays.copyOf(cipherSuites, cipherSuites.length) : null; this.clientAuth = clientAuth; } @@ -339,7 +351,8 @@ public class TSSLTransportFactory { * @param keyManagerType The default is X509 * @param keyStoreType The default is JKS */ - public void setKeyStore(String keyStore, String keyPass, String keyManagerType, String keyStoreType) { + public void setKeyStore( + String keyStore, String keyPass, String keyManagerType, String keyStoreType) { this.keyStore = keyStore; this.keyPass = keyPass; if (keyManagerType != null) { @@ -359,9 +372,10 @@ public class TSSLTransportFactory { * @param keyManagerType The default is X509 * @param keyStoreType The default is JKS */ - public void setKeyStore(InputStream keyStoreStream, String keyPass, String keyManagerType, String keyStoreType) { - this.keyStoreStream = keyStoreStream; - setKeyStore("", keyPass, keyManagerType, keyStoreType); + public void setKeyStore( + InputStream keyStoreStream, String keyPass, String keyManagerType, String keyStoreType) { + this.keyStoreStream = keyStoreStream; + setKeyStore("", keyPass, keyManagerType, keyStoreType); } /** @@ -392,7 +406,8 @@ public class TSSLTransportFactory { * @param trustManagerType The default is X509 * @param trustStoreType The default is JKS */ - public void setTrustStore(String trustStore, String trustPass, String trustManagerType, String trustStoreType) { + public void setTrustStore( + String trustStore, String trustPass, String trustManagerType, String trustStoreType) { this.trustStore = trustStore; this.trustPass = trustPass; if (trustManagerType != null) { @@ -412,7 +427,11 @@ public class TSSLTransportFactory { * @param trustManagerType The default is X509 * @param trustStoreType The default is JKS */ - public void setTrustStore(InputStream trustStoreStream, String trustPass, String trustManagerType, String trustStoreType) { + public void setTrustStore( + InputStream trustStoreStream, + String trustPass, + String trustManagerType, + String trustStoreType) { this.trustStoreStream = trustStoreStream; setTrustStore("", trustPass, trustManagerType, trustStoreType); } @@ -444,6 +463,6 @@ public class TSSLTransportFactory { */ public void requireClientAuth(boolean clientAuth) { this.clientAuth = clientAuth; - } - } + } + } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java index e5ca41831..19cc41ec0 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSaslClientTransport.java @@ -21,71 +21,69 @@ package org.apache.thrift.transport; import java.nio.charset.StandardCharsets; import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; - import org.apache.thrift.transport.sasl.NegotiationStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Wraps another Thrift <code>TTransport</code>, but performs SASL client - * negotiation on the call to <code>open()</code>. This class will wrap ensuing - * communication over it, if a SASL QOP is negotiated with the other party. + * Wraps another Thrift <code>TTransport</code>, but performs SASL client negotiation on the call to + * <code>open()</code>. This class will wrap ensuing communication over it, if a SASL QOP is + * negotiated with the other party. */ public class TSaslClientTransport extends TSaslTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TSaslClientTransport.class); - /** - * The name of the mechanism this client supports. - */ + /** The name of the mechanism this client supports. */ private final String mechanism; /** * Uses the given <code>SaslClient</code>. * - * @param saslClient - * The <code>SaslClient</code> to use for the subsequent SASL - * negotiation. - * @param transport - * Transport underlying this one. + * @param saslClient The <code>SaslClient</code> to use for the subsequent SASL negotiation. + * @param transport Transport underlying this one. */ - public TSaslClientTransport(SaslClient saslClient, TTransport transport) throws TTransportException { + public TSaslClientTransport(SaslClient saslClient, TTransport transport) + throws TTransportException { super(saslClient, transport); mechanism = saslClient.getMechanismName(); } /** - * Creates a <code>SaslClient</code> using the given SASL-specific parameters. - * See the Java documentation for <code>Sasl.createSaslClient</code> for the - * details of the parameters. + * Creates a <code>SaslClient</code> using the given SASL-specific parameters. See the Java + * documentation for <code>Sasl.createSaslClient</code> for the details of the parameters. * - * @param transport - * The underlying Thrift transport. + * @param transport The underlying Thrift transport. * @throws SaslException */ - public TSaslClientTransport(String mechanism, String authorizationId, String protocol, - String serverName, Map<String, String> props, CallbackHandler cbh, TTransport transport) - throws SaslException, TTransportException { - super(Sasl.createSaslClient(new String[] { mechanism }, authorizationId, protocol, serverName, - props, cbh), transport); + public TSaslClientTransport( + String mechanism, + String authorizationId, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh, + TTransport transport) + throws SaslException, TTransportException { + super( + Sasl.createSaslClient( + new String[] {mechanism}, authorizationId, protocol, serverName, props, cbh), + transport); this.mechanism = mechanism; } - @Override protected SaslRole getRole() { return SaslRole.CLIENT; } /** - * Performs the client side of the initial portion of the Thrift SASL - * protocol. Generates and sends the initial response to the server, including - * which mechanism this client wants to use. + * Performs the client side of the initial portion of the Thrift SASL protocol. Generates and + * sends the initial response to the server, including which mechanism this client wants to use. */ @Override protected void handleSaslStartMessage() throws TTransportException, SaslException { @@ -95,15 +93,17 @@ public class TSaslClientTransport extends TSaslTransport { if (saslClient.hasInitialResponse()) initialResponse = saslClient.evaluateChallenge(initialResponse); - LOGGER.debug("Sending mechanism name {} and initial response of length {}", mechanism, + LOGGER.debug( + "Sending mechanism name {} and initial response of length {}", + mechanism, initialResponse.length); byte[] mechanismBytes = mechanism.getBytes(StandardCharsets.UTF_8); - sendSaslMessage(NegotiationStatus.START, - mechanismBytes); + sendSaslMessage(NegotiationStatus.START, mechanismBytes); // Send initial response - sendSaslMessage(saslClient.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, - initialResponse); + sendSaslMessage( + saslClient.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, + initialResponse); underlyingTransport.flush(); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java index 9111712a4..42a838c0a 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSaslServerTransport.java @@ -25,71 +25,76 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; - import org.apache.thrift.transport.sasl.NegotiationStatus; import org.apache.thrift.transport.sasl.TSaslServerDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Wraps another Thrift <code>TTransport</code>, but performs SASL server - * negotiation on the call to <code>open()</code>. This class will wrap ensuing - * communication over it, if a SASL QOP is negotiated with the other party. + * Wraps another Thrift <code>TTransport</code>, but performs SASL server negotiation on the call to + * <code>open()</code>. This class will wrap ensuing communication over it, if a SASL QOP is + * negotiated with the other party. */ public class TSaslServerTransport extends TSaslTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TSaslServerTransport.class); /** - * Mapping from SASL mechanism name -> all the parameters required to - * instantiate a SASL server. + * Mapping from SASL mechanism name -> all the parameters required to instantiate a SASL server. */ - private Map<String, TSaslServerDefinition> serverDefinitionMap = new HashMap<String, TSaslServerDefinition>(); + private Map<String, TSaslServerDefinition> serverDefinitionMap = + new HashMap<String, TSaslServerDefinition>(); /** - * Uses the given underlying transport. Assumes that addServerDefinition is - * called later. + * Uses the given underlying transport. Assumes that addServerDefinition is called later. * - * @param transport - * Transport underlying this one. + * @param transport Transport underlying this one. */ public TSaslServerTransport(TTransport transport) throws TTransportException { super(transport); } /** - * Creates a <code>SaslServer</code> using the given SASL-specific parameters. - * See the Java documentation for <code>Sasl.createSaslServer</code> for the - * details of the parameters. + * Creates a <code>SaslServer</code> using the given SASL-specific parameters. See the Java + * documentation for <code>Sasl.createSaslServer</code> for the details of the parameters. * - * @param transport - * The underlying Thrift transport. + * @param transport The underlying Thrift transport. */ - public TSaslServerTransport(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh, TTransport transport) throws TTransportException { + public TSaslServerTransport( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh, + TTransport transport) + throws TTransportException { super(transport); addServerDefinition(mechanism, protocol, serverName, props, cbh); } - private TSaslServerTransport(Map<String, TSaslServerDefinition> serverDefinitionMap, TTransport transport) throws TTransportException { + private TSaslServerTransport( + Map<String, TSaslServerDefinition> serverDefinitionMap, TTransport transport) + throws TTransportException { super(transport); this.serverDefinitionMap.putAll(serverDefinitionMap); } /** - * Add a supported server definition to this transport. See the Java - * documentation for <code>Sasl.createSaslServer</code> for the details of the - * parameters. + * Add a supported server definition to this transport. See the Java documentation for <code> + * Sasl.createSaslServer</code> for the details of the parameters. */ - public void addServerDefinition(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { - serverDefinitionMap.put(mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, - props, cbh)); + public void addServerDefinition( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { + serverDefinitionMap.put( + mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, props, cbh)); } @Override @@ -98,10 +103,9 @@ public class TSaslServerTransport extends TSaslTransport { } /** - * Performs the server side of the initial portion of the Thrift SASL protocol. - * Receives the initial response from the client, creates a SASL server using - * the mechanism requested by the client (if this server supports it), and - * sends the first challenge back to the client. + * Performs the server side of the initial portion of the Thrift SASL protocol. Receives the + * initial response from the client, creates a SASL server using the mechanism requested by the + * client (if this server supports it), and sends the first challenge back to the client. */ @Override protected void handleSaslStartMessage() throws TTransportException, SaslException { @@ -109,7 +113,8 @@ public class TSaslServerTransport extends TSaslTransport { LOGGER.debug("Received start message with status {}", message.status); if (message.status != NegotiationStatus.START) { - throw sendAndThrowMessage(NegotiationStatus.ERROR, "Expecting START status, received " + message.status); + throw sendAndThrowMessage( + NegotiationStatus.ERROR, "Expecting START status, received " + message.status); } // Get the mechanism name. @@ -118,75 +123,80 @@ public class TSaslServerTransport extends TSaslTransport { LOGGER.debug("Received mechanism name '{}'", mechanismName); if (serverDefinition == null) { - throw sendAndThrowMessage(NegotiationStatus.BAD, "Unsupported mechanism type " + mechanismName); + throw sendAndThrowMessage( + NegotiationStatus.BAD, "Unsupported mechanism type " + mechanismName); } - SaslServer saslServer = Sasl.createSaslServer(serverDefinition.mechanism, - serverDefinition.protocol, serverDefinition.serverName, serverDefinition.props, - serverDefinition.cbh); + SaslServer saslServer = + Sasl.createSaslServer( + serverDefinition.mechanism, + serverDefinition.protocol, + serverDefinition.serverName, + serverDefinition.props, + serverDefinition.cbh); setSaslServer(saslServer); } /** - * <code>TTransportFactory</code> to create - * <code>TSaslServerTransports</code>. Ensures that a given - * underlying <code>TTransport</code> instance receives the same - * <code>TSaslServerTransport</code>. This is kind of an awful hack to work - * around the fact that Thrift is designed assuming that - * <code>TTransport</code> instances are stateless, and thus the existing - * <code>TServers</code> use different <code>TTransport</code> instances for - * input and output. + * <code>TTransportFactory</code> to create <code>TSaslServerTransports</code>. Ensures that a + * given underlying <code>TTransport</code> instance receives the same <code>TSaslServerTransport + * </code>. This is kind of an awful hack to work around the fact that Thrift is designed assuming + * that <code>TTransport</code> instances are stateless, and thus the existing <code>TServers + * </code> use different <code>TTransport</code> instances for input and output. */ public static class Factory extends TTransportFactory { /** - * This is the implementation of the awful hack described above. - * <code>WeakHashMap</code> is used to ensure that we don't leak memory. + * This is the implementation of the awful hack described above. <code>WeakHashMap</code> is + * used to ensure that we don't leak memory. */ private static Map<TTransport, WeakReference<TSaslServerTransport>> transportMap = - Collections.synchronizedMap(new WeakHashMap<TTransport, WeakReference<TSaslServerTransport>>()); + Collections.synchronizedMap( + new WeakHashMap<TTransport, WeakReference<TSaslServerTransport>>()); /** - * Mapping from SASL mechanism name -> all the parameters required to - * instantiate a SASL server. + * Mapping from SASL mechanism name -> all the parameters required to instantiate a SASL server. */ - private Map<String, TSaslServerDefinition> serverDefinitionMap = new HashMap<String, TSaslServerDefinition>(); + private Map<String, TSaslServerDefinition> serverDefinitionMap = + new HashMap<String, TSaslServerDefinition>(); - /** - * Create a new Factory. Assumes that <code>addServerDefinition</code> will - * be called later. - */ + /** Create a new Factory. Assumes that <code>addServerDefinition</code> will be called later. */ public Factory() { super(); } /** - * Create a new <code>Factory</code>, initially with the single server - * definition given. You may still call <code>addServerDefinition</code> - * later. See the Java documentation for <code>Sasl.createSaslServer</code> - * for the details of the parameters. + * Create a new <code>Factory</code>, initially with the single server definition given. You may + * still call <code>addServerDefinition</code> later. See the Java documentation for <code> + * Sasl.createSaslServer</code> for the details of the parameters. */ - public Factory(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { + public Factory( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { super(); addServerDefinition(mechanism, protocol, serverName, props, cbh); } /** - * Add a supported server definition to the transports created by this - * factory. See the Java documentation for - * <code>Sasl.createSaslServer</code> for the details of the parameters. + * Add a supported server definition to the transports created by this factory. See the Java + * documentation for <code>Sasl.createSaslServer</code> for the details of the parameters. */ - public void addServerDefinition(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { - serverDefinitionMap.put(mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, - props, cbh)); + public void addServerDefinition( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { + serverDefinitionMap.put( + mechanism, new TSaslServerDefinition(mechanism, protocol, serverName, props, cbh)); } /** - * Get a new <code>TSaslServerTransport</code> instance, or reuse the - * existing one if a <code>TSaslServerTransport</code> has already been - * created before using the given <code>TTransport</code> as an underlying - * transport. This ensures that a given underlying transport instance + * Get a new <code>TSaslServerTransport</code> instance, or reuse the existing one if a <code> + * TSaslServerTransport</code> has already been created before using the given <code>TTransport + * </code> as an underlying transport. This ensures that a given underlying transport instance * receives the same <code>TSaslServerTransport</code>. */ @Override @@ -194,7 +204,9 @@ public class TSaslServerTransport extends TSaslTransport { WeakReference<TSaslServerTransport> ret = transportMap.get(base); if (ret == null || ret.get() == null) { LOGGER.debug("transport map does not contain key", base); - ret = new WeakReference<TSaslServerTransport>(new TSaslServerTransport(serverDefinitionMap, base)); + ret = + new WeakReference<TSaslServerTransport>( + new TSaslServerTransport(serverDefinitionMap, base)); try { ret.get().open(); } catch (TTransportException e) { @@ -202,7 +214,7 @@ public class TSaslServerTransport extends TSaslTransport { throw new RuntimeException(e); } transportMap.put(base, ret); // No need for putIfAbsent(). - // Concurrent calls to getTransport() will pass in different TTransports. + // Concurrent calls to getTransport() will pass in different TTransports. } else { LOGGER.debug("transport map does contain key {}", base); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java index b22469d2b..0a280d6b3 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java @@ -21,12 +21,10 @@ package org.apache.thrift.transport; import java.nio.charset.StandardCharsets; import java.util.Objects; - import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; - import org.apache.thrift.EncodingUtils; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; @@ -36,8 +34,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A superclass for SASL client/server thrift transports. A subclass need only - * implement the <code>open</code> method. + * A superclass for SASL client/server thrift transports. A subclass need only implement the <code> + * open</code> method. */ abstract class TSaslTransport extends TEndpointTransport { @@ -50,44 +48,39 @@ abstract class TSaslTransport extends TEndpointTransport { protected static final int PAYLOAD_LENGTH_BYTES = 4; protected static enum SaslRole { - SERVER, CLIENT; + SERVER, + CLIENT; } - /** - * Transport underlying this one. - */ + /** Transport underlying this one. */ protected TTransport underlyingTransport; - /** - * Either a SASL client or a SASL server. - */ + /** Either a SASL client or a SASL server. */ private SaslParticipant sasl; /** - * Whether or not we should wrap/unwrap reads/writes. Determined by whether or - * not a QOP is negotiated during the SASL handshake. + * Whether or not we should wrap/unwrap reads/writes. Determined by whether or not a QOP is + * negotiated during the SASL handshake. */ private boolean shouldWrap = false; - /** - * Buffer for input. - */ + /** Buffer for input. */ private TMemoryInputTransport readBuffer; - /** - * Buffer for output. - */ + /** Buffer for output. */ private final TByteArrayOutputStream writeBuffer = new TByteArrayOutputStream(1024); /** - * Create a TSaslTransport. It's assumed that setSaslServer will be called - * later to initialize the SASL endpoint underlying this transport. + * Create a TSaslTransport. It's assumed that setSaslServer will be called later to initialize the + * SASL endpoint underlying this transport. * - * @param underlyingTransport - * The thrift transport which this transport is wrapping. + * @param underlyingTransport The thrift transport which this transport is wrapping. */ protected TSaslTransport(TTransport underlyingTransport) throws TTransportException { - super(Objects.isNull(underlyingTransport.getConfiguration()) ? new TConfiguration() : underlyingTransport.getConfiguration()); + super( + Objects.isNull(underlyingTransport.getConfiguration()) + ? new TConfiguration() + : underlyingTransport.getConfiguration()); this.underlyingTransport = underlyingTransport; this.readBuffer = new TMemoryInputTransport(underlyingTransport.getConfiguration()); } @@ -95,14 +88,16 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Create a TSaslTransport which acts as a client. * - * @param saslClient - * The <code>SaslClient</code> which this transport will use for SASL - * negotiation. - * @param underlyingTransport - * The thrift transport which this transport is wrapping. + * @param saslClient The <code>SaslClient</code> which this transport will use for SASL + * negotiation. + * @param underlyingTransport The thrift transport which this transport is wrapping. */ - protected TSaslTransport(SaslClient saslClient, TTransport underlyingTransport) throws TTransportException { - super(Objects.isNull(underlyingTransport.getConfiguration()) ? new TConfiguration() : underlyingTransport.getConfiguration()); + protected TSaslTransport(SaslClient saslClient, TTransport underlyingTransport) + throws TTransportException { + super( + Objects.isNull(underlyingTransport.getConfiguration()) + ? new TConfiguration() + : underlyingTransport.getConfiguration()); sasl = new SaslParticipant(saslClient); this.underlyingTransport = underlyingTransport; this.readBuffer = new TMemoryInputTransport(underlyingTransport.getConfiguration()); @@ -118,21 +113,22 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Send a complete Thrift SASL message. * - * @param status - * The status to send. - * @param payload - * The data to send as the payload of this message. + * @param status The status to send. + * @param payload The data to send as the payload of this message. * @throws TTransportException */ - protected void sendSaslMessage(NegotiationStatus status, byte[] payload) throws TTransportException { - if (payload == null) - payload = new byte[0]; + protected void sendSaslMessage(NegotiationStatus status, byte[] payload) + throws TTransportException { + if (payload == null) payload = new byte[0]; messageHeader[0] = status.getValue(); EncodingUtils.encodeBigEndian(payload.length, messageHeader, STATUS_BYTES); - LOGGER.debug("{}: Writing message with status {} and payload length {}", - getRole(), status, payload.length); + LOGGER.debug( + "{}: Writing message with status {} and payload length {}", + getRole(), + status, + payload.length); underlyingTransport.write(messageHeader); underlyingTransport.write(payload); @@ -143,9 +139,8 @@ abstract class TSaslTransport extends TEndpointTransport { * Read a complete Thrift SASL message. * * @return The SASL status and payload from this message. - * @throws TTransportException - * Thrown if there is a failure reading from the underlying - * transport, or if a status code of BAD or ERROR is encountered. + * @throws TTransportException Thrown if there is a failure reading from the underlying transport, + * or if a status code of BAD or ERROR is encountered. */ protected SaslResponse receiveSaslMessage() throws TTransportException { underlyingTransport.readAll(messageHeader, 0, messageHeader.length); @@ -160,7 +155,7 @@ abstract class TSaslTransport extends TEndpointTransport { int payloadBytes = EncodingUtils.decodeBigEndian(messageHeader, STATUS_BYTES); if (payloadBytes < 0 || payloadBytes > getConfiguration().getMaxMessageSize() /* 100 MB */) { throw sendAndThrowMessage( - NegotiationStatus.ERROR, "Invalid payload header length: " + payloadBytes); + NegotiationStatus.ERROR, "Invalid payload header length: " + payloadBytes); } byte[] payload = new byte[payloadBytes]; @@ -170,26 +165,26 @@ abstract class TSaslTransport extends TEndpointTransport { String remoteMessage = new String(payload, StandardCharsets.UTF_8); throw new TTransportException("Peer indicated failure: " + remoteMessage); } - LOGGER.debug("{}: Received message with status {} and payload length {}", - getRole(), status, payload.length); + LOGGER.debug( + "{}: Received message with status {} and payload length {}", + getRole(), + status, + payload.length); return new SaslResponse(status, payload); } /** - * Send a Thrift SASL message with the given status (usually BAD or ERROR) and - * string message, and then throw a TTransportException with the given - * message. + * Send a Thrift SASL message with the given status (usually BAD or ERROR) and string message, and + * then throw a TTransportException with the given message. * - * @param status - * The Thrift SASL status code to send. Usually BAD or ERROR. - * @param message - * The optional message to send to the other side. - * @throws TTransportException - * Always thrown with the message provided. - * @return always throws TTransportException but declares return type to allow - * throw sendAndThrowMessage(...) to inform compiler control flow + * @param status The Thrift SASL status code to send. Usually BAD or ERROR. + * @param message The optional message to send to the other side. + * @throws TTransportException Always thrown with the message provided. + * @return always throws TTransportException but declares return type to allow throw + * sendAndThrowMessage(...) to inform compiler control flow */ - protected TTransportException sendAndThrowMessage(NegotiationStatus status, String message) throws TTransportException { + protected TTransportException sendAndThrowMessage(NegotiationStatus status, String message) + throws TTransportException { try { sendSaslMessage(status, message.getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { @@ -200,21 +195,20 @@ abstract class TSaslTransport extends TEndpointTransport { } /** - * Implemented by subclasses to start the Thrift SASL handshake process. When - * this method completes, the <code>SaslParticipant</code> in this class is - * assumed to be initialized. + * Implemented by subclasses to start the Thrift SASL handshake process. When this method + * completes, the <code>SaslParticipant</code> in this class is assumed to be initialized. * * @throws TTransportException * @throws SaslException */ - abstract protected void handleSaslStartMessage() throws TTransportException, SaslException; + protected abstract void handleSaslStartMessage() throws TTransportException, SaslException; protected abstract SaslRole getRole(); /** - * Opens the underlying transport if it's not already open and then performs - * SASL negotiation. If a QOP is negotiated during this SASL handshake, it used - * for all communication on this transport after this call is complete. + * Opens the underlying transport if it's not already open and then performs SASL negotiation. If + * a QOP is negotiated during this SASL handshake, it used for all communication on this transport + * after this call is complete. */ @Override public void open() throws TTransportException { @@ -229,8 +223,7 @@ abstract class TSaslTransport extends TEndpointTransport { if (sasl != null && sasl.isComplete()) throw new TTransportException("SASL transport already open"); - if (!underlyingTransport.isOpen()) - underlyingTransport.open(); + if (!underlyingTransport.isOpen()) underlyingTransport.open(); try { // Negotiate a SASL mechanism. The client also sends its @@ -242,8 +235,8 @@ abstract class TSaslTransport extends TEndpointTransport { SaslResponse message = null; while (!sasl.isComplete()) { message = receiveSaslMessage(); - if (message.status != NegotiationStatus.COMPLETE && - message.status != NegotiationStatus.OK) { + if (message.status != NegotiationStatus.COMPLETE + && message.status != NegotiationStatus.OK) { throw new TTransportException("Expected COMPLETE or OK, got " + message.status); } @@ -251,14 +244,13 @@ abstract class TSaslTransport extends TEndpointTransport { // If we are the client, and the server indicates COMPLETE, we don't need to // send back any further response. - if (message.status == NegotiationStatus.COMPLETE && - getRole() == SaslRole.CLIENT) { + if (message.status == NegotiationStatus.COMPLETE && getRole() == SaslRole.CLIENT) { LOGGER.debug("{}: All done!", getRole()); continue; } - sendSaslMessage(sasl.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, - challenge); + sendSaslMessage( + sasl.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, challenge); } LOGGER.debug("{}: Main negotiation loop complete", getRole()); @@ -266,13 +258,12 @@ abstract class TSaslTransport extends TEndpointTransport { // complete yet, we need to wait for its response. This will occur // with ANONYMOUS auth, for example, where we send an initial response // and are immediately complete. - if (getRole() == SaslRole.CLIENT && - (message == null || message.status == NegotiationStatus.OK)) { + if (getRole() == SaslRole.CLIENT + && (message == null || message.status == NegotiationStatus.OK)) { LOGGER.debug("{}: SASL Client receiving last message", getRole()); message = receiveSaslMessage(); if (message.status != NegotiationStatus.COMPLETE) { - throw new TTransportException( - "Expected SASL COMPLETE, but got " + message.status); + throw new TTransportException("Expected SASL COMPLETE, but got " + message.status); } } } catch (SaslException e) { @@ -293,15 +284,14 @@ abstract class TSaslTransport extends TEndpointTransport { } String qop = (String) sasl.getNegotiatedProperty(Sasl.QOP); - if (qop != null && !qop.equalsIgnoreCase("auth")) - shouldWrap = true; + if (qop != null && !qop.equalsIgnoreCase("auth")) shouldWrap = true; } /** * Get the underlying <code>SaslClient</code>. * - * @return The <code>SaslClient</code>, or <code>null</code> if this transport - * is backed by a <code>SaslServer</code>. + * @return The <code>SaslClient</code>, or <code>null</code> if this transport is backed by a + * <code>SaslServer</code>. */ public SaslClient getSaslClient() { return sasl.saslClient; @@ -309,29 +299,28 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Get the underlying transport that Sasl is using. + * * @return The <code>TTransport</code> transport */ - public TTransport getUnderlyingTransport() { - return underlyingTransport; - } + public TTransport getUnderlyingTransport() { + return underlyingTransport; + } /** * Get the underlying <code>SaslServer</code>. * - * @return The <code>SaslServer</code>, or <code>null</code> if this transport - * is backed by a <code>SaslClient</code>. + * @return The <code>SaslServer</code>, or <code>null</code> if this transport is backed by a + * <code>SaslClient</code>. */ public SaslServer getSaslServer() { return sasl.saslServer; } /** - * Read a 4-byte word from the underlying transport and interpret it as an - * integer. + * Read a 4-byte word from the underlying transport and interpret it as an integer. * * @return The length prefix of the next SASL message to read. - * @throws TTransportException - * Thrown if reading from the underlying transport fails. + * @throws TTransportException Thrown if reading from the underlying transport fails. */ protected int readLength() throws TTransportException { byte[] lenBuf = new byte[4]; @@ -342,10 +331,8 @@ abstract class TSaslTransport extends TEndpointTransport { /** * Write the given integer as 4 bytes to the underlying transport. * - * @param length - * The length prefix of the next SASL message to write. - * @throws TTransportException - * Thrown if writing to the underlying transport fails. + * @param length The length prefix of the next SASL message to write. + * @throws TTransportException Thrown if writing to the underlying transport fails. */ protected void writeLength(int length) throws TTransportException { byte[] lenBuf = new byte[4]; @@ -356,8 +343,8 @@ abstract class TSaslTransport extends TEndpointTransport { // Below is the SASL implementation of the TTransport interface. /** - * Closes the underlying transport and disposes of the SASL implementation - * underlying this transport. + * Closes the underlying transport and disposes of the SASL implementation underlying this + * transport. */ @Override public void close() { @@ -369,23 +356,19 @@ abstract class TSaslTransport extends TEndpointTransport { } } - /** - * True if the underlying transport is open and the SASL handshake is - * complete. - */ + /** True if the underlying transport is open and the SASL handshake is complete. */ @Override public boolean isOpen() { return underlyingTransport.isOpen() && sasl != null && sasl.isComplete(); } /** - * Read from the underlying transport. Unwraps the contents if a QOP was - * negotiated during the SASL handshake. + * Read from the underlying transport. Unwraps the contents if a QOP was negotiated during the + * SASL handshake. */ @Override public int read(byte[] buf, int off, int len) throws TTransportException { - if (!isOpen()) - throw new TTransportException("SASL authentication not complete"); + if (!isOpen()) throw new TTransportException("SASL authentication not complete"); int got = readBuffer.read(buf, off, len); if (got > 0) { @@ -409,13 +392,10 @@ abstract class TSaslTransport extends TEndpointTransport { } /** - * Read a single frame of data from the underlying transport, unwrapping if - * necessary. + * Read a single frame of data from the underlying transport, unwrapping if necessary. * - * @throws TTransportException - * Thrown if there's an error reading from the underlying transport. - * @throws SaslException - * Thrown if there's an error unwrapping the data. + * @throws TTransportException Thrown if there's an error reading from the underlying transport. + * @throws SaslException Thrown if there's an error unwrapping the data. */ private void readFrame() throws TTransportException, SaslException { int dataLength = readLength(); @@ -433,20 +413,17 @@ abstract class TSaslTransport extends TEndpointTransport { readBuffer.reset(buff); } - /** - * Write to the underlying transport. - */ + /** Write to the underlying transport. */ @Override public void write(byte[] buf, int off, int len) throws TTransportException { - if (!isOpen()) - throw new TTransportException("SASL authentication not complete"); + if (!isOpen()) throw new TTransportException("SASL authentication not complete"); writeBuffer.write(buf, off, len); } /** - * Flushes to the underlying transport. Wraps the contents if a QOP was - * negotiated during the SASL handshake. + * Flushes to the underlying transport. Wraps the contents if a QOP was negotiated during the SASL + * handshake. */ @Override public void flush() throws TTransportException { @@ -469,9 +446,7 @@ abstract class TSaslTransport extends TEndpointTransport { underlyingTransport.flush(); } - /** - * Used exclusively by readSaslMessage to return both a status and data. - */ + /** Used exclusively by readSaslMessage to return both a status and data. */ protected static class SaslResponse { public NegotiationStatus status; public byte[] payload; @@ -483,9 +458,8 @@ abstract class TSaslTransport extends TEndpointTransport { } /** - * Used to abstract over the <code>SaslServer</code> and - * <code>SaslClient</code> classes, which share a lot of their interface, but - * unfortunately don't share a common superclass. + * Used to abstract over the <code>SaslServer</code> and <code>SaslClient</code> classes, which + * share a lot of their interface, but unfortunately don't share a common superclass. */ private static class SaslParticipant { // One of these will always be null. @@ -509,38 +483,28 @@ abstract class TSaslTransport extends TEndpointTransport { } public boolean isComplete() { - if (saslClient != null) - return saslClient.isComplete(); - else - return saslServer.isComplete(); + if (saslClient != null) return saslClient.isComplete(); + else return saslServer.isComplete(); } public void dispose() throws SaslException { - if (saslClient != null) - saslClient.dispose(); - else - saslServer.dispose(); + if (saslClient != null) saslClient.dispose(); + else saslServer.dispose(); } public byte[] unwrap(byte[] buf, int off, int len) throws SaslException { - if (saslClient != null) - return saslClient.unwrap(buf, off, len); - else - return saslServer.unwrap(buf, off, len); + if (saslClient != null) return saslClient.unwrap(buf, off, len); + else return saslServer.unwrap(buf, off, len); } public byte[] wrap(byte[] buf, int off, int len) throws SaslException { - if (saslClient != null) - return saslClient.wrap(buf, off, len); - else - return saslServer.wrap(buf, off, len); + if (saslClient != null) return saslClient.wrap(buf, off, len); + else return saslServer.wrap(buf, off, len); } public Object getNegotiatedProperty(String propName) { - if (saslClient != null) - return saslClient.getNegotiatedProperty(propName); - else - return saslServer.getNegotiatedProperty(propName); + if (saslClient != null) return saslClient.getNegotiatedProperty(propName); + else return saslServer.getNegotiatedProperty(propName); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java b/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java index e02d36f6c..6200dadce 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSeekableFile.java @@ -19,15 +19,19 @@ package org.apache.thrift.transport; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; public interface TSeekableFile { public InputStream getInputStream() throws IOException; + public OutputStream getOutputStream() throws IOException; + public void close() throws IOException; + public long length() throws IOException; + public void seek(long pos) throws IOException; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java index eb302fd26..e1056623e 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TServerSocket.java @@ -19,34 +19,27 @@ package org.apache.thrift.transport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** - * Wrapper around ServerSocket for Thrift. - * - */ +/** Wrapper around ServerSocket for Thrift. */ public class TServerSocket extends TServerTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TServerSocket.class.getName()); - /** - * Underlying ServerSocket object - */ + /** Underlying ServerSocket object */ private ServerSocket serverSocket_ = null; - /** - * Timeout for client sockets from accept - */ + /** Timeout for client sockets from accept */ private int clientTimeout_ = 0; - public static class ServerSocketTransportArgs extends AbstractServerTransportArgs<ServerSocketTransportArgs> { + public static class ServerSocketTransportArgs + extends AbstractServerTransportArgs<ServerSocketTransportArgs> { ServerSocket serverSocket; public ServerSocketTransportArgs serverSocket(ServerSocket serverSocket) { @@ -55,30 +48,22 @@ public class TServerSocket extends TServerTransport { } } - /** - * Creates a server socket from underlying socket object - */ + /** Creates a server socket from underlying socket object */ public TServerSocket(ServerSocket serverSocket) throws TTransportException { this(serverSocket, 0); } - /** - * Creates a server socket from underlying socket object - */ + /** Creates a server socket from underlying socket object */ public TServerSocket(ServerSocket serverSocket, int clientTimeout) throws TTransportException { this(new ServerSocketTransportArgs().serverSocket(serverSocket).clientTimeout(clientTimeout)); } - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TServerSocket(int port) throws TTransportException { this(port, 0); } - /** - * Creates just a port listening server socket - */ + /** Creates just a port listening server socket */ public TServerSocket(int port, int clientTimeout) throws TTransportException { this(new InetSocketAddress(port), clientTimeout); } @@ -106,7 +91,8 @@ public class TServerSocket extends TServerTransport { serverSocket_.bind(args.bindAddr, args.backlog); } catch (IOException ioe) { close(); - throw new TTransportException("Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); + throw new TTransportException( + "Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java index 3a7b49a31..47fa2513c 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TServerTransport.java @@ -21,16 +21,13 @@ package org.apache.thrift.transport; import java.io.Closeable; import java.net.InetSocketAddress; - import org.apache.thrift.TConfiguration; -/** - * Server transport. Object which provides client transports. - * - */ +/** Server transport. Object which provides client transports. */ public abstract class TServerTransport implements Closeable { - public static abstract class AbstractServerTransportArgs<T extends AbstractServerTransportArgs<T>> { + public abstract static class AbstractServerTransportArgs< + T extends AbstractServerTransportArgs<T>> { int backlog = 0; // A value of 0 means the default value will be used (currently set at 50) int clientTimeout = 0; InetSocketAddress bindAddr; @@ -65,9 +62,9 @@ public abstract class TServerTransport implements Closeable { public abstract void listen() throws TTransportException; /** - * Accept incoming connection on the server socket. When there is no incoming connection available: - * either it should block infinitely in a blocking implementation, either it should return null in - * a nonblocking implementation. + * Accept incoming connection on the server socket. When there is no incoming connection + * available: either it should block infinitely in a blocking implementation, either it should + * return null in a nonblocking implementation. * * @return new connection * @throws TTransportException if IO error. @@ -77,12 +74,10 @@ public abstract class TServerTransport implements Closeable { public abstract void close(); /** - * Optional method implementation. This signals to the server transport - * that it should break out of any accept() or listen() that it is currently - * blocked on. This method, if implemented, MUST be thread safe, as it may - * be called from a different thread context than the other TServerTransport - * methods. + * Optional method implementation. This signals to the server transport that it should break out + * of any accept() or listen() that it is currently blocked on. This method, if implemented, MUST + * be thread safe, as it may be called from a different thread context than the other + * TServerTransport methods. */ public void interrupt() {} - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java index c1bbd4853..9dfdb82d9 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSimpleFileTransport.java @@ -18,15 +18,11 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.IOException; import java.io.RandomAccessFile; +import org.apache.thrift.TConfiguration; - -/** - * Basic file support for the TTransport interface - */ +/** Basic file support for the TTransport interface */ public final class TSimpleFileTransport extends TEndpointTransport { private RandomAccessFile file = null; @@ -34,7 +30,6 @@ public final class TSimpleFileTransport extends TEndpointTransport { private boolean writable; private String path_; - /** * Create a transport backed by a simple file * @@ -44,9 +39,8 @@ public final class TSimpleFileTransport extends TEndpointTransport { * @param openFile true to open the file on construction * @throws TTransportException if file open fails */ - public TSimpleFileTransport(String path, boolean read, - boolean write, boolean openFile) - throws TTransportException { + public TSimpleFileTransport(String path, boolean read, boolean write, boolean openFile) + throws TTransportException { this(new TConfiguration(), path, read, write, openFile); } @@ -60,9 +54,9 @@ public final class TSimpleFileTransport extends TEndpointTransport { * @param openFile true to open the file on construction * @throws TTransportException if file open fails */ - public TSimpleFileTransport(TConfiguration config, String path, boolean read, - boolean write, boolean openFile) - throws TTransportException { + public TSimpleFileTransport( + TConfiguration config, String path, boolean read, boolean write, boolean openFile) + throws TTransportException { super(config); if (path.length() <= 0) { throw new TTransportException("No path specified"); @@ -79,22 +73,19 @@ public final class TSimpleFileTransport extends TEndpointTransport { } /** - * Create a transport backed by a simple file - * Implicitly opens file to conform to C++ behavior. + * Create a transport backed by a simple file Implicitly opens file to conform to C++ behavior. * * @param path the path to the file to open/create * @param read true to support read operations * @param write true to support write operations * @throws TTransportException if file open fails */ - public TSimpleFileTransport(String path, boolean read, boolean write) - throws TTransportException { + public TSimpleFileTransport(String path, boolean read, boolean write) throws TTransportException { this(path, read, write, true); } /** - * Create a transport backed by a simple read only disk file (implicitly opens - * file) + * Create a transport backed by a simple read only disk file (implicitly opens file) * * @param path the path to the file to open/create * @throws TTransportException if file open fails @@ -120,9 +111,9 @@ public final class TSimpleFileTransport extends TEndpointTransport { */ @Override public void open() throws TTransportException { - if (file == null){ + if (file == null) { try { - String access = "r"; //RandomAccessFile objects must be readable + String access = "r"; // RandomAccessFile objects must be readable if (writable) { access += "w"; } @@ -134,16 +125,14 @@ public final class TSimpleFileTransport extends TEndpointTransport { } } - /** - * Close file, subsequent read/write activity will throw exceptions - */ + /** Close file, subsequent read/write activity will throw exceptions */ @Override public void close() { if (file != null) { try { file.close(); } catch (Exception e) { - //Nothing to do + // Nothing to do } file = null; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java b/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java index aef2a3ff8..558c4fa7e 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TSocket.java @@ -19,48 +19,34 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; +import org.apache.thrift.TConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** - * Socket implementation of the TTransport interface. To be commented soon! - * - */ +/** Socket implementation of the TTransport interface. To be commented soon! */ public class TSocket extends TIOStreamTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TSocket.class.getName()); - /** - * Wrapped Socket object - */ + /** Wrapped Socket object */ private Socket socket_; - /** - * Remote host - */ + /** Remote host */ private String host_; - /** - * Remote port - */ + /** Remote port */ private int port_; - /** - * Socket timeout - read timeout on the socket - */ + /** Socket timeout - read timeout on the socket */ private int socketTimeout_; - /** - * Connection timeout - */ + /** Connection timeout */ private int connectTimeout_; /** @@ -92,10 +78,9 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * - * @param config check config + * @param config check config * @param host Remote host * @param port Remote port */ @@ -104,8 +89,7 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * * @param host Remote host * @param port Remote port @@ -115,11 +99,10 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * - * @param host Remote host - * @param port Remote port + * @param host Remote host + * @param port Remote port * @param timeout Socket timeout and connection timeout */ public TSocket(String host, int port, int timeout) throws TTransportException { @@ -127,30 +110,31 @@ public class TSocket extends TIOStreamTransport { } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port. + * Creates a new unconnected socket that will connect to the given host on the given port. * - * @param config check config - * @param host Remote host - * @param port Remote port + * @param config check config + * @param host Remote host + * @param port Remote port * @param timeout Socket timeout and connection timeout */ - public TSocket(TConfiguration config, String host, int port, int timeout) throws TTransportException { + public TSocket(TConfiguration config, String host, int port, int timeout) + throws TTransportException { this(config, host, port, timeout, timeout); } /** - * Creates a new unconnected socket that will connect to the given host - * on the given port, with a specific connection timeout and a - * specific socket timeout. + * Creates a new unconnected socket that will connect to the given host on the given port, with a + * specific connection timeout and a specific socket timeout. * - * @param config check config - * @param host Remote host - * @param port Remote port - * @param socketTimeout Socket timeout - * @param connectTimeout Connection timeout + * @param config check config + * @param host Remote host + * @param port Remote port + * @param socketTimeout Socket timeout + * @param connectTimeout Connection timeout */ - public TSocket(TConfiguration config, String host, int port, int socketTimeout, int connectTimeout) throws TTransportException { + public TSocket( + TConfiguration config, String host, int port, int socketTimeout, int connectTimeout) + throws TTransportException { super(config); host_ = host; port_ = port; @@ -159,9 +143,7 @@ public class TSocket extends TIOStreamTransport { initSocket(); } - /** - * Initializes the socket object - */ + /** Initializes the socket object */ private void initSocket() { socket_ = new Socket(); try { @@ -207,9 +189,7 @@ public class TSocket extends TIOStreamTransport { } } - /** - * Returns a reference to the underlying socket. - */ + /** Returns a reference to the underlying socket. */ public Socket getSocket() { if (socket_ == null) { initSocket(); @@ -217,9 +197,7 @@ public class TSocket extends TIOStreamTransport { return socket_; } - /** - * Checks whether the socket is connected. - */ + /** Checks whether the socket is connected. */ public boolean isOpen() { if (socket_ == null) { return false; @@ -227,9 +205,7 @@ public class TSocket extends TIOStreamTransport { return socket_.isConnected(); } - /** - * Connects the socket, creating a new socket object if necessary. - */ + /** Connects the socket, creating a new socket object if necessary. */ public void open() throws TTransportException { if (isOpen()) { throw new TTransportException(TTransportException.ALREADY_OPEN, "Socket already connected."); @@ -256,9 +232,7 @@ public class TSocket extends TIOStreamTransport { } } - /** - * Closes the socket. - */ + /** Closes the socket. */ public void close() { // Close the underlying streams super.close(); @@ -273,5 +247,4 @@ public class TSocket extends TIOStreamTransport { socket_ = null; } } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java b/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java index 7a33af8ee..65c29a502 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TStandardFile.java @@ -19,12 +19,12 @@ package org.apache.thrift.transport; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; import java.io.RandomAccessFile; -import java.io.FileInputStream; -import java.io.FileOutputStream; public class TStandardFile implements TSeekableFile { @@ -45,7 +45,7 @@ public class TStandardFile implements TSeekableFile { } public void close() throws IOException { - if(inputFile_ != null) { + if (inputFile_ != null) { inputFile_.close(); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java index afe9cfb88..dc771fc58 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TTransport.java @@ -19,15 +19,13 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.Closeable; import java.nio.ByteBuffer; +import org.apache.thrift.TConfiguration; /** - * Generic class that encapsulates the I/O layer. This is basically a thin - * wrapper around the combined functionality of Java input/output streams. - * + * Generic class that encapsulates the I/O layer. This is basically a thin wrapper around the + * combined functionality of Java input/output streams. */ public abstract class TTransport implements Closeable { @@ -52,25 +50,20 @@ public abstract class TTransport implements Closeable { * * @throws TTransportException if the transport could not be opened */ - public abstract void open() - throws TTransportException; + public abstract void open() throws TTransportException; - /** - * Closes the transport. - */ + /** Closes the transport. */ public abstract void close(); /** - * Reads a sequence of bytes from this channel into the given buffer. An - * attempt is made to read up to the number of bytes remaining in the buffer, - * that is, dst.remaining(), at the moment this method is invoked. Upon return - * the buffer's position will move forward the number of bytes read; its limit - * will not have changed. Subclasses are encouraged to provide a more - * efficient implementation of this method. + * Reads a sequence of bytes from this channel into the given buffer. An attempt is made to read + * up to the number of bytes remaining in the buffer, that is, dst.remaining(), at the moment this + * method is invoked. Upon return the buffer's position will move forward the number of bytes + * read; its limit will not have changed. Subclasses are encouraged to provide a more efficient + * implementation of this method. * * @param dst The buffer into which bytes are to be transferred - * @return The number of bytes read, possibly zero, or -1 if the channel has - * reached end-of-stream + * @return The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream * @throws TTransportException if there was an error reading data */ public int read(ByteBuffer dst) throws TTransportException { @@ -89,8 +82,7 @@ public abstract class TTransport implements Closeable { * @return The number of bytes actually read * @throws TTransportException if there was an error reading data */ - public abstract int read(byte[] buf, int off, int len) - throws TTransportException; + public abstract int read(byte[] buf, int off, int len) throws TTransportException; /** * Guarantees that all of len bytes are actually read off the transport. @@ -101,12 +93,11 @@ public abstract class TTransport implements Closeable { * @return The number of bytes actually read, which must be equal to len * @throws TTransportException if there was an error reading data */ - public int readAll(byte[] buf, int off, int len) - throws TTransportException { + public int readAll(byte[] buf, int off, int len) throws TTransportException { int got = 0; int ret = 0; while (got < len) { - ret = read(buf, off+got, len-got); + ret = read(buf, off + got, len - got); if (ret <= 0) { throw new TTransportException( "Cannot read. Remote side has closed. Tried to read " @@ -138,15 +129,13 @@ public abstract class TTransport implements Closeable { * @param len The number of bytes to write * @throws TTransportException if there was an error writing data */ - public abstract void write(byte[] buf, int off, int len) - throws TTransportException; + public abstract void write(byte[] buf, int off, int len) throws TTransportException; /** - * Writes a sequence of bytes to the buffer. An attempt is made to write all - * remaining bytes in the buffer, that is, src.remaining(), at the moment this - * method is invoked. Upon return the buffer's position will updated; its limit - * will not have changed. Subclasses are encouraged to provide a more efficient - * implementation of this method. + * Writes a sequence of bytes to the buffer. An attempt is made to write all remaining bytes in + * the buffer, that is, src.remaining(), at the moment this method is invoked. Upon return the + * buffer's position will updated; its limit will not have changed. Subclasses are encouraged to + * provide a more efficient implementation of this method. * * @param src The buffer from which bytes are to be retrieved * @return The number of bytes written, possibly zero @@ -164,12 +153,12 @@ public abstract class TTransport implements Closeable { * * @throws TTransportException if there was an error writing out data. */ - public void flush() - throws TTransportException {} + public void flush() throws TTransportException {} /** - * Access the protocol's underlying buffer directly. If this is not a - * buffered transport, return null. + * Access the protocol's underlying buffer directly. If this is not a buffered transport, return + * null. + * * @return protocol's Underlying buffer */ public byte[] getBuffer() { @@ -177,20 +166,22 @@ public abstract class TTransport implements Closeable { } /** - * Return the index within the underlying buffer that specifies the next spot - * that should be read from. - * @return index within the underlying buffer that specifies the next spot - * that should be read from + * Return the index within the underlying buffer that specifies the next spot that should be read + * from. + * + * @return index within the underlying buffer that specifies the next spot that should be read + * from */ public int getBufferPosition() { return 0; } /** - * Get the number of bytes remaining in the underlying buffer. Returns -1 if - * this is a non-buffered transport. - * @return the number of bytes remaining in the underlying buffer. <br> Returns -1 if - * this is a non-buffered transport. + * Get the number of bytes remaining in the underlying buffer. Returns -1 if this is a + * non-buffered transport. + * + * @return the number of bytes remaining in the underlying buffer. <br> + * Returns -1 if this is a non-buffered transport. */ public int getBytesRemainingInBuffer() { return -1; @@ -198,6 +189,7 @@ public abstract class TTransport implements Closeable { /** * Consume len bytes from the underlying buffer. + * * @param len the number of bytes to consume from the underlying buffer. */ public void consumeBuffer(int len) {} diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java b/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java index b886bc269..cc7532f2a 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TTransportException.java @@ -21,10 +21,7 @@ package org.apache.thrift.transport; import org.apache.thrift.TException; -/** - * Transport exceptions. - * - */ +/** Transport exceptions. */ public class TTransportException extends TException { private static final long serialVersionUID = 1L; @@ -77,5 +74,4 @@ public class TTransportException extends TException { public int getType() { return type_; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java b/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java index e068b4beb..ded5be432 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TTransportFactory.java @@ -20,11 +20,9 @@ package org.apache.thrift.transport; /** - * Factory class used to create wrapped instance of Transports. - * This is used primarily in servers, which get Transports from - * a ServerTransport and then may want to mutate them (i.e. create - * a BufferedTransport from the underlying base transport) - * + * Factory class used to create wrapped instance of Transports. This is used primarily in servers, + * which get Transports from a ServerTransport and then may want to mutate them (i.e. create a + * BufferedTransport from the underlying base transport) */ public class TTransportFactory { @@ -37,5 +35,4 @@ public class TTransportFactory { public TTransport getTransport(TTransport trans) throws TTransportException { return trans; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java index 73b21aa3f..e0b5b90b5 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/TZlibTransport.java @@ -18,8 +18,6 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -28,125 +26,129 @@ import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; +import org.apache.thrift.TConfiguration; -/** - * TZlibTransport deflates on write and inflates on read. - */ +/** TZlibTransport deflates on write and inflates on read. */ public class TZlibTransport extends TIOStreamTransport { - private TTransport transport_ = null; - - public static class Factory extends TTransportFactory { - public Factory() { - } - - @Override - public TTransport getTransport(TTransport base) throws TTransportException { - return new TZlibTransport(base); - } - } + private TTransport transport_ = null; - /** - * Constructs a new TZlibTransport instance. - * @param transport the underlying transport to read from and write to - */ - public TZlibTransport(TTransport transport) throws TTransportException { - this(transport, Deflater.BEST_COMPRESSION); - } - - /** - * Constructs a new TZlibTransport instance. - * @param transport the underlying transport to read from and write to - * @param compressionLevel 0 for no compression, 9 for maximum compression - */ - public TZlibTransport(TTransport transport, int compressionLevel) throws TTransportException { - super(Objects.isNull(transport.getConfiguration()) ? new TConfiguration() : transport.getConfiguration()); - transport_ = transport; - inputStream_ = new InflaterInputStream(new TTransportInputStream(transport_), new Inflater()); - outputStream_ = new DeflaterOutputStream(new TTransportOutputStream(transport_), new Deflater(compressionLevel, false), true); - } - - @Override - public boolean isOpen() { - return transport_.isOpen(); - } + public static class Factory extends TTransportFactory { + public Factory() {} @Override - public void open() throws TTransportException { - transport_.open(); + public TTransport getTransport(TTransport base) throws TTransportException { + return new TZlibTransport(base); } - - @Override - public void close() { - super.close(); - if (transport_.isOpen()) { - transport_.close(); - } + } + + /** + * Constructs a new TZlibTransport instance. + * + * @param transport the underlying transport to read from and write to + */ + public TZlibTransport(TTransport transport) throws TTransportException { + this(transport, Deflater.BEST_COMPRESSION); + } + + /** + * Constructs a new TZlibTransport instance. + * + * @param transport the underlying transport to read from and write to + * @param compressionLevel 0 for no compression, 9 for maximum compression + */ + public TZlibTransport(TTransport transport, int compressionLevel) throws TTransportException { + super( + Objects.isNull(transport.getConfiguration()) + ? new TConfiguration() + : transport.getConfiguration()); + transport_ = transport; + inputStream_ = new InflaterInputStream(new TTransportInputStream(transport_), new Inflater()); + outputStream_ = + new DeflaterOutputStream( + new TTransportOutputStream(transport_), new Deflater(compressionLevel, false), true); + } + + @Override + public boolean isOpen() { + return transport_.isOpen(); + } + + @Override + public void open() throws TTransportException { + transport_.open(); + } + + @Override + public void close() { + super.close(); + if (transport_.isOpen()) { + transport_.close(); } + } } class TTransportInputStream extends InputStream { - private TTransport transport = null; + private TTransport transport = null; - public TTransportInputStream(TTransport transport) { - this.transport = transport; - } + public TTransportInputStream(TTransport transport) { + this.transport = transport; + } - @Override - public int read() throws IOException { - try { - byte[] buf = new byte[1]; - transport.read(buf, 0, 1); - return buf[0]; - } catch (TTransportException e) { - throw new IOException(e); - } + @Override + public int read() throws IOException { + try { + byte[] buf = new byte[1]; + transport.read(buf, 0, 1); + return buf[0]; + } catch (TTransportException e) { + throw new IOException(e); } - - @Override - public int read(byte b[], int off, int len) throws IOException { - try { - return transport.read(b, off, len); - } catch (TTransportException e) { - throw new IOException(e); - } + } + + @Override + public int read(byte b[], int off, int len) throws IOException { + try { + return transport.read(b, off, len); + } catch (TTransportException e) { + throw new IOException(e); } + } } class TTransportOutputStream extends OutputStream { - private TTransport transport = null; + private TTransport transport = null; - public TTransportOutputStream(TTransport transport) { - this.transport = transport; - } + public TTransportOutputStream(TTransport transport) { + this.transport = transport; + } - @Override - public void write(final int b) throws IOException { - try { - transport.write(new byte[]{(byte) b}); - } catch (TTransportException e) { - throw new IOException(e); - } + @Override + public void write(final int b) throws IOException { + try { + transport.write(new byte[] {(byte) b}); + } catch (TTransportException e) { + throw new IOException(e); } - - @Override - public void write(byte b[], int off, int len) throws IOException { - try { - transport.write(b, off, len); - } catch (TTransportException e) { - throw new IOException(e); - } + } + + @Override + public void write(byte b[], int off, int len) throws IOException { + try { + transport.write(b, off, len); + } catch (TTransportException e) { + throw new IOException(e); } - - @Override - public void flush() throws IOException { - try { - transport.flush(); - } catch (TTransportException e) { - throw new IOException(e); - } + } + + @Override + public void flush() throws IOException { + try { + transport.flush(); + } catch (TTransportException e) { + throw new IOException(e); } + } } - diff --git a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java index 29bf39c14..45f4e97ee 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java @@ -18,20 +18,17 @@ */ package org.apache.thrift.transport.layered; - +import java.util.Objects; import org.apache.thrift.TConfiguration; import org.apache.thrift.transport.*; -import java.util.Objects; - /** - * This transport is wire compatible with {@link TFramedTransport}, but makes - * use of reusable, expanding read and write buffers in order to avoid - * allocating new byte[]s all the time. Since the buffers only expand, you - * should probably only use this transport if your messages are not too variably - * large, unless the persistent memory cost is not an issue. + * This transport is wire compatible with {@link TFramedTransport}, but makes use of reusable, + * expanding read and write buffers in order to avoid allocating new byte[]s all the time. Since the + * buffers only expand, you should probably only use this transport if your messages are not too + * variably large, unless the persistent memory cost is not an issue. * - * This implementation is NOT threadsafe. + * <p>This implementation is NOT threadsafe. */ public class TFastFramedTransport extends TLayeredTransport { @@ -54,15 +51,11 @@ public class TFastFramedTransport extends TLayeredTransport { @Override public TTransport getTransport(TTransport trans) throws TTransportException { - return new TFastFramedTransport(trans, - initialCapacity, - maxLength); + return new TFastFramedTransport(trans, initialCapacity, maxLength); } } - /** - * How big should the default read and write buffers be? - */ + /** How big should the default read and write buffers be? */ public static final int DEFAULT_BUF_CAPACITY = 1024; private final AutoExpandingBufferWriteTransport writeBuffer; @@ -72,8 +65,9 @@ public class TFastFramedTransport extends TLayeredTransport { private final int maxLength; /** - * Create a new {@link TFastFramedTransport}. Use the defaults - * for initial buffer size and max frame length. + * Create a new {@link TFastFramedTransport}. Use the defaults for initial buffer size and max + * frame length. + * * @param underlying Transport that real reads and writes will go through to. */ public TFastFramedTransport(TTransport underlying) throws TTransportException { @@ -81,31 +75,35 @@ public class TFastFramedTransport extends TLayeredTransport { } /** - * Create a new {@link TFastFramedTransport}. Use the specified - * initial buffer capacity and the default max frame length. + * Create a new {@link TFastFramedTransport}. Use the specified initial buffer capacity and the + * default max frame length. + * * @param underlying Transport that real reads and writes will go through to. - * @param initialBufferCapacity The initial size of the read and write buffers. - * In practice, it's not critical to set this unless you know in advance that - * your messages are going to be very large. + * @param initialBufferCapacity The initial size of the read and write buffers. In practice, it's + * not critical to set this unless you know in advance that your messages are going to be very + * large. */ - public TFastFramedTransport(TTransport underlying, int initialBufferCapacity) throws TTransportException { + public TFastFramedTransport(TTransport underlying, int initialBufferCapacity) + throws TTransportException { this(underlying, initialBufferCapacity, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } /** - * * @param underlying Transport that real reads and writes will go through to. - * @param initialBufferCapacity The initial size of the read and write buffers. - * In practice, it's not critical to set this unless you know in advance that - * your messages are going to be very large. (You can pass - * TFramedTransportWithReusableBuffer.DEFAULT_BUF_CAPACITY if you're only - * using this constructor because you want to set the maxLength.) - * @param maxLength The max frame size you are willing to read. You can use - * this parameter to limit how much memory can be allocated. + * @param initialBufferCapacity The initial size of the read and write buffers. In practice, it's + * not critical to set this unless you know in advance that your messages are going to be very + * large. (You can pass TFramedTransportWithReusableBuffer.DEFAULT_BUF_CAPACITY if you're only + * using this constructor because you want to set the maxLength.) + * @param maxLength The max frame size you are willing to read. You can use this parameter to + * limit how much memory can be allocated. */ - public TFastFramedTransport(TTransport underlying, int initialBufferCapacity, int maxLength) throws TTransportException { + public TFastFramedTransport(TTransport underlying, int initialBufferCapacity, int maxLength) + throws TTransportException { super(underlying); - TConfiguration config = Objects.isNull(underlying.getConfiguration()) ? new TConfiguration() : underlying.getConfiguration(); + TConfiguration config = + Objects.isNull(underlying.getConfiguration()) + ? new TConfiguration() + : underlying.getConfiguration(); this.maxLength = maxLength; config.setMaxFrameSize(maxLength); this.initialBufferCapacity = initialBufferCapacity; @@ -142,17 +140,19 @@ public class TFastFramedTransport extends TLayeredTransport { } private void readFrame() throws TTransportException { - getInnerTransport().readAll(i32buf , 0, 4); + getInnerTransport().readAll(i32buf, 0, 4); int size = TFramedTransport.decodeFrameSize(i32buf); if (size < 0) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); + throw new TTransportException( + TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); } if (size > getInnerTransport().getConfiguration().getMaxFrameSize()) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, + throw new TTransportException( + TTransportException.CORRUPTED_DATA, "Frame size (" + size + ") larger than max length (" + maxLength + ")!"); } @@ -169,9 +169,7 @@ public class TFastFramedTransport extends TLayeredTransport { readBuffer.consumeBuffer(len); } - /** - * Only clears the read buffer! - */ + /** Only clears the read buffer! */ public void clear() throws TTransportException { readBuffer = new AutoExpandingBufferReadTransport(getConfiguration(), initialBufferCapacity); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java index 10a9a1c17..6ba40187b 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/layered/TFramedTransport.java @@ -19,6 +19,7 @@ package org.apache.thrift.transport.layered; +import java.util.Objects; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TConfiguration; import org.apache.thrift.transport.TMemoryInputTransport; @@ -26,23 +27,16 @@ import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.transport.TTransportFactory; -import java.util.Objects; - /** - * TFramedTransport is a buffered TTransport that ensures a fully read message - * every time by preceding messages with a 4-byte frame size. + * TFramedTransport is a buffered TTransport that ensures a fully read message every time by + * preceding messages with a 4-byte frame size. */ public class TFramedTransport extends TLayeredTransport { - /** - * Buffer for output - */ - private final TByteArrayOutputStream writeBuffer_ = - new TByteArrayOutputStream(1024); + /** Buffer for output */ + private final TByteArrayOutputStream writeBuffer_ = new TByteArrayOutputStream(1024); - /** - * Buffer for input - */ + /** Buffer for input */ private final TMemoryInputTransport readBuffer_; public static class Factory extends TTransportFactory { @@ -63,21 +57,21 @@ public class TFramedTransport extends TLayeredTransport { } /** - * Something to fill in the first four bytes of the buffer - * to make room for the frame size. This allows the - * implementation to write once instead of twice. + * Something to fill in the first four bytes of the buffer to make room for the frame size. This + * allows the implementation to write once instead of twice. */ - private static final byte[] sizeFiller_ = new byte[] { 0x00, 0x00, 0x00, 0x00 }; + private static final byte[] sizeFiller_ = new byte[] {0x00, 0x00, 0x00, 0x00}; - /** - * Constructor wraps around another transport - */ + /** Constructor wraps around another transport */ public TFramedTransport(TTransport transport, int maxLength) throws TTransportException { super(transport); - TConfiguration _configuration = Objects.isNull(transport.getConfiguration()) ? new TConfiguration() : transport.getConfiguration(); + TConfiguration _configuration = + Objects.isNull(transport.getConfiguration()) + ? new TConfiguration() + : transport.getConfiguration(); _configuration.setMaxFrameSize(maxLength); writeBuffer_.write(sizeFiller_, 0, 4); - readBuffer_= new TMemoryInputTransport(_configuration, new byte[0]); + readBuffer_ = new TMemoryInputTransport(_configuration, new byte[0]); } public TFramedTransport(TTransport transport) throws TTransportException { @@ -140,13 +134,19 @@ public class TFramedTransport extends TLayeredTransport { if (size < 0) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); + throw new TTransportException( + TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); } if (size > getInnerTransport().getConfiguration().getMaxFrameSize()) { close(); - throw new TTransportException(TTransportException.CORRUPTED_DATA, - "Frame size (" + size + ") larger than max length (" + getInnerTransport().getConfiguration().getMaxFrameSize() + ")!"); + throw new TTransportException( + TTransportException.CORRUPTED_DATA, + "Frame size (" + + size + + ") larger than max length (" + + getInnerTransport().getConfiguration().getMaxFrameSize() + + ")!"); } byte[] buff = new byte[size]; @@ -161,27 +161,26 @@ public class TFramedTransport extends TLayeredTransport { @Override public void flush() throws TTransportException { byte[] buf = writeBuffer_.get(); - int len = writeBuffer_.len() - 4; // account for the prepended frame size + int len = writeBuffer_.len() - 4; // account for the prepended frame size writeBuffer_.reset(); - writeBuffer_.write(sizeFiller_, 0, 4); // make room for the next frame's size data + writeBuffer_.write(sizeFiller_, 0, 4); // make room for the next frame's size data - encodeFrameSize(len, buf); // this is the frame length without the filler - getInnerTransport().write(buf, 0, len + 4); // we have to write the frame size and frame data + encodeFrameSize(len, buf); // this is the frame length without the filler + getInnerTransport().write(buf, 0, len + 4); // we have to write the frame size and frame data getInnerTransport().flush(); } public static final void encodeFrameSize(final int frameSize, final byte[] buf) { - buf[0] = (byte)(0xff & (frameSize >> 24)); - buf[1] = (byte)(0xff & (frameSize >> 16)); - buf[2] = (byte)(0xff & (frameSize >> 8)); - buf[3] = (byte)(0xff & (frameSize)); + buf[0] = (byte) (0xff & (frameSize >> 24)); + buf[1] = (byte) (0xff & (frameSize >> 16)); + buf[2] = (byte) (0xff & (frameSize >> 8)); + buf[3] = (byte) (0xff & (frameSize)); } public static final int decodeFrameSize(final byte[] buf) { - return - ((buf[0] & 0xff) << 24) | - ((buf[1] & 0xff) << 16) | - ((buf[2] & 0xff) << 8) | - ((buf[3] & 0xff)); + return ((buf[0] & 0xff) << 24) + | ((buf[1] & 0xff) << 16) + | ((buf[2] & 0xff) << 8) + | ((buf[3] & 0xff)); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java b/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java index 69ec824ee..6e3d1964d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/layered/TLayeredTransport.java @@ -18,35 +18,33 @@ */ package org.apache.thrift.transport.layered; +import java.util.Objects; import org.apache.thrift.TConfiguration; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; -import java.util.Objects; - -public abstract class TLayeredTransport extends TTransport{ +public abstract class TLayeredTransport extends TTransport { - private TTransport innerTransport; + private TTransport innerTransport; - public TConfiguration getConfiguration() { - return innerTransport.getConfiguration(); - } + public TConfiguration getConfiguration() { + return innerTransport.getConfiguration(); + } - public TLayeredTransport(TTransport transport) - { - Objects.requireNonNull(transport, "TTransport cannot be null."); - innerTransport = transport; - } + public TLayeredTransport(TTransport transport) { + Objects.requireNonNull(transport, "TTransport cannot be null."); + innerTransport = transport; + } - public void updateKnownMessageSize(long size) throws TTransportException { - innerTransport.updateKnownMessageSize(size); - } + public void updateKnownMessageSize(long size) throws TTransportException { + innerTransport.updateKnownMessageSize(size); + } - public void checkReadBytesAvailable(long numBytes) throws TTransportException { - innerTransport.checkReadBytesAvailable(numBytes); - } + public void checkReadBytesAvailable(long numBytes) throws TTransportException { + innerTransport.checkReadBytesAvailable(numBytes); + } - public TTransport getInnerTransport() { - return innerTransport; - } + public TTransport getInnerTransport() { + return innerTransport; + } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java index 2900df9c1..399ccc62d 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameHeaderReader.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * The header for data frame, it only contains a 4-byte payload size. - */ +/** The header for data frame, it only contains a 4-byte payload size. */ public class DataFrameHeaderReader extends FixedSizeHeaderReader { public static final int PAYLOAD_LENGTH_BYTES = 4; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java index e6900bbc6..cd5c002fa 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameReader.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * Frames for thrift (serialized) messages. - */ +/** Frames for thrift (serialized) messages. */ public class DataFrameReader extends FrameReader<DataFrameHeaderReader> { public DataFrameReader() { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java index a2dd15a8c..b79537dd8 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/DataFrameWriter.java @@ -19,34 +19,43 @@ package org.apache.thrift.transport.sasl; -import java.nio.ByteBuffer; +import static org.apache.thrift.transport.sasl.DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES; +import java.nio.ByteBuffer; import org.apache.thrift.EncodingUtils; import org.apache.thrift.utils.StringUtils; -import static org.apache.thrift.transport.sasl.DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES; - /** - * Write frames of thrift messages. It expects an empty/null header to be provided with a payload - * to be written out. Non empty headers are considered as error. + * Write frames of thrift messages. It expects an empty/null header to be provided with a payload to + * be written out. Non empty headers are considered as error. */ public class DataFrameWriter extends FrameWriter { @Override public void withOnlyPayload(byte[] payload, int offset, int length) { if (!isComplete()) { - throw new IllegalStateException("Previsous write is not yet complete, with " + - frameBytes.remaining() + " bytes left."); + throw new IllegalStateException( + "Previsous write is not yet complete, with " + frameBytes.remaining() + " bytes left."); } frameBytes = buildFrameWithPayload(payload, offset, length); } @Override - protected ByteBuffer buildFrame(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength) { + protected ByteBuffer buildFrame( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength) { if (header != null && headerLength > 0) { - throw new IllegalArgumentException("Extra header [" + StringUtils.bytesToHexString(header) + - "] offset " + payloadOffset + " length " + payloadLength); + throw new IllegalArgumentException( + "Extra header [" + + StringUtils.bytesToHexString(header) + + "] offset " + + payloadOffset + + " length " + + payloadLength); } return buildFrameWithPayload(payload, payloadOffset, payloadLength); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java index 1cbc0ace0..4f90faf85 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FixedSizeHeaderReader.java @@ -19,15 +19,12 @@ package org.apache.thrift.transport.sasl; +import java.nio.ByteBuffer; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.utils.StringUtils; -import java.nio.ByteBuffer; - -/** - * Headers' size should be predefined. - */ +/** Headers' size should be predefined. */ public abstract class FixedSizeHeaderReader implements FrameHeaderReader { protected final ByteBuffer byteBuffer = ByteBuffer.allocate(headerSize()); @@ -45,7 +42,9 @@ public abstract class FixedSizeHeaderReader implements FrameHeaderReader { @Override public byte[] toBytes() { if (!isComplete()) { - throw new IllegalStateException("Header is not yet complete " + StringUtils.bytesToHexString(byteBuffer.array(), 0, byteBuffer.position())); + throw new IllegalStateException( + "Header is not yet complete " + + StringUtils.bytesToHexString(byteBuffer.array(), 0, byteBuffer.position())); } return byteBuffer.array(); } @@ -60,9 +59,7 @@ public abstract class FixedSizeHeaderReader implements FrameHeaderReader { return true; } - /** - * @return Size of the header. - */ + /** @return Size of the header. */ protected abstract int headerSize(); /** diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java index f7c659315..d618346a4 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameHeaderReader.java @@ -36,20 +36,15 @@ public interface FrameHeaderReader { int payloadSize(); /** - * * @return The received bytes for the header. * @throws IllegalStateException if isComplete returns false. */ byte[] toBytes(); - /** - * @return true if this header has all its fields set. - */ + /** @return true if this header has all its fields set. */ boolean isComplete(); - /** - * Clear the header and make it available to read a new header. - */ + /** Clear the header and make it available to read a new header. */ void clear(); /** diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java index acb4b738d..1f5872c30 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameReader.java @@ -19,16 +19,15 @@ package org.apache.thrift.transport.sasl; +import java.nio.ByteBuffer; import org.apache.thrift.transport.TEOFException; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; -import java.nio.ByteBuffer; - /** - * Read frames from a transport. Each frame has a header and a payload. A header will indicate - * the size of the payload and other informations about how to decode payload. - * Implementations should subclass it by providing a header reader implementation. + * Read frames from a transport. Each frame has a header and a payload. A header will indicate the + * size of the payload and other informations about how to decode payload. Implementations should + * subclass it by providing a header reader implementation. * * @param <T> Header type. */ @@ -70,7 +69,8 @@ public abstract class FrameReader<T extends FrameHeaderReader> { * @throws TSaslNegotiationException if fail to read back a validd sasl negotiation header. * @throws TTransportException if io error. */ - private boolean readHeader(TTransport transport) throws TSaslNegotiationException, TTransportException { + private boolean readHeader(TTransport transport) + throws TSaslNegotiationException, TTransportException { return header.read(transport); } @@ -86,49 +86,32 @@ public abstract class FrameReader<T extends FrameHeaderReader> { return payload.hasRemaining(); } - /** - * - * @return header of the frame - */ + /** @return header of the frame */ public T getHeader() { return header; } - /** - * - * @return number of bytes of the header - */ + /** @return number of bytes of the header */ public int getHeaderSize() { return header.toBytes().length; } - /** - * - * @return byte array of the payload - */ + /** @return byte array of the payload */ public byte[] getPayload() { return payload.array(); } - /** - * - * @return size of the payload - */ + /** @return size of the payload */ public int getPayloadSize() { return header.payloadSize(); } - /** - * - * @return true if the reader has fully read a frame - */ + /** @return true if the reader has fully read a frame */ public boolean isComplete() { return !(payload == null || payload.hasRemaining()); } - /** - * Reset the state of the reader so that it can be reused to read a new frame. - */ + /** Reset the state of the reader so that it can be reused to read a new frame. */ public void clear() { header.clear(); payload = null; @@ -144,8 +127,8 @@ public abstract class FrameReader<T extends FrameHeaderReader> { */ static int readAvailable(TTransport transport, ByteBuffer recipient) throws TTransportException { if (!recipient.hasRemaining()) { - throw new IllegalStateException("Trying to fill a full recipient with " + recipient.limit() - + " bytes"); + throw new IllegalStateException( + "Trying to fill a full recipient with " + recipient.limit() + " bytes"); } int currentPosition = recipient.position(); byte[] bytes = recipient.array(); @@ -153,8 +136,8 @@ public abstract class FrameReader<T extends FrameHeaderReader> { int expectedLength = recipient.remaining(); int got = transport.read(bytes, offset, expectedLength); if (got < 0) { - throw new TEOFException("Transport is closed, while trying to read " + expectedLength + - " bytes"); + throw new TEOFException( + "Transport is closed, while trying to read " + expectedLength + " bytes"); } recipient.position(currentPosition + got); return got; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java index 4357f13e1..bae6d4999 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/FrameWriter.java @@ -19,15 +19,11 @@ package org.apache.thrift.transport.sasl; -import java.io.IOException; import java.nio.ByteBuffer; - import org.apache.thrift.transport.TNonblockingTransport; import org.apache.thrift.transport.TTransportException; -/** - * Write frame (header and payload) to transport in a nonblocking way. - */ +/** Write frame (header and payload) to transport in a nonblocking way. */ public abstract class FrameWriter { protected ByteBuffer frameBytes; @@ -37,7 +33,7 @@ public abstract class FrameWriter { * returns true (last frame has been written out). * * @param header Some extra header bytes (without the 4 bytes for payload length), which will be - * the start of the frame. It can be empty, depending on the message format + * the start of the frame. It can be empty, depending on the message format * @param payload Payload as a byte array * @throws IllegalStateException if it is called when isComplete returns false * @throws IllegalArgumentException if header or payload is invalid @@ -65,18 +61,24 @@ public abstract class FrameWriter { * @throws IllegalStateException if preivous frame is not yet complete (isComplete returns fals) * @throws IllegalArgumentException if header or payload is invalid */ - public void withHeaderAndPayload(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength) { + public void withHeaderAndPayload( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength) { if (!isComplete()) { - throw new IllegalStateException("Previsous write is not yet complete, with " + - frameBytes.remaining() + " bytes left."); + throw new IllegalStateException( + "Previsous write is not yet complete, with " + frameBytes.remaining() + " bytes left."); } - frameBytes = buildFrame(header, headerOffset, headerLength, payload, payloadOffset, payloadLength); + frameBytes = + buildFrame(header, headerOffset, headerLength, payload, payloadOffset, payloadLength); } /** - * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects - * a header. + * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects a + * header. * * @param payload payload as a byte array */ @@ -85,8 +87,8 @@ public abstract class FrameWriter { } /** - * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects - * a header. + * Provide only payload to the frame. Throws UnsupportedOperationException if the frame expects a + * header. * * @param payload The underlying byte array as a recipient of the payload * @param offset The offset in the byte array starting from where the payload is located @@ -94,8 +96,13 @@ public abstract class FrameWriter { */ public abstract void withOnlyPayload(byte[] payload, int offset, int length); - protected abstract ByteBuffer buildFrame(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength); + protected abstract ByteBuffer buildFrame( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength); /** * Nonblocking write to the underlying transport. @@ -106,17 +113,12 @@ public abstract class FrameWriter { transport.write(frameBytes); } - /** - * - * @return true when no more data needs to be written out - */ + /** @return true when no more data needs to be written out */ public boolean isComplete() { return frameBytes == null || !frameBytes.hasRemaining(); } - /** - * Release the byte buffer. - */ + /** Release the byte buffer. */ public void clear() { frameBytes = null; } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java index ad704a0a1..9b0ddcba0 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NegotiationStatus.java @@ -19,20 +19,18 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; + import java.util.HashMap; import java.util.Map; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; - -/** - * Status bytes used during the initial Thrift SASL handshake. - */ +/** Status bytes used during the initial Thrift SASL handshake. */ public enum NegotiationStatus { - START((byte)0x01), - OK((byte)0x02), - BAD((byte)0x03), - ERROR((byte)0x04), - COMPLETE((byte)0x05); + START((byte) 0x01), + OK((byte) 0x02), + BAD((byte) 0x03), + ERROR((byte) 0x04), + COMPLETE((byte) 0x05); private static final Map<Byte, NegotiationStatus> reverseMap = new HashMap<>(); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java index d73c3ec18..2557a4285 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/NonblockingSaslHandler.java @@ -19,11 +19,12 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.NegotiationStatus.COMPLETE; +import static org.apache.thrift.transport.sasl.NegotiationStatus.OK; + import java.nio.channels.SelectionKey; import java.nio.charset.StandardCharsets; - import javax.security.sasl.SaslServer; - import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; @@ -37,12 +38,7 @@ import org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.thrift.transport.sasl.NegotiationStatus.COMPLETE; -import static org.apache.thrift.transport.sasl.NegotiationStatus.OK; - -/** - * State machine managing one sasl connection in a nonblocking way. - */ +/** State machine managing one sasl connection in a nonblocking way. */ public class NonblockingSaslHandler { private static final Logger LOGGER = LoggerFactory.getLogger(NonblockingSaslHandler.class); @@ -86,10 +82,14 @@ public class NonblockingSaslHandler { // If sasl is negotiated for integrity/confidentiality protection private boolean dataProtected; - public NonblockingSaslHandler(SelectionKey selectionKey, TNonblockingTransport underlyingTransport, - TSaslServerFactory saslServerFactory, TSaslProcessorFactory processorFactory, - TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, - TServerEventHandler eventHandler) { + public NonblockingSaslHandler( + SelectionKey selectionKey, + TNonblockingTransport underlyingTransport, + TSaslServerFactory saslServerFactory, + TSaslProcessorFactory processorFactory, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + TServerEventHandler eventHandler) { this.selectionKey = selectionKey; this.underlyingTransport = underlyingTransport; this.saslServerFactory = saslServerFactory; @@ -114,8 +114,8 @@ public class NonblockingSaslHandler { } /** - * Get next phase of the state machine. - * It is different from current phase iff current phase is done (and next phase not yet started). + * Get next phase of the state machine. It is different from current phase iff current phase is + * done (and next phase not yet started). * * @return next phase. */ @@ -123,26 +123,17 @@ public class NonblockingSaslHandler { return nextPhase; } - /** - * - * @return underlying nonblocking socket - */ + /** @return underlying nonblocking socket */ public TNonblockingTransport getUnderlyingTransport() { return underlyingTransport; } - /** - * - * @return SaslServer instance - */ + /** @return SaslServer instance */ public SaslServer getSaslServer() { return saslPeer.getSaslServer(); } - /** - * - * @return true if current phase is done. - */ + /** @return true if current phase is done. */ public boolean isCurrentPhaseDone() { return currentPhase != nextPhase; } @@ -178,8 +169,8 @@ public class NonblockingSaslHandler { private void handleOps(int interestOps) { if (currentPhase.selectionInterest != interestOps) { - throw new IllegalStateException("Current phase " + currentPhase + " but got interest " + - interestOps); + throw new IllegalStateException( + "Current phase " + currentPhase + " but got interest " + interestOps); } runCurrentPhase(); if (isCurrentPhaseDone() && nextPhase.selectionInterest == interestOps) { @@ -190,8 +181,8 @@ public class NonblockingSaslHandler { /** * When current phase is finished, it's expected to call this method first before running the - * state machine again. - * By calling this, "next phase" is marked as started (and not done), thus is ready to run. + * state machine again. By calling this, "next phase" is marked as started (and not done), thus is + * ready to run. * * @throws IllegalArgumentException if current phase is not yet done. */ @@ -207,8 +198,8 @@ public class NonblockingSaslHandler { } // If next phase's interest is not the same as current, nor the same as the selection key, // we need to change interest on the selector. - if (!(nextPhase.selectionInterest == currentPhase.selectionInterest || - nextPhase.selectionInterest == selectionKey.interestOps())) { + if (!(nextPhase.selectionInterest == currentPhase.selectionInterest + || nextPhase.selectionInterest == selectionKey.interestOps())) { changeSelectionInterest(nextPhase.selectionInterest); } currentPhase = nextPhase; @@ -222,8 +213,8 @@ public class NonblockingSaslHandler { private void failSaslNegotiation(TSaslNegotiationException e) { LOGGER.error("Sasl negotiation failed", e); String errorMsg = e.getDetails(); - saslChallenge.withHeaderAndPayload(new byte[]{e.getErrorType().code.getValue()}, - errorMsg.getBytes(StandardCharsets.UTF_8)); + saslChallenge.withHeaderAndPayload( + new byte[] {e.getErrorType().code.getValue()}, errorMsg.getBytes(StandardCharsets.UTF_8)); nextPhase = Phase.WRITING_FAILURE_MESSAGE; } @@ -233,10 +224,8 @@ public class NonblockingSaslHandler { } private void failIO(TTransportException e) { - StringBuilder errorMsg = new StringBuilder("IO failure ") - .append(e.getType()) - .append(" in ") - .append(currentPhase); + StringBuilder errorMsg = + new StringBuilder("IO failure ").append(e.getType()).append(" in ").append(currentPhase); if (e.getMessage() != null) { errorMsg.append(": ").append(e.getMessage()); } @@ -252,7 +241,8 @@ public class NonblockingSaslHandler { if (saslResponse.isComplete()) { SaslNegotiationHeaderReader startHeader = saslResponse.getHeader(); if (startHeader.getStatus() != NegotiationStatus.START) { - throw new TInvalidSaslFrameException("Expecting START status but got " + startHeader.getStatus()); + throw new TInvalidSaslFrameException( + "Expecting START status but got " + startHeader.getStatus()); } String mechanism = new String(saslResponse.getPayload(), StandardCharsets.UTF_8); saslPeer = saslServerFactory.getSaslPeer(mechanism); @@ -293,8 +283,10 @@ public class NonblockingSaslHandler { // Computation executions private void executeEvaluatingSaslResponse() { - if (!(saslResponse.getHeader().getStatus() == OK || saslResponse.getHeader().getStatus() == COMPLETE)) { - String error = "Expect status OK or COMPLETE, but got " + saslResponse.getHeader().getStatus(); + if (!(saslResponse.getHeader().getStatus() == OK + || saslResponse.getHeader().getStatus() == COMPLETE)) { + String error = + "Expect status OK or COMPLETE, but got " + saslResponse.getHeader().getStatus(); failSaslNegotiation(new TSaslNegotiationException(ErrorType.PROTOCOL_ERROR, error)); return; } @@ -304,10 +296,10 @@ public class NonblockingSaslHandler { byte[] newChallenge = saslPeer.evaluate(response); if (saslPeer.isAuthenticated()) { dataProtected = saslPeer.isDataProtected(); - saslChallenge.withHeaderAndPayload(new byte[]{COMPLETE.getValue()}, newChallenge); + saslChallenge.withHeaderAndPayload(new byte[] {COMPLETE.getValue()}, newChallenge); nextPhase = Phase.WRITING_SUCCESS_MESSAGE; } else { - saslChallenge.withHeaderAndPayload(new byte[]{OK.getValue()}, newChallenge); + saslChallenge.withHeaderAndPayload(new byte[] {OK.getValue()}, newChallenge); nextPhase = Phase.WRITING_SASL_CHALLENGE; } } catch (TSaslNegotiationException e) { @@ -344,7 +336,7 @@ public class NonblockingSaslHandler { byte[] outputPayload = saslPeer.wrap(rawOutput.get(), 0, rawOutput.len()); responseWriter.withOnlyPayload(outputPayload); } else { - responseWriter.withOnlyPayload(rawOutput.get(), 0 ,rawOutput.len()); + responseWriter.withOnlyPayload(rawOutput.get(), 0, rawOutput.len()); } nextPhase = Phase.WRITING_RESPONSE; } catch (TTransportException e) { @@ -406,8 +398,9 @@ public class NonblockingSaslHandler { } /** - * Release all the resources managed by this state machine (connection, selection and sasl server). - * To avoid being blocked, this should be invoked in the network thread that manages the selector. + * Release all the resources managed by this state machine (connection, selection and sasl + * server). To avoid being blocked, this should be invoked in the network thread that manages the + * selector. */ public void close() { underlyingTransport.close(); @@ -416,7 +409,8 @@ public class NonblockingSaslHandler { saslPeer.dispose(); } if (serverContextCreated) { - eventHandler.deleteContext(serverContext, + eventHandler.deleteContext( + serverContext, inputProtocolFactory.getProtocol(underlyingTransport), outputProtocolFactory.getProtocol(underlyingTransport)); } @@ -491,8 +485,7 @@ public class NonblockingSaslHandler { void unsafeRun(NonblockingSaslHandler statemachine) { // Do nothing. } - } - ; + }; // The interest on the selection key during the phase private int selectionInterest; @@ -511,8 +504,8 @@ public class NonblockingSaslHandler { */ void runStateMachine(NonblockingSaslHandler statemachine) { if (statemachine.currentPhase != this) { - throw new IllegalArgumentException("State machine is " + statemachine.currentPhase + - " but is expected to be " + this); + throw new IllegalArgumentException( + "State machine is " + statemachine.currentPhase + " but is expected to be " + this); } if (statemachine.isCurrentPhaseDone()) { throw new IllegalStateException("State machine should step into " + statemachine.nextPhase); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java index 01c172836..ede2177d5 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameReader.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * Read frames for sasl negotiatiions. - */ +/** Read frames for sasl negotiatiions. */ public class SaslNegotiationFrameReader extends FrameReader<SaslNegotiationHeaderReader> { public SaslNegotiationFrameReader() { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java index 1e9ad1570..186d6d065 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationFrameWriter.java @@ -19,14 +19,13 @@ package org.apache.thrift.transport.sasl; -import java.nio.ByteBuffer; +import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.PAYLOAD_LENGTH_BYTES; +import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.STATUS_BYTES; +import java.nio.ByteBuffer; import org.apache.thrift.EncodingUtils; import org.apache.thrift.utils.StringUtils; -import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.PAYLOAD_LENGTH_BYTES; -import static org.apache.thrift.transport.sasl.SaslNegotiationHeaderReader.STATUS_BYTES; - /** * Writer for sasl negotiation frames. It expect a status byte as header with a payload to be * written out (any header whose size is not equal to 1 would be considered as error). @@ -41,11 +40,19 @@ public class SaslNegotiationFrameWriter extends FrameWriter { } @Override - protected ByteBuffer buildFrame(byte[] header, int headerOffset, int headerLength, - byte[] payload, int payloadOffset, int payloadLength) { + protected ByteBuffer buildFrame( + byte[] header, + int headerOffset, + int headerLength, + byte[] payload, + int payloadOffset, + int payloadLength) { if (header == null || headerLength != STATUS_BYTES) { - throw new IllegalArgumentException("Header " + StringUtils.bytesToHexString(header) + - " does not have expected length " + STATUS_BYTES); + throw new IllegalArgumentException( + "Header " + + StringUtils.bytesToHexString(header) + + " does not have expected length " + + STATUS_BYTES); } byte[] bytes = new byte[HEADER_BYTES + payloadLength]; System.arraycopy(header, headerOffset, bytes, 0, STATUS_BYTES); diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java index 2d76ddb29..554758572 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslNegotiationHeaderReader.java @@ -42,7 +42,8 @@ public class SaslNegotiationHeaderReader extends FixedSizeHeaderReader { negotiationStatus = NegotiationStatus.byValue(byteBuffer.get(0)); payloadSize = byteBuffer.getInt(1); if (payloadSize < 0) { - throw new TSaslNegotiationException(PROTOCOL_ERROR, "Payload size is negative: " + payloadSize); + throw new TSaslNegotiationException( + PROTOCOL_ERROR, "Payload size is negative: " + payloadSize); } } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java index 8f8138044..9a9e733da 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/SaslPeer.java @@ -21,9 +21,7 @@ package org.apache.thrift.transport.sasl; import org.apache.thrift.transport.TTransportException; -/** - * A peer in a sasl negotiation. - */ +/** A peer in a sasl negotiation. */ public interface SaslPeer { /** @@ -35,9 +33,7 @@ public interface SaslPeer { */ byte[] evaluate(byte[] negotiationMessage) throws TSaslNegotiationException; - /** - * @return true if authentication is done. - */ + /** @return true if authentication is done. */ boolean isAuthenticated(); /** @@ -93,8 +89,6 @@ public interface SaslPeer { return unwrap(data, 0, data.length); } - /** - * Close this peer and release resources. - */ + /** Close this peer and release resources. */ void dispose(); } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java index 31992e5fc..0264531d6 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/ServerSaslPeer.java @@ -19,19 +19,16 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.AUTHENTICATION_FAILURE; + import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; - import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.AUTHENTICATION_FAILURE; - -/** - * Server side sasl peer, a wrapper around SaslServer to provide some handy methods. - */ +/** Server side sasl peer, a wrapper around SaslServer to provide some handy methods. */ public class ServerSaslPeer implements SaslPeer { private static final Logger LOGGER = LoggerFactory.getLogger(ServerSaslPeer.class); @@ -49,8 +46,8 @@ public class ServerSaslPeer implements SaslPeer { try { return saslServer.evaluateResponse(negotiationMessage); } catch (SaslException e) { - throw new TSaslNegotiationException(AUTHENTICATION_FAILURE, - "Authentication failed with " + saslServer.getMechanismName(), e); + throw new TSaslNegotiationException( + AUTHENTICATION_FAILURE, "Authentication failed with " + saslServer.getMechanismName(), e); } } @@ -104,5 +101,4 @@ public class ServerSaslPeer implements SaslPeer { SaslServer getSaslServer() { return saslServer; } - } diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java index ff57ea5c4..3ec88165c 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TInvalidSaslFrameException.java @@ -19,9 +19,7 @@ package org.apache.thrift.transport.sasl; -/** - * Got an invalid frame that does not respect the thrift sasl protocol. - */ +/** Got an invalid frame that does not respect the thrift sasl protocol. */ public class TInvalidSaslFrameException extends TSaslNegotiationException { public TInvalidSaslFrameException(String message) { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java index 9b1fa060e..15c597e13 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslNegotiationException.java @@ -21,9 +21,7 @@ package org.apache.thrift.transport.sasl; import org.apache.thrift.transport.TTransportException; -/** - * Exception for sasl negotiation errors. - */ +/** Exception for sasl negotiation errors. */ public class TSaslNegotiationException extends TTransportException { private final ErrorType error; @@ -42,18 +40,16 @@ public class TSaslNegotiationException extends TTransportException { return error; } - /** - * @return Errory type plus the message. - */ + /** @return Errory type plus the message. */ public String getSummary() { return error.name() + ": " + getMessage(); } - /** - * @return Summary and eventually the cause's message. - */ + /** @return Summary and eventually the cause's message. */ public String getDetails() { - return getCause() == null ? getSummary() : getSummary() + "\nReason: " + getCause().getMessage(); + return getCause() == null + ? getSummary() + : getSummary() + "\nReason: " + getCause().getMessage(); } public enum ErrorType { diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java index 5486641d8..6e8d9ef9f 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerDefinition.java @@ -19,12 +19,10 @@ package org.apache.thrift.transport.sasl; -import javax.security.auth.callback.CallbackHandler; import java.util.Map; +import javax.security.auth.callback.CallbackHandler; -/** - * Contains all the parameters used to define a SASL server implementation. - */ +/** Contains all the parameters used to define a SASL server implementation. */ public class TSaslServerDefinition { public final String mechanism; public final String protocol; @@ -32,8 +30,12 @@ public class TSaslServerDefinition { public final Map<String, String> props; public final CallbackHandler cbh; - public TSaslServerDefinition(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { + public TSaslServerDefinition( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { this.mechanism = mechanism; this.protocol = protocol; this.serverName = serverName; diff --git a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java index 06cf534b6..ab0e24518 100644 --- a/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java +++ b/lib/java/src/main/java/org/apache/thrift/transport/sasl/TSaslServerFactory.java @@ -19,17 +19,16 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.MECHANISME_MISMATCH; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; + import java.util.HashMap; import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.MECHANISME_MISMATCH; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.PROTOCOL_ERROR; - /** * Factory to create sasl server. Users can extend this class to customize the SaslServer creation. */ @@ -41,24 +40,31 @@ public class TSaslServerFactory { this.saslMechanisms = new HashMap<>(); } - public void addSaslMechanism(String mechanism, String protocol, String serverName, - Map<String, String> props, CallbackHandler cbh) { - TSaslServerDefinition definition = new TSaslServerDefinition(mechanism, protocol, serverName, - props, cbh); + public void addSaslMechanism( + String mechanism, + String protocol, + String serverName, + Map<String, String> props, + CallbackHandler cbh) { + TSaslServerDefinition definition = + new TSaslServerDefinition(mechanism, protocol, serverName, props, cbh); saslMechanisms.put(definition.mechanism, definition); } public ServerSaslPeer getSaslPeer(String mechanism) throws TSaslNegotiationException { if (!saslMechanisms.containsKey(mechanism)) { - throw new TSaslNegotiationException(MECHANISME_MISMATCH, "Unsupported mechanism " + mechanism); + throw new TSaslNegotiationException( + MECHANISME_MISMATCH, "Unsupported mechanism " + mechanism); } TSaslServerDefinition saslDef = saslMechanisms.get(mechanism); try { - SaslServer saslServer = Sasl.createSaslServer(saslDef.mechanism, saslDef.protocol, - saslDef.serverName, saslDef.props, saslDef.cbh); + SaslServer saslServer = + Sasl.createSaslServer( + saslDef.mechanism, saslDef.protocol, saslDef.serverName, saslDef.props, saslDef.cbh); return new ServerSaslPeer(saslServer); } catch (SaslException e) { - throw new TSaslNegotiationException(PROTOCOL_ERROR, "Fail to create sasl server " + mechanism, e); + throw new TSaslNegotiationException( + PROTOCOL_ERROR, "Fail to create sasl server " + mechanism, e); } } } diff --git a/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java b/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java index b54388a5b..6cb507006 100644 --- a/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java +++ b/lib/java/src/main/java/org/apache/thrift/utils/StringUtils.java @@ -25,7 +25,9 @@ public final class StringUtils { // Utility class. } - private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + private static final char[] HEX_CHARS = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; /** * Stringify a byte array to the hex representation for each byte. @@ -56,7 +58,13 @@ public final class StringUtils { throw new IndexOutOfBoundsException("Negative start offset " + offset); } if (length > bytes.length - offset) { - throw new IndexOutOfBoundsException("Invalid range, bytes.length: " + bytes.length + " offset: " + offset + " length: " + length); + throw new IndexOutOfBoundsException( + "Invalid range, bytes.length: " + + bytes.length + + " offset: " + + offset + + " length: " + + length); } char[] chars = new char[length * 2]; for (int i = 0; i < length; i++) { diff --git a/lib/java/src/test/java/org/apache/thrift/Fixtures.java b/lib/java/src/test/java/org/apache/thrift/Fixtures.java index a8b051866..eace85322 100644 --- a/lib/java/src/test/java/org/apache/thrift/Fixtures.java +++ b/lib/java/src/test/java/org/apache/thrift/Fixtures.java @@ -25,7 +25,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; - import thrift.test.Bonk; import thrift.test.CompactProtoTestStruct; import thrift.test.HolyMoley; @@ -70,221 +69,1064 @@ public class Fixtures { // These byte arrays are serialized versions of the above structs. // They were serialized in binary protocol using thrift 0.6.x and are used to // test backwards compatibility with respect to the standard scheme. - private static final byte[] persistentBytesOneOfEach = new byte[] { (byte) 0x02, (byte) 0x00, - (byte) 0x01, (byte) 0x01, (byte) 0x02, (byte) 0x00, (byte) 0x02, - (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x03, (byte) 0xD6, - (byte) 0x06, (byte) 0x00, (byte) 0x04, (byte) 0x69, (byte) 0x78, - (byte) 0x08, (byte) 0x00, (byte) 0x05, (byte) 0x01, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x06, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x65, - (byte) 0xA0, (byte) 0xBC, (byte) 0x00, (byte) 0x04, (byte) 0x00, - (byte) 0x07, (byte) 0x40, (byte) 0x09, (byte) 0x21, (byte) 0xFB, - (byte) 0x54, (byte) 0x44, (byte) 0x2D, (byte) 0x18, (byte) 0x0B, - (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x0D, (byte) 0x4A, (byte) 0x53, (byte) 0x4F, (byte) 0x4E, - (byte) 0x20, (byte) 0x54, (byte) 0x48, (byte) 0x49, (byte) 0x53, - (byte) 0x21, (byte) 0x20, (byte) 0x22, (byte) 0x01, (byte) 0x0B, - (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x2E, (byte) 0xD3, (byte) 0x80, (byte) 0xE2, (byte) 0x85, - (byte) 0xAE, (byte) 0xCE, (byte) 0x9D, (byte) 0x20, (byte) 0xD0, - (byte) 0x9D, (byte) 0xCE, (byte) 0xBF, (byte) 0xE2, (byte) 0x85, - (byte) 0xBF, (byte) 0xD0, (byte) 0xBE, (byte) 0xC9, (byte) 0xA1, - (byte) 0xD0, (byte) 0xB3, (byte) 0xD0, (byte) 0xB0, (byte) 0xCF, - (byte) 0x81, (byte) 0xE2, (byte) 0x84, (byte) 0x8E, (byte) 0x20, - (byte) 0xCE, (byte) 0x91, (byte) 0x74, (byte) 0x74, (byte) 0xCE, - (byte) 0xB1, (byte) 0xE2, (byte) 0x85, (byte) 0xBD, (byte) 0xCE, - (byte) 0xBA, (byte) 0xEF, (byte) 0xBF, (byte) 0xBD, (byte) 0xE2, - (byte) 0x80, (byte) 0xBC, (byte) 0x02, (byte) 0x00, (byte) 0x0A, - (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x0B, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x62, (byte) 0x61, - (byte) 0x73, (byte) 0x65, (byte) 0x36, (byte) 0x34, (byte) 0x0F, - (byte) 0x00, (byte) 0x0C, (byte) 0x03, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x03, (byte) 0x01, (byte) 0x02, (byte) 0x03, - (byte) 0x0F, (byte) 0x00, (byte) 0x0D, (byte) 0x06, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x01, - (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x03, (byte) 0x0F, - (byte) 0x00, (byte) 0x0E, (byte) 0x0A, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x03, (byte) 0x00 }; - private static final byte[] persistentBytesNesting = new byte[] { (byte) 0x0C, (byte) 0x00, - (byte) 0x01, (byte) 0x08, (byte) 0x00, (byte) 0x01, (byte) 0x00, - (byte) 0x00, (byte) 0x7A, (byte) 0x69, (byte) 0x0B, (byte) 0x00, - (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x13, - (byte) 0x49, (byte) 0x20, (byte) 0x61, (byte) 0x6D, (byte) 0x20, - (byte) 0x61, (byte) 0x20, (byte) 0x62, (byte) 0x6F, (byte) 0x6E, - (byte) 0x6B, (byte) 0x2E, (byte) 0x2E, (byte) 0x2E, (byte) 0x20, - (byte) 0x78, (byte) 0x6F, (byte) 0x72, (byte) 0x21, (byte) 0x00, - (byte) 0x0C, (byte) 0x00, (byte) 0x02, (byte) 0x02, (byte) 0x00, - (byte) 0x01, (byte) 0x01, (byte) 0x02, (byte) 0x00, (byte) 0x02, - (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x03, (byte) 0xD6, - (byte) 0x06, (byte) 0x00, (byte) 0x04, (byte) 0x69, (byte) 0x78, - (byte) 0x08, (byte) 0x00, (byte) 0x05, (byte) 0x01, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x06, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x65, - (byte) 0xA0, (byte) 0xBC, (byte) 0x00, (byte) 0x04, (byte) 0x00, - (byte) 0x07, (byte) 0x40, (byte) 0x09, (byte) 0x21, (byte) 0xFB, - (byte) 0x54, (byte) 0x44, (byte) 0x2D, (byte) 0x18, (byte) 0x0B, - (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x0D, (byte) 0x4A, (byte) 0x53, (byte) 0x4F, (byte) 0x4E, - (byte) 0x20, (byte) 0x54, (byte) 0x48, (byte) 0x49, (byte) 0x53, - (byte) 0x21, (byte) 0x20, (byte) 0x22, (byte) 0x01, (byte) 0x0B, - (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x2E, (byte) 0xD3, (byte) 0x80, (byte) 0xE2, (byte) 0x85, - (byte) 0xAE, (byte) 0xCE, (byte) 0x9D, (byte) 0x20, (byte) 0xD0, - (byte) 0x9D, (byte) 0xCE, (byte) 0xBF, (byte) 0xE2, (byte) 0x85, - (byte) 0xBF, (byte) 0xD0, (byte) 0xBE, (byte) 0xC9, (byte) 0xA1, - (byte) 0xD0, (byte) 0xB3, (byte) 0xD0, (byte) 0xB0, (byte) 0xCF, - (byte) 0x81, (byte) 0xE2, (byte) 0x84, (byte) 0x8E, (byte) 0x20, - (byte) 0xCE, (byte) 0x91, (byte) 0x74, (byte) 0x74, (byte) 0xCE, - (byte) 0xB1, (byte) 0xE2, (byte) 0x85, (byte) 0xBD, (byte) 0xCE, - (byte) 0xBA, (byte) 0xEF, (byte) 0xBF, (byte) 0xBD, (byte) 0xE2, - (byte) 0x80, (byte) 0xBC, (byte) 0x02, (byte) 0x00, (byte) 0x0A, - (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x0B, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x62, (byte) 0x61, - (byte) 0x73, (byte) 0x65, (byte) 0x36, (byte) 0x34, (byte) 0x0F, - (byte) 0x00, (byte) 0x0C, (byte) 0x03, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x03, (byte) 0x01, (byte) 0x02, (byte) 0x03, - (byte) 0x0F, (byte) 0x00, (byte) 0x0D, (byte) 0x06, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x01, - (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x03, (byte) 0x0F, - (byte) 0x00, (byte) 0x0E, (byte) 0x0A, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x03, (byte) 0x00, (byte) 0x00 }; - private static final byte[] persistentBytesHolyMoley = new byte[] { (byte) 0x0F, (byte) 0x00, - (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x02, (byte) 0x02, (byte) 0x00, (byte) 0x01, (byte) 0x01, - (byte) 0x02, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x03, - (byte) 0x00, (byte) 0x03, (byte) 0x23, (byte) 0x06, (byte) 0x00, - (byte) 0x04, (byte) 0x69, (byte) 0x78, (byte) 0x08, (byte) 0x00, - (byte) 0x05, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x0A, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x01, (byte) 0x65, (byte) 0xA0, (byte) 0xBC, - (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x07, (byte) 0x40, - (byte) 0x09, (byte) 0x21, (byte) 0xFB, (byte) 0x54, (byte) 0x44, - (byte) 0x2D, (byte) 0x18, (byte) 0x0B, (byte) 0x00, (byte) 0x08, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0D, (byte) 0x4A, - (byte) 0x53, (byte) 0x4F, (byte) 0x4E, (byte) 0x20, (byte) 0x54, - (byte) 0x48, (byte) 0x49, (byte) 0x53, (byte) 0x21, (byte) 0x20, - (byte) 0x22, (byte) 0x01, (byte) 0x0B, (byte) 0x00, (byte) 0x09, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x2E, (byte) 0xD3, - (byte) 0x80, (byte) 0xE2, (byte) 0x85, (byte) 0xAE, (byte) 0xCE, - (byte) 0x9D, (byte) 0x20, (byte) 0xD0, (byte) 0x9D, (byte) 0xCE, - (byte) 0xBF, (byte) 0xE2, (byte) 0x85, (byte) 0xBF, (byte) 0xD0, - (byte) 0xBE, (byte) 0xC9, (byte) 0xA1, (byte) 0xD0, (byte) 0xB3, - (byte) 0xD0, (byte) 0xB0, (byte) 0xCF, (byte) 0x81, (byte) 0xE2, - (byte) 0x84, (byte) 0x8E, (byte) 0x20, (byte) 0xCE, (byte) 0x91, - (byte) 0x74, (byte) 0x74, (byte) 0xCE, (byte) 0xB1, (byte) 0xE2, - (byte) 0x85, (byte) 0xBD, (byte) 0xCE, (byte) 0xBA, (byte) 0xEF, - (byte) 0xBF, (byte) 0xBD, (byte) 0xE2, (byte) 0x80, (byte) 0xBC, - (byte) 0x02, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x0B, - (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x06, (byte) 0x62, (byte) 0x61, (byte) 0x73, (byte) 0x65, - (byte) 0x36, (byte) 0x34, (byte) 0x0F, (byte) 0x00, (byte) 0x0C, - (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, - (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x0F, (byte) 0x00, - (byte) 0x0D, (byte) 0x06, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x03, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x02, - (byte) 0x00, (byte) 0x03, (byte) 0x0F, (byte) 0x00, (byte) 0x0E, - (byte) 0x0A, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, - (byte) 0x02, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x02, - (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x03, (byte) 0x00, - (byte) 0x03, (byte) 0xD6, (byte) 0x06, (byte) 0x00, (byte) 0x04, - (byte) 0x69, (byte) 0x78, (byte) 0x08, (byte) 0x00, (byte) 0x05, - (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0A, - (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x01, (byte) 0x65, (byte) 0xA0, (byte) 0xBC, (byte) 0x00, - (byte) 0x04, (byte) 0x00, (byte) 0x07, (byte) 0x40, (byte) 0x09, - (byte) 0x21, (byte) 0xFB, (byte) 0x54, (byte) 0x44, (byte) 0x2D, - (byte) 0x18, (byte) 0x0B, (byte) 0x00, (byte) 0x08, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x0D, (byte) 0x4A, (byte) 0x53, - (byte) 0x4F, (byte) 0x4E, (byte) 0x20, (byte) 0x54, (byte) 0x48, - (byte) 0x49, (byte) 0x53, (byte) 0x21, (byte) 0x20, (byte) 0x22, - (byte) 0x01, (byte) 0x0B, (byte) 0x00, (byte) 0x09, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x2E, (byte) 0xD3, (byte) 0x80, - (byte) 0xE2, (byte) 0x85, (byte) 0xAE, (byte) 0xCE, (byte) 0x9D, - (byte) 0x20, (byte) 0xD0, (byte) 0x9D, (byte) 0xCE, (byte) 0xBF, - (byte) 0xE2, (byte) 0x85, (byte) 0xBF, (byte) 0xD0, (byte) 0xBE, - (byte) 0xC9, (byte) 0xA1, (byte) 0xD0, (byte) 0xB3, (byte) 0xD0, - (byte) 0xB0, (byte) 0xCF, (byte) 0x81, (byte) 0xE2, (byte) 0x84, - (byte) 0x8E, (byte) 0x20, (byte) 0xCE, (byte) 0x91, (byte) 0x74, - (byte) 0x74, (byte) 0xCE, (byte) 0xB1, (byte) 0xE2, (byte) 0x85, - (byte) 0xBD, (byte) 0xCE, (byte) 0xBA, (byte) 0xEF, (byte) 0xBF, - (byte) 0xBD, (byte) 0xE2, (byte) 0x80, (byte) 0xBC, (byte) 0x02, - (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x0B, (byte) 0x00, - (byte) 0x0B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, - (byte) 0x62, (byte) 0x61, (byte) 0x73, (byte) 0x65, (byte) 0x36, - (byte) 0x34, (byte) 0x0F, (byte) 0x00, (byte) 0x0C, (byte) 0x03, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x01, - (byte) 0x02, (byte) 0x03, (byte) 0x0F, (byte) 0x00, (byte) 0x0D, - (byte) 0x06, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, - (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x02, (byte) 0x00, - (byte) 0x03, (byte) 0x0F, (byte) 0x00, (byte) 0x0E, (byte) 0x0A, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x0E, - (byte) 0x00, (byte) 0x02, (byte) 0x0F, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x03, (byte) 0x0B, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x0F, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x6E, - (byte) 0x20, (byte) 0x61, (byte) 0x20, (byte) 0x6F, (byte) 0x6E, - (byte) 0x65, (byte) 0x2C, (byte) 0x20, (byte) 0x74, (byte) 0x77, - (byte) 0x6F, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, - (byte) 0x74, (byte) 0x68, (byte) 0x72, (byte) 0x65, (byte) 0x65, - (byte) 0x21, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, - (byte) 0x46, (byte) 0x4F, (byte) 0x55, (byte) 0x52, (byte) 0x21, - (byte) 0x21, (byte) 0x0B, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x09, - (byte) 0x61, (byte) 0x6E, (byte) 0x64, (byte) 0x20, (byte) 0x61, - (byte) 0x20, (byte) 0x6F, (byte) 0x6E, (byte) 0x65, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x09, (byte) 0x61, (byte) 0x6E, - (byte) 0x64, (byte) 0x20, (byte) 0x61, (byte) 0x20, (byte) 0x74, - (byte) 0x77, (byte) 0x6F, (byte) 0x0D, (byte) 0x00, (byte) 0x03, - (byte) 0x0B, (byte) 0x0F, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, - (byte) 0x74, (byte) 0x77, (byte) 0x6F, (byte) 0x0C, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x08, (byte) 0x00, - (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, - (byte) 0x0B, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x05, (byte) 0x57, (byte) 0x61, (byte) 0x69, - (byte) 0x74, (byte) 0x2E, (byte) 0x00, (byte) 0x08, (byte) 0x00, - (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, - (byte) 0x0B, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x05, (byte) 0x57, (byte) 0x68, (byte) 0x61, - (byte) 0x74, (byte) 0x3F, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x05, (byte) 0x74, (byte) 0x68, (byte) 0x72, - (byte) 0x65, (byte) 0x65, (byte) 0x0C, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x04, (byte) 0x7A, (byte) 0x65, (byte) 0x72, (byte) 0x6F, - (byte) 0x0C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00 }; + private static final byte[] persistentBytesOneOfEach = + new byte[] { + (byte) 0x02, + (byte) 0x00, + (byte) 0x01, + (byte) 0x01, + (byte) 0x02, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x03, + (byte) 0xD6, + (byte) 0x06, + (byte) 0x00, + (byte) 0x04, + (byte) 0x69, + (byte) 0x78, + (byte) 0x08, + (byte) 0x00, + (byte) 0x05, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x65, + (byte) 0xA0, + (byte) 0xBC, + (byte) 0x00, + (byte) 0x04, + (byte) 0x00, + (byte) 0x07, + (byte) 0x40, + (byte) 0x09, + (byte) 0x21, + (byte) 0xFB, + (byte) 0x54, + (byte) 0x44, + (byte) 0x2D, + (byte) 0x18, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x08, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x4A, + (byte) 0x53, + (byte) 0x4F, + (byte) 0x4E, + (byte) 0x20, + (byte) 0x54, + (byte) 0x48, + (byte) 0x49, + (byte) 0x53, + (byte) 0x21, + (byte) 0x20, + (byte) 0x22, + (byte) 0x01, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x09, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x2E, + (byte) 0xD3, + (byte) 0x80, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xAE, + (byte) 0xCE, + (byte) 0x9D, + (byte) 0x20, + (byte) 0xD0, + (byte) 0x9D, + (byte) 0xCE, + (byte) 0xBF, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBF, + (byte) 0xD0, + (byte) 0xBE, + (byte) 0xC9, + (byte) 0xA1, + (byte) 0xD0, + (byte) 0xB3, + (byte) 0xD0, + (byte) 0xB0, + (byte) 0xCF, + (byte) 0x81, + (byte) 0xE2, + (byte) 0x84, + (byte) 0x8E, + (byte) 0x20, + (byte) 0xCE, + (byte) 0x91, + (byte) 0x74, + (byte) 0x74, + (byte) 0xCE, + (byte) 0xB1, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBD, + (byte) 0xCE, + (byte) 0xBA, + (byte) 0xEF, + (byte) 0xBF, + (byte) 0xBD, + (byte) 0xE2, + (byte) 0x80, + (byte) 0xBC, + (byte) 0x02, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x06, + (byte) 0x62, + (byte) 0x61, + (byte) 0x73, + (byte) 0x65, + (byte) 0x36, + (byte) 0x34, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0C, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x01, + (byte) 0x02, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0E, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00 + }; + private static final byte[] persistentBytesNesting = + new byte[] { + (byte) 0x0C, + (byte) 0x00, + (byte) 0x01, + (byte) 0x08, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x7A, + (byte) 0x69, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x13, + (byte) 0x49, + (byte) 0x20, + (byte) 0x61, + (byte) 0x6D, + (byte) 0x20, + (byte) 0x61, + (byte) 0x20, + (byte) 0x62, + (byte) 0x6F, + (byte) 0x6E, + (byte) 0x6B, + (byte) 0x2E, + (byte) 0x2E, + (byte) 0x2E, + (byte) 0x20, + (byte) 0x78, + (byte) 0x6F, + (byte) 0x72, + (byte) 0x21, + (byte) 0x00, + (byte) 0x0C, + (byte) 0x00, + (byte) 0x02, + (byte) 0x02, + (byte) 0x00, + (byte) 0x01, + (byte) 0x01, + (byte) 0x02, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x03, + (byte) 0xD6, + (byte) 0x06, + (byte) 0x00, + (byte) 0x04, + (byte) 0x69, + (byte) 0x78, + (byte) 0x08, + (byte) 0x00, + (byte) 0x05, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x65, + (byte) 0xA0, + (byte) 0xBC, + (byte) 0x00, + (byte) 0x04, + (byte) 0x00, + (byte) 0x07, + (byte) 0x40, + (byte) 0x09, + (byte) 0x21, + (byte) 0xFB, + (byte) 0x54, + (byte) 0x44, + (byte) 0x2D, + (byte) 0x18, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x08, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x4A, + (byte) 0x53, + (byte) 0x4F, + (byte) 0x4E, + (byte) 0x20, + (byte) 0x54, + (byte) 0x48, + (byte) 0x49, + (byte) 0x53, + (byte) 0x21, + (byte) 0x20, + (byte) 0x22, + (byte) 0x01, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x09, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x2E, + (byte) 0xD3, + (byte) 0x80, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xAE, + (byte) 0xCE, + (byte) 0x9D, + (byte) 0x20, + (byte) 0xD0, + (byte) 0x9D, + (byte) 0xCE, + (byte) 0xBF, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBF, + (byte) 0xD0, + (byte) 0xBE, + (byte) 0xC9, + (byte) 0xA1, + (byte) 0xD0, + (byte) 0xB3, + (byte) 0xD0, + (byte) 0xB0, + (byte) 0xCF, + (byte) 0x81, + (byte) 0xE2, + (byte) 0x84, + (byte) 0x8E, + (byte) 0x20, + (byte) 0xCE, + (byte) 0x91, + (byte) 0x74, + (byte) 0x74, + (byte) 0xCE, + (byte) 0xB1, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBD, + (byte) 0xCE, + (byte) 0xBA, + (byte) 0xEF, + (byte) 0xBF, + (byte) 0xBD, + (byte) 0xE2, + (byte) 0x80, + (byte) 0xBC, + (byte) 0x02, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x06, + (byte) 0x62, + (byte) 0x61, + (byte) 0x73, + (byte) 0x65, + (byte) 0x36, + (byte) 0x34, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0C, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x01, + (byte) 0x02, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0E, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00 + }; + private static final byte[] persistentBytesHolyMoley = + new byte[] { + (byte) 0x0F, + (byte) 0x00, + (byte) 0x01, + (byte) 0x0C, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x02, + (byte) 0x00, + (byte) 0x01, + (byte) 0x01, + (byte) 0x02, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x03, + (byte) 0x23, + (byte) 0x06, + (byte) 0x00, + (byte) 0x04, + (byte) 0x69, + (byte) 0x78, + (byte) 0x08, + (byte) 0x00, + (byte) 0x05, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x65, + (byte) 0xA0, + (byte) 0xBC, + (byte) 0x00, + (byte) 0x04, + (byte) 0x00, + (byte) 0x07, + (byte) 0x40, + (byte) 0x09, + (byte) 0x21, + (byte) 0xFB, + (byte) 0x54, + (byte) 0x44, + (byte) 0x2D, + (byte) 0x18, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x08, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x4A, + (byte) 0x53, + (byte) 0x4F, + (byte) 0x4E, + (byte) 0x20, + (byte) 0x54, + (byte) 0x48, + (byte) 0x49, + (byte) 0x53, + (byte) 0x21, + (byte) 0x20, + (byte) 0x22, + (byte) 0x01, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x09, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x2E, + (byte) 0xD3, + (byte) 0x80, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xAE, + (byte) 0xCE, + (byte) 0x9D, + (byte) 0x20, + (byte) 0xD0, + (byte) 0x9D, + (byte) 0xCE, + (byte) 0xBF, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBF, + (byte) 0xD0, + (byte) 0xBE, + (byte) 0xC9, + (byte) 0xA1, + (byte) 0xD0, + (byte) 0xB3, + (byte) 0xD0, + (byte) 0xB0, + (byte) 0xCF, + (byte) 0x81, + (byte) 0xE2, + (byte) 0x84, + (byte) 0x8E, + (byte) 0x20, + (byte) 0xCE, + (byte) 0x91, + (byte) 0x74, + (byte) 0x74, + (byte) 0xCE, + (byte) 0xB1, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBD, + (byte) 0xCE, + (byte) 0xBA, + (byte) 0xEF, + (byte) 0xBF, + (byte) 0xBD, + (byte) 0xE2, + (byte) 0x80, + (byte) 0xBC, + (byte) 0x02, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x06, + (byte) 0x62, + (byte) 0x61, + (byte) 0x73, + (byte) 0x65, + (byte) 0x36, + (byte) 0x34, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0C, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x01, + (byte) 0x02, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0E, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x01, + (byte) 0x01, + (byte) 0x02, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x03, + (byte) 0xD6, + (byte) 0x06, + (byte) 0x00, + (byte) 0x04, + (byte) 0x69, + (byte) 0x78, + (byte) 0x08, + (byte) 0x00, + (byte) 0x05, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x65, + (byte) 0xA0, + (byte) 0xBC, + (byte) 0x00, + (byte) 0x04, + (byte) 0x00, + (byte) 0x07, + (byte) 0x40, + (byte) 0x09, + (byte) 0x21, + (byte) 0xFB, + (byte) 0x54, + (byte) 0x44, + (byte) 0x2D, + (byte) 0x18, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x08, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x4A, + (byte) 0x53, + (byte) 0x4F, + (byte) 0x4E, + (byte) 0x20, + (byte) 0x54, + (byte) 0x48, + (byte) 0x49, + (byte) 0x53, + (byte) 0x21, + (byte) 0x20, + (byte) 0x22, + (byte) 0x01, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x09, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x2E, + (byte) 0xD3, + (byte) 0x80, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xAE, + (byte) 0xCE, + (byte) 0x9D, + (byte) 0x20, + (byte) 0xD0, + (byte) 0x9D, + (byte) 0xCE, + (byte) 0xBF, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBF, + (byte) 0xD0, + (byte) 0xBE, + (byte) 0xC9, + (byte) 0xA1, + (byte) 0xD0, + (byte) 0xB3, + (byte) 0xD0, + (byte) 0xB0, + (byte) 0xCF, + (byte) 0x81, + (byte) 0xE2, + (byte) 0x84, + (byte) 0x8E, + (byte) 0x20, + (byte) 0xCE, + (byte) 0x91, + (byte) 0x74, + (byte) 0x74, + (byte) 0xCE, + (byte) 0xB1, + (byte) 0xE2, + (byte) 0x85, + (byte) 0xBD, + (byte) 0xCE, + (byte) 0xBA, + (byte) 0xEF, + (byte) 0xBF, + (byte) 0xBD, + (byte) 0xE2, + (byte) 0x80, + (byte) 0xBC, + (byte) 0x02, + (byte) 0x00, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x06, + (byte) 0x62, + (byte) 0x61, + (byte) 0x73, + (byte) 0x65, + (byte) 0x36, + (byte) 0x34, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0C, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x01, + (byte) 0x02, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0D, + (byte) 0x06, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x03, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x0E, + (byte) 0x0A, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x0E, + (byte) 0x00, + (byte) 0x02, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x0F, + (byte) 0x74, + (byte) 0x68, + (byte) 0x65, + (byte) 0x6E, + (byte) 0x20, + (byte) 0x61, + (byte) 0x20, + (byte) 0x6F, + (byte) 0x6E, + (byte) 0x65, + (byte) 0x2C, + (byte) 0x20, + (byte) 0x74, + (byte) 0x77, + (byte) 0x6F, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x06, + (byte) 0x74, + (byte) 0x68, + (byte) 0x72, + (byte) 0x65, + (byte) 0x65, + (byte) 0x21, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x06, + (byte) 0x46, + (byte) 0x4F, + (byte) 0x55, + (byte) 0x52, + (byte) 0x21, + (byte) 0x21, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x09, + (byte) 0x61, + (byte) 0x6E, + (byte) 0x64, + (byte) 0x20, + (byte) 0x61, + (byte) 0x20, + (byte) 0x6F, + (byte) 0x6E, + (byte) 0x65, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x09, + (byte) 0x61, + (byte) 0x6E, + (byte) 0x64, + (byte) 0x20, + (byte) 0x61, + (byte) 0x20, + (byte) 0x74, + (byte) 0x77, + (byte) 0x6F, + (byte) 0x0D, + (byte) 0x00, + (byte) 0x03, + (byte) 0x0B, + (byte) 0x0F, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x03, + (byte) 0x74, + (byte) 0x77, + (byte) 0x6F, + (byte) 0x0C, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x08, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x01, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x05, + (byte) 0x57, + (byte) 0x61, + (byte) 0x69, + (byte) 0x74, + (byte) 0x2E, + (byte) 0x00, + (byte) 0x08, + (byte) 0x00, + (byte) 0x01, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x02, + (byte) 0x0B, + (byte) 0x00, + (byte) 0x02, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x05, + (byte) 0x57, + (byte) 0x68, + (byte) 0x61, + (byte) 0x74, + (byte) 0x3F, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x05, + (byte) 0x74, + (byte) 0x68, + (byte) 0x72, + (byte) 0x65, + (byte) 0x65, + (byte) 0x0C, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x04, + (byte) 0x7A, + (byte) 0x65, + (byte) 0x72, + (byte) 0x6F, + (byte) 0x0C, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00 + }; - private static final byte[] kUnicodeBytes = { (byte) 0xd3, (byte) 0x80, - (byte) 0xe2, (byte) 0x85, (byte) 0xae, (byte) 0xce, (byte) 0x9d, - (byte) 0x20, (byte) 0xd0, (byte) 0x9d, (byte) 0xce, (byte) 0xbf, - (byte) 0xe2, (byte) 0x85, (byte) 0xbf, (byte) 0xd0, (byte) 0xbe, - (byte) 0xc9, (byte) 0xa1, (byte) 0xd0, (byte) 0xb3, (byte) 0xd0, - (byte) 0xb0, (byte) 0xcf, (byte) 0x81, (byte) 0xe2, (byte) 0x84, - (byte) 0x8e, (byte) 0x20, (byte) 0xce, (byte) 0x91, (byte) 0x74, - (byte) 0x74, (byte) 0xce, (byte) 0xb1, (byte) 0xe2, (byte) 0x85, - (byte) 0xbd, (byte) 0xce, (byte) 0xba, (byte) 0x83, (byte) 0xe2, - (byte) 0x80, (byte) 0xbc }; + private static final byte[] kUnicodeBytes = { + (byte) 0xd3, + (byte) 0x80, + (byte) 0xe2, + (byte) 0x85, + (byte) 0xae, + (byte) 0xce, + (byte) 0x9d, + (byte) 0x20, + (byte) 0xd0, + (byte) 0x9d, + (byte) 0xce, + (byte) 0xbf, + (byte) 0xe2, + (byte) 0x85, + (byte) 0xbf, + (byte) 0xd0, + (byte) 0xbe, + (byte) 0xc9, + (byte) 0xa1, + (byte) 0xd0, + (byte) 0xb3, + (byte) 0xd0, + (byte) 0xb0, + (byte) 0xcf, + (byte) 0x81, + (byte) 0xe2, + (byte) 0x84, + (byte) 0x8e, + (byte) 0x20, + (byte) 0xce, + (byte) 0x91, + (byte) 0x74, + (byte) 0x74, + (byte) 0xce, + (byte) 0xb1, + (byte) 0xe2, + (byte) 0x85, + (byte) 0xbd, + (byte) 0xce, + (byte) 0xba, + (byte) 0x83, + (byte) 0xe2, + (byte) 0x80, + (byte) 0xbc + }; static { try { @@ -358,10 +1200,9 @@ public class Fixtures { holyMoley.getBonks().put("three", stage2); // superhuge compact proto test struct - compactProtoTestStruct = new CompactProtoTestStruct( - thrift.test.DebugProtoTestConstants.COMPACT_TEST); - compactProtoTestStruct.setA_binary(ByteBuffer.wrap(new byte[] { 0, 1, 2, - 3, 4, 5, 6, 7, 8 })); + compactProtoTestStruct = + new CompactProtoTestStruct(thrift.test.DebugProtoTestConstants.COMPACT_TEST); + compactProtoTestStruct.setA_binary(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8})); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/lib/java/src/test/java/org/apache/thrift/TestAnnotationMetadata.java b/lib/java/src/test/java/org/apache/thrift/TestAnnotationMetadata.java index 83be6b95d..c40c49b90 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestAnnotationMetadata.java +++ b/lib/java/src/test/java/org/apache/thrift/TestAnnotationMetadata.java @@ -19,44 +19,51 @@ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Collections; import java.util.HashMap; import java.util.Map; - import org.apache.thrift.meta_data.FieldMetaData; import org.junit.jupiter.api.Test; import thrift.test.OneOfEachBeans; import thrift.test.annotations.OneOfEachBeansWithAnnotations; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class TestAnnotationMetadata { - @Test - public void testWithoutParamShouldGenerateEmpty() { - Map<? extends TFieldIdEnum, FieldMetaData> structMetaDataMap = FieldMetaData.getStructMetaDataMap(OneOfEachBeans.class); - { - Map<String, String> metadata = structMetaDataMap.get(OneOfEachBeans._Fields.I16_LIST).getFieldAnnotations(); - assertEquals(Collections.emptyMap(), metadata); - } - { - Map<String, String> metadata = structMetaDataMap.get(OneOfEachBeans._Fields.A_BITE).getFieldAnnotations(); - assertEquals(Collections.emptyMap(), metadata); - } + @Test + public void testWithoutParamShouldGenerateEmpty() { + Map<? extends TFieldIdEnum, FieldMetaData> structMetaDataMap = + FieldMetaData.getStructMetaDataMap(OneOfEachBeans.class); + { + Map<String, String> metadata = + structMetaDataMap.get(OneOfEachBeans._Fields.I16_LIST).getFieldAnnotations(); + assertEquals(Collections.emptyMap(), metadata); + } + { + Map<String, String> metadata = + structMetaDataMap.get(OneOfEachBeans._Fields.A_BITE).getFieldAnnotations(); + assertEquals(Collections.emptyMap(), metadata); } + } - @Test - public void testGeneratedAnnotations() { - Map<? extends TFieldIdEnum, FieldMetaData> structMetaDataMap = FieldMetaData.getStructMetaDataMap(OneOfEachBeansWithAnnotations.class); - { - Map<String, String> metadata = structMetaDataMap.get(OneOfEachBeansWithAnnotations._Fields.I16_LIST).getFieldAnnotations(); - assertEquals(Collections.emptyMap(), metadata); - } - { - Map<String, String> metadata = structMetaDataMap.get(OneOfEachBeansWithAnnotations._Fields.A_BITE).getFieldAnnotations(); - Map<String, String> expected = new HashMap<>(); - expected.put("compression", "false"); - assertEquals(expected, metadata); - } + @Test + public void testGeneratedAnnotations() { + Map<? extends TFieldIdEnum, FieldMetaData> structMetaDataMap = + FieldMetaData.getStructMetaDataMap(OneOfEachBeansWithAnnotations.class); + { + Map<String, String> metadata = + structMetaDataMap + .get(OneOfEachBeansWithAnnotations._Fields.I16_LIST) + .getFieldAnnotations(); + assertEquals(Collections.emptyMap(), metadata); + } + { + Map<String, String> metadata = + structMetaDataMap.get(OneOfEachBeansWithAnnotations._Fields.A_BITE).getFieldAnnotations(); + Map<String, String> expected = new HashMap<>(); + expected.put("compression", "false"); + assertEquals(expected, metadata); } + } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java b/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java index 8fd9a97c9..7f243b3fc 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java +++ b/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java @@ -1,12 +1,12 @@ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertNotSame; + import org.junit.jupiter.api.Test; import thrift.test.DeepCopyBar; import thrift.test.DeepCopyFoo; -import static org.junit.jupiter.api.Assertions.assertNotSame; - -public class TestDeepCopy { +public class TestDeepCopy { @Test public void testDeepCopy() throws Exception { @@ -26,12 +26,16 @@ public class TestDeepCopy { assertNotSame(foo.getBar(), deepCopyFoo.getBar()); - assertNotSame(foo.getL().get(0), deepCopyFoo.getL().get(0)); - assertNotSame(foo.getS().toArray(new DeepCopyBar[0])[0], deepCopyFoo.getS().toArray(new DeepCopyBar[0])[0]); - assertNotSame(foo.getM().get("test 3"), deepCopyFoo.getM().get("test 3")); - - assertNotSame(foo.getLi().get(0), deepCopyFoo.getLi().get(0)); - assertNotSame(foo.getSi().toArray(new thrift.test.Object[0])[0], deepCopyFoo.getSi().toArray(new thrift.test.Object[0])[0]); - assertNotSame(foo.getMi().get("test 3"), deepCopyFoo.getMi().get("test 3")); + assertNotSame(foo.getL().get(0), deepCopyFoo.getL().get(0)); + assertNotSame( + foo.getS().toArray(new DeepCopyBar[0])[0], + deepCopyFoo.getS().toArray(new DeepCopyBar[0])[0]); + assertNotSame(foo.getM().get("test 3"), deepCopyFoo.getM().get("test 3")); + + assertNotSame(foo.getLi().get(0), deepCopyFoo.getLi().get(0)); + assertNotSame( + foo.getSi().toArray(new thrift.test.Object[0])[0], + deepCopyFoo.getSi().toArray(new thrift.test.Object[0])[0]); + assertNotSame(foo.getMi().get("test 3"), deepCopyFoo.getMi().get("test 3")); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java b/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java index b7b291396..5e3a9938d 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java +++ b/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java @@ -19,70 +19,70 @@ package org.apache.thrift; -import org.junit.jupiter.api.Test; -import thrift.test.enumcontainers.EnumContainersTestConstants; -import thrift.test.enumcontainers.GodBean; -import thrift.test.enumcontainers.GreekGodGoddess; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; +import org.junit.jupiter.api.Test; +import thrift.test.enumcontainers.EnumContainersTestConstants; +import thrift.test.enumcontainers.GodBean; +import thrift.test.enumcontainers.GreekGodGoddess; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class TestEnumContainers { +public class TestEnumContainers { - @Test - public void testEnumContainers() throws Exception { - final GodBean b1 = new GodBean(); - b1.addToGoddess(GreekGodGoddess.HERA); - b1.getGoddess().add(GreekGodGoddess.APHRODITE); - b1.putToPower(GreekGodGoddess.ZEUS, 1000); - b1.getPower().put(GreekGodGoddess.HERA, 333); - b1.putToByAlias("Mr. Z", GreekGodGoddess.ZEUS); - b1.addToImages("Baths of Aphrodite 01.jpeg"); + @Test + public void testEnumContainers() throws Exception { + final GodBean b1 = new GodBean(); + b1.addToGoddess(GreekGodGoddess.HERA); + b1.getGoddess().add(GreekGodGoddess.APHRODITE); + b1.putToPower(GreekGodGoddess.ZEUS, 1000); + b1.getPower().put(GreekGodGoddess.HERA, 333); + b1.putToByAlias("Mr. Z", GreekGodGoddess.ZEUS); + b1.addToImages("Baths of Aphrodite 01.jpeg"); - final GodBean b2 = new GodBean(b1); + final GodBean b2 = new GodBean(b1); - final GodBean b3 = new GodBean(); - { - final TSerializer serializer = new TSerializer(); - final TDeserializer deserializer = new TDeserializer(); + final GodBean b3 = new GodBean(); + { + final TSerializer serializer = new TSerializer(); + final TDeserializer deserializer = new TDeserializer(); - final byte[] bytes = serializer.serialize(b1); - deserializer.deserialize(b3, bytes); - } + final byte[] bytes = serializer.serialize(b1); + deserializer.deserialize(b3, bytes); + } - assertNotSame(b1.getGoddess(), b2.getGoddess()); - assertNotSame(b1.getPower(), b2.getPower()); + assertNotSame(b1.getGoddess(), b2.getGoddess()); + assertNotSame(b1.getPower(), b2.getPower()); - assertNotSame(b1.getGoddess(), b3.getGoddess()); - assertNotSame(b1.getPower(), b3.getPower()); + assertNotSame(b1.getGoddess(), b3.getGoddess()); + assertNotSame(b1.getPower(), b3.getPower()); - for (GodBean each : new GodBean[]{b1, b2, b3}) { - assertTrue(each.getGoddess().contains(GreekGodGoddess.HERA)); - assertFalse(each.getGoddess().contains(GreekGodGoddess.POSEIDON)); - assertTrue(each.getGoddess() instanceof EnumSet); + for (GodBean each : new GodBean[] {b1, b2, b3}) { + assertTrue(each.getGoddess().contains(GreekGodGoddess.HERA)); + assertFalse(each.getGoddess().contains(GreekGodGoddess.POSEIDON)); + assertTrue(each.getGoddess() instanceof EnumSet); - assertEquals(Integer.valueOf(1000), each.getPower().get(GreekGodGoddess.ZEUS)); - assertEquals(Integer.valueOf(333), each.getPower().get(GreekGodGoddess.HERA)); - assertTrue(each.getPower() instanceof EnumMap); + assertEquals(Integer.valueOf(1000), each.getPower().get(GreekGodGoddess.ZEUS)); + assertEquals(Integer.valueOf(333), each.getPower().get(GreekGodGoddess.HERA)); + assertTrue(each.getPower() instanceof EnumMap); - assertTrue(each.getByAlias() instanceof HashMap); - assertTrue(each.getImages() instanceof HashSet); - } + assertTrue(each.getByAlias() instanceof HashMap); + assertTrue(each.getImages() instanceof HashSet); } + } - @Test - public void testEnumConstants() { - assertEquals("lightning bolt", EnumContainersTestConstants.ATTRIBUTES.get(GreekGodGoddess.ZEUS)); - assertTrue(EnumContainersTestConstants.ATTRIBUTES instanceof EnumMap); + @Test + public void testEnumConstants() { + assertEquals( + "lightning bolt", EnumContainersTestConstants.ATTRIBUTES.get(GreekGodGoddess.ZEUS)); + assertTrue(EnumContainersTestConstants.ATTRIBUTES instanceof EnumMap); - assertTrue(EnumContainersTestConstants.BEAUTY.contains(GreekGodGoddess.APHRODITE)); - assertTrue(EnumContainersTestConstants.BEAUTY instanceof EnumSet); - } + assertTrue(EnumContainersTestConstants.BEAUTY.contains(GreekGodGoddess.APHRODITE)); + assertTrue(EnumContainersTestConstants.BEAUTY instanceof EnumSet); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java b/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java index 45662045d..008195c04 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java +++ b/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java @@ -19,21 +19,21 @@ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.thrift.protocol.TBinaryProtocol; import org.junit.jupiter.api.Test; import thrift.test.fullcamel.OneOfEachZZ; import thrift.test.fullcamel.UnderscoreSrv; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - // Sanity check for the code generated by 'fullcamel'. // -public class TestFullCamel { +public class TestFullCamel { @Test public void testCamelCaseSyntax() throws Exception { - TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); OneOfEachZZ obj = new OneOfEachZZ(); @@ -47,13 +47,13 @@ public class TestFullCamel { @Test public void testCamelCaseRpcMethods() throws Exception { - final UnderscoreSrv.Iface srv = new UnderscoreSrv.Iface() { - @Override - public long someRpcCall(String message) { - return 1l; - } - }; + final UnderscoreSrv.Iface srv = + new UnderscoreSrv.Iface() { + @Override + public long someRpcCall(String message) { + return 1l; + } + }; assertTrue(1l == srv.someRpcCall("test")); } } - diff --git a/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java b/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java index 7b00cca2a..efd1882bf 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java +++ b/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java @@ -19,18 +19,18 @@ package org.apache.thrift; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.protocol.TProtocol; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import org.apache.thrift.protocol.TMessage; +import org.apache.thrift.protocol.TMessageType; +import org.apache.thrift.protocol.TProtocol; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + public class TestMultiplexedProcessor { private TMultiplexedProcessor mp; private TProtocol iprot; @@ -45,22 +45,22 @@ public class TestMultiplexedProcessor { @Test public void testWrongMessageType() throws TException { - when (iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.REPLY, 42)); - assertThrows(TException.class, ()->mp.process(iprot, oprot)); + when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.REPLY, 42)); + assertThrows(TException.class, () -> mp.process(iprot, oprot)); } @Test public void testNoSuchService() throws TException { when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.CALL, 42)); - assertThrows(TException.class, ()->mp.process(iprot, oprot)); + assertThrows(TException.class, () -> mp.process(iprot, oprot)); } static class StubProcessor implements TProcessor { @Override public void process(TProtocol in, TProtocol out) throws TException { TMessage msg = in.readMessageBegin(); - if (!"func".equals(msg.name) || msg.type!=TMessageType.CALL || msg.seqid!=42) { + if (!"func".equals(msg.name) || msg.type != TMessageType.CALL || msg.seqid != 42) { throw new TException("incorrect parameters"); } out.writeMessageBegin(new TMessage("func", TMessageType.REPLY, 42)); @@ -82,5 +82,4 @@ public class TestMultiplexedProcessor { mp.process(iprot, oprot); verify(oprot).writeMessageBegin(any(TMessage.class)); } - } diff --git a/lib/java/src/test/java/org/apache/thrift/TestOptionType.java b/lib/java/src/test/java/org/apache/thrift/TestOptionType.java index 6365203af..e0ac9cb39 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestOptionType.java +++ b/lib/java/src/test/java/org/apache/thrift/TestOptionType.java @@ -19,49 +19,49 @@ package org.apache.thrift; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + // Tests and documents behavior for the "Option<T>" type -public class TestOptionType { - @Test - public void testSome() { - String name = "Chuck Norris"; - Option<String> option = Option.fromNullable(name); +public class TestOptionType { + @Test + public void testSome() { + String name = "Chuck Norris"; + Option<String> option = Option.fromNullable(name); - assertTrue(option instanceof Option.Some); - assertTrue(option.isDefined()); - assertEquals("Some(Chuck Norris)", option.toString()); - assertEquals(option.or("default value"), "Chuck Norris"); - assertEquals(option.get(),"Chuck Norris"); - } + assertTrue(option instanceof Option.Some); + assertTrue(option.isDefined()); + assertEquals("Some(Chuck Norris)", option.toString()); + assertEquals(option.or("default value"), "Chuck Norris"); + assertEquals(option.get(), "Chuck Norris"); + } - @Test - public void testNone() throws Exception { - String name = null; - Option<String> option = Option.fromNullable(name); + @Test + public void testNone() throws Exception { + String name = null; + Option<String> option = Option.fromNullable(name); - assertTrue(option instanceof Option.None); - assertFalse(option.isDefined()); - assertEquals("None", option.toString()); - assertEquals(option.or("default value"), "default value"); - // Expect exception - assertThrows(IllegalStateException.class, option::get); - } + assertTrue(option instanceof Option.None); + assertFalse(option.isDefined()); + assertEquals("None", option.toString()); + assertEquals(option.or("default value"), "default value"); + // Expect exception + assertThrows(IllegalStateException.class, option::get); + } - @Test - public void testMakeSome() throws Exception { - Option<String> some = Option.some("wee"); - assertTrue(some.isDefined()); - } + @Test + public void testMakeSome() throws Exception { + Option<String> some = Option.some("wee"); + assertTrue(some.isDefined()); + } - @Test - public void testMakeNone() throws Exception { - Option<Integer> none = Option.none(); - assertFalse(none.isDefined()); - } + @Test + public void testMakeNone() throws Exception { + Option<Integer> none = Option.none(); + assertFalse(none.isDefined()); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestOptionals.java b/lib/java/src/test/java/org/apache/thrift/TestOptionals.java index 38322eeee..5d83a1b9d 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestOptionals.java +++ b/lib/java/src/test/java/org/apache/thrift/TestOptionals.java @@ -19,27 +19,27 @@ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; import thrift.test.Opt30; import thrift.test.Opt4; import thrift.test.Opt64; import thrift.test.Opt80; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - // Exercises the isSet methods using structs from ManyOptionals.thrift -public class TestOptionals { +public class TestOptionals { @Test public void testEncodingUtils() throws Exception { - assertEquals((short)0x8, EncodingUtils.setBit((short)0, 3, true)); - assertEquals((short)0, EncodingUtils.setBit((short)0x8, 3, false)); + assertEquals((short) 0x8, EncodingUtils.setBit((short) 0, 3, true)); + assertEquals((short) 0, EncodingUtils.setBit((short) 0x8, 3, false)); assertTrue(EncodingUtils.testBit((short) 0x8, 3)); assertFalse(EncodingUtils.testBit((short) 0x8, 4)); - assertEquals(Short.MIN_VALUE, EncodingUtils.setBit((short)0, 15, true)); - assertEquals((short)0, EncodingUtils.setBit(Short.MIN_VALUE, 15, false)); + assertEquals(Short.MIN_VALUE, EncodingUtils.setBit((short) 0, 15, true)); + assertEquals((short) 0, EncodingUtils.setBit(Short.MIN_VALUE, 15, false)); assertTrue(EncodingUtils.testBit(Short.MIN_VALUE, 15)); assertFalse(EncodingUtils.testBit(Short.MIN_VALUE, 14)); } diff --git a/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java b/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java index 2f3cf3bad..e025910a1 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java +++ b/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java @@ -19,52 +19,52 @@ package org.apache.thrift; -import org.junit.jupiter.api.Test; -import thrift.test.optiontypejdk8.Person; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; +import thrift.test.optiontypejdk8.Person; + // Tests and documents behavior for the JDK8 "Option<T>" type -public class TestOptionalsWithJdk8 { +public class TestOptionalsWithJdk8 { - @Test - public void testConstruction() { - Person person = new Person(1L, "name"); - assertFalse(person.getAge().isPresent()); - assertFalse(person.isSetAge()); - assertFalse(person.getPhone().isPresent()); - assertFalse(person.isSetPhone()); - assertEquals(1L, person.getId()); - assertTrue(person.isSetId()); - assertEquals("name", person.getName()); - assertTrue(person.isSetName()); + @Test + public void testConstruction() { + Person person = new Person(1L, "name"); + assertFalse(person.getAge().isPresent()); + assertFalse(person.isSetAge()); + assertFalse(person.getPhone().isPresent()); + assertFalse(person.isSetPhone()); + assertEquals(1L, person.getId()); + assertTrue(person.isSetId()); + assertEquals("name", person.getName()); + assertTrue(person.isSetName()); - assertFalse(person.getAddresses().isPresent()); - assertEquals(Integer.valueOf(0), person.getAddressesSize().orElse(0)); - assertFalse(person.getPets().isPresent()); - assertEquals(Integer.valueOf(0), person.getPetsSize().orElse(0)); - } + assertFalse(person.getAddresses().isPresent()); + assertEquals(Integer.valueOf(0), person.getAddressesSize().orElse(0)); + assertFalse(person.getPets().isPresent()); + assertEquals(Integer.valueOf(0), person.getPetsSize().orElse(0)); + } - @Test - public void testEmpty() { - Person person = new Person(); - person.setPhone("phone"); - assertFalse(person.getAge().isPresent()); - assertFalse(person.isSetAge()); - assertTrue(person.getPhone().isPresent()); - assertEquals("phone", person.getPhone().get()); - assertTrue(person.isSetPhone()); - assertEquals(0L, person.getId()); - assertFalse(person.isSetId()); - assertNull(person.getName()); - assertFalse(person.isSetName()); + @Test + public void testEmpty() { + Person person = new Person(); + person.setPhone("phone"); + assertFalse(person.getAge().isPresent()); + assertFalse(person.isSetAge()); + assertTrue(person.getPhone().isPresent()); + assertEquals("phone", person.getPhone().get()); + assertTrue(person.isSetPhone()); + assertEquals(0L, person.getId()); + assertFalse(person.isSetId()); + assertNull(person.getName()); + assertFalse(person.isSetName()); - assertFalse(person.getAddresses().isPresent()); - assertEquals(Integer.valueOf(0), person.getAddressesSize().orElse(0)); - assertFalse(person.getPets().isPresent()); - assertEquals(Integer.valueOf(0), person.getPetsSize().orElse(0)); - } + assertFalse(person.getAddresses().isPresent()); + assertEquals(Integer.valueOf(0), person.getAddressesSize().orElse(0)); + assertFalse(person.getPets().isPresent()); + assertEquals(Integer.valueOf(0), person.getPetsSize().orElse(0)); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java b/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java index b38f39c8f..2afc6ffdd 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java +++ b/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java @@ -19,163 +19,209 @@ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import thrift.test.DoubleConstantsTestConstants; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class TestRenderedDoubleConstants { - private static final double EPSILON = 0.0000001; - private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST = - "failed to verify a double constant generated by Thrift (expected = %f, got = %f)"; - private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST = - "failed to verify a list item by Thrift (expected = %f, got = %f)"; - private static final String ASSERTION_MESSAGE_FOR_TYPE_CHECKS = - "the rendered variable with name %s is not of double type"; + private static final double EPSILON = 0.0000001; + private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST = + "failed to verify a double constant generated by Thrift (expected = %f, got = %f)"; + private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST = + "failed to verify a list item by Thrift (expected = %f, got = %f)"; + private static final String ASSERTION_MESSAGE_FOR_TYPE_CHECKS = + "the rendered variable with name %s is not of double type"; - // to make sure lists containing doubles are generated correctly - @Test - public void testRenderedDoubleList() throws Exception { - final double[] EXPECTED_LIST = - {1d, -100d, 100d, 9223372036854775807d, -9223372036854775807d, 3.14159265359, 1000000.1, -1000000.1, 1.7e+308, - -1.7e+308, 9223372036854775816.43, -9223372036854775816.43}; - assertEquals(EXPECTED_LIST.length, DoubleConstantsTestConstants.DOUBLE_LIST_TEST.size()); - for (int i = 0; i < EXPECTED_LIST.length; ++i) { - assertEquals( - EXPECTED_LIST[i], - DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i), EPSILON, String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST, - EXPECTED_LIST[i], - DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i))); - } + // to make sure lists containing doubles are generated correctly + @Test + public void testRenderedDoubleList() throws Exception { + final double[] EXPECTED_LIST = { + 1d, + -100d, + 100d, + 9223372036854775807d, + -9223372036854775807d, + 3.14159265359, + 1000000.1, + -1000000.1, + 1.7e+308, + -1.7e+308, + 9223372036854775816.43, + -9223372036854775816.43 + }; + assertEquals(EXPECTED_LIST.length, DoubleConstantsTestConstants.DOUBLE_LIST_TEST.size()); + for (int i = 0; i < EXPECTED_LIST.length; ++i) { + assertEquals( + EXPECTED_LIST[i], + DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i), + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST, + EXPECTED_LIST[i], + DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i))); } + } - // to make sure the variables inside Thrift files are generated correctly - @Test - public void testRenderedDoubleConstants() throws Exception { - final double EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1.0; - final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100.0; - final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT = 9223372036854775807.0; - final double EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT = -9223372036854775807.0; - final double EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS = 3.14159265359; - final double EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE = 1000000.1; - final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE = -1000000.1; - final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE = 1.7e+308; - final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE = 9223372036854775816.43; - final double EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308; - final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = -9223372036854775816.43; - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, EPSILON, String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)); - assertEquals( - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON, - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST")); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST")); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST")); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST")); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST")); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST")); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST")); - //assertTrue( - // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST"), - // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)); - assertTrue( - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST), - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST")); - //assertTrue( - // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST"), - // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)); - assertTrue( - Double.class.isInstance( - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST), - String.format( - ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST")); - } + // to make sure the variables inside Thrift files are generated correctly + @Test + public void testRenderedDoubleConstants() throws Exception { + final double EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT = 9223372036854775807.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT = -9223372036854775807.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS = 3.14159265359; + final double EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE = 1000000.1; + final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE = -1000000.1; + final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE = 1.7e+308; + final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE = 9223372036854775816.43; + final double EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308; + final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = + -9223372036854775816.43; + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)); + assertEquals( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, + EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants + .DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)); + assertTrue( + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST")); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST")); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST")); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST")); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, + "DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST")); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST")); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, + "DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST")); + // assertTrue( + // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST"), + // + // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST")); + // assertTrue( + // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST"), + // + // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)); + assertTrue( + Double.class.isInstance( + DoubleConstantsTestConstants + .DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, + "DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST")); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestReuse.java b/lib/java/src/test/java/org/apache/thrift/TestReuse.java index 56dc1d4ed..4fa81db38 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestReuse.java +++ b/lib/java/src/test/java/org/apache/thrift/TestReuse.java @@ -19,22 +19,21 @@ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.util.HashSet; import org.apache.thrift.protocol.TBinaryProtocol; import org.junit.jupiter.api.Test; import thrift.test.Reuse; -import java.util.HashSet; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; - // Tests reusing objects for deserialization. // public class TestReuse extends TestStruct { @Test public void testReuseObject() throws Exception { - TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); Reuse ru1 = new Reuse(); @@ -57,5 +56,4 @@ public class TestReuse extends TestStruct { assertSame(hs1, ru1.getVal2()); assertEquals(2, hs1.size()); } - } diff --git a/lib/java/src/test/java/org/apache/thrift/TestStruct.java b/lib/java/src/test/java/org/apache/thrift/TestStruct.java index 84b00b4fb..17a00f159 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestStruct.java +++ b/lib/java/src/test/java/org/apache/thrift/TestStruct.java @@ -18,6 +18,21 @@ */ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; import org.apache.thrift.meta_data.FieldMetaData; import org.apache.thrift.meta_data.ListMetaData; import org.apache.thrift.meta_data.MapMetaData; @@ -38,26 +53,10 @@ import thrift.test.StructA; import thrift.test.StructB; import thrift.test.Xtruct; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class TestStruct { @Test public void testIdentity() throws Exception { - TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); OneOfEach ooe = Fixtures.getOneOfEach(); @@ -67,37 +66,31 @@ public class TestStruct { n.my_ooe.integer16 = 16; n.my_ooe.integer32 = 32; n.my_ooe.integer64 = 64; - n.my_ooe.double_precision = (Math.sqrt(5)+1)/2; - n.my_ooe.some_characters = ":R (me going \"rrrr\")"; - n.my_ooe.zomg_unicode = "\u04c0\u216e\u039d\u0020\u041d\u03bf\u217f"+ - "\u043e\u0261\u0433\u0430\u03c1\u210e\u0020"+ - "\u0391\u0074\u0074\u03b1\u217d\u03ba\u01c3"+ - "\u203c"; + n.my_ooe.double_precision = (Math.sqrt(5) + 1) / 2; + n.my_ooe.some_characters = ":R (me going \"rrrr\")"; + n.my_ooe.zomg_unicode = + "\u04c0\u216e\u039d\u0020\u041d\u03bf\u217f" + + "\u043e\u0261\u0433\u0430\u03c1\u210e\u0020" + + "\u0391\u0074\u0074\u03b1\u217d\u03ba\u01c3" + + "\u203c"; n.my_bonk = Fixtures.getNesting().my_bonk; HolyMoley hm = Fixtures.getHolyMoley(); OneOfEach ooe2 = new OneOfEach(); - binaryDeserializer.deserialize( - ooe2, - binarySerializer.serialize(ooe)); + binaryDeserializer.deserialize(ooe2, binarySerializer.serialize(ooe)); assertEquals(ooe, ooe2); assertEquals(ooe.hashCode(), ooe2.hashCode()); - Nesting n2 = new Nesting(); - binaryDeserializer.deserialize( - n2, - binarySerializer.serialize(n)); + binaryDeserializer.deserialize(n2, binarySerializer.serialize(n)); assertEquals(n, n2); assertEquals(n.hashCode(), n2.hashCode()); HolyMoley hm2 = new HolyMoley(); - binaryDeserializer.deserialize( - hm2, - binarySerializer.serialize(hm)); + binaryDeserializer.deserialize(hm2, binarySerializer.serialize(hm)); assertEquals(hm, hm2); assertEquals(hm.hashCode(), hm2.hashCode()); @@ -105,7 +98,7 @@ public class TestStruct { @Test public void testDeepCopy() throws Exception { - TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); HolyMoley hm = Fixtures.getHolyMoley(); @@ -195,17 +188,21 @@ public class TestStruct { private void expectLessThan(Insanity insanity1, Insanity insanity2) { int compareTo = insanity1.compareTo(insanity2); - assertTrue(compareTo < 0, insanity1 + " should be less than " + insanity2 + ", but is: " + compareTo); + assertTrue( + compareTo < 0, insanity1 + " should be less than " + insanity2 + ", but is: " + compareTo); } private void expectGreaterThan(Insanity insanity1, Insanity insanity2) { int compareTo = insanity1.compareTo(insanity2); - assertTrue(compareTo > 0, insanity1 + " should be greater than " + insanity2 + ", but is: " + compareTo); + assertTrue( + compareTo > 0, + insanity1 + " should be greater than " + insanity2 + ", but is: " + compareTo); } private void expectEquals(Insanity insanity1, Insanity insanity2) { int compareTo = insanity1.compareTo(insanity2); - assertEquals(0, compareTo, insanity1 + " should be equal to " + insanity2 + ", but is: " + compareTo); + assertEquals( + 0, compareTo, insanity1 + " should be equal to " + insanity2 + ", but is: " + compareTo); } @Test @@ -225,9 +222,13 @@ public class TestStruct { assertEquals("set_field", mdMap.get(CrazyNesting._Fields.SET_FIELD).fieldName); assertEquals("binary_field", mdMap.get(CrazyNesting._Fields.BINARY_FIELD).fieldName); - assertEquals(TFieldRequirementType.DEFAULT, mdMap.get(CrazyNesting._Fields.STRING_FIELD).requirementType); - assertEquals(TFieldRequirementType.REQUIRED, mdMap.get(CrazyNesting._Fields.LIST_FIELD).requirementType); - assertEquals(TFieldRequirementType.OPTIONAL, mdMap.get(CrazyNesting._Fields.SET_FIELD).requirementType); + assertEquals( + TFieldRequirementType.DEFAULT, + mdMap.get(CrazyNesting._Fields.STRING_FIELD).requirementType); + assertEquals( + TFieldRequirementType.REQUIRED, mdMap.get(CrazyNesting._Fields.LIST_FIELD).requirementType); + assertEquals( + TFieldRequirementType.OPTIONAL, mdMap.get(CrazyNesting._Fields.SET_FIELD).requirementType); assertEquals(TType.STRING, mdMap.get(CrazyNesting._Fields.STRING_FIELD).valueMetaData.type); assertFalse(mdMap.get(CrazyNesting._Fields.STRING_FIELD).valueMetaData.isBinary()); @@ -241,9 +242,44 @@ public class TestStruct { assertFalse(mdMap.get(CrazyNesting._Fields.LIST_FIELD).valueMetaData.isStruct()); - assertEquals(TType.STRUCT, ((MapMetaData)((ListMetaData)((SetMetaData)((MapMetaData)((MapMetaData)((ListMetaData)mdMap.get(CrazyNesting._Fields.LIST_FIELD).valueMetaData).elemMetaData).valueMetaData).valueMetaData).elemMetaData).elemMetaData).keyMetaData.type); - - assertEquals(Insanity.class, ((StructMetaData)((MapMetaData)((ListMetaData)((SetMetaData)((MapMetaData)((MapMetaData)((ListMetaData)mdMap.get(CrazyNesting._Fields.LIST_FIELD).valueMetaData).elemMetaData).valueMetaData).valueMetaData).elemMetaData).elemMetaData).keyMetaData).structClass); + assertEquals( + TType.STRUCT, + ((MapMetaData) + ((ListMetaData) + ((SetMetaData) + ((MapMetaData) + ((MapMetaData) + ((ListMetaData) + mdMap.get(CrazyNesting._Fields.LIST_FIELD) + .valueMetaData) + .elemMetaData) + .valueMetaData) + .valueMetaData) + .elemMetaData) + .elemMetaData) + .keyMetaData + .type); + + assertEquals( + Insanity.class, + ((StructMetaData) + ((MapMetaData) + ((ListMetaData) + ((SetMetaData) + ((MapMetaData) + ((MapMetaData) + ((ListMetaData) + mdMap.get( + CrazyNesting._Fields + .LIST_FIELD) + .valueMetaData) + .elemMetaData) + .valueMetaData) + .valueMetaData) + .elemMetaData) + .elemMetaData) + .keyMetaData) + .structClass); // Check that FieldMetaData contains a map with metadata for all generated struct classes assertNotNull(FieldMetaData.getStructMetaDataMap(CrazyNesting.class)); @@ -257,7 +293,8 @@ public class TestStruct { assertEquals(mdEntry.getKey(), CrazyNesting._Fields.findByName(mdEntry.getValue().fieldName)); } - MapMetaData vmd = (MapMetaData)Insanity.metaDataMap.get(Insanity._Fields.USER_MAP).valueMetaData; + MapMetaData vmd = + (MapMetaData) Insanity.metaDataMap.get(Insanity._Fields.USER_MAP).valueMetaData; assertTrue(vmd.valueMetaData.isTypedef()); assertFalse(vmd.keyMetaData.isTypedef()); } @@ -268,56 +305,56 @@ public class TestStruct { object.req_int = 0; object.req_obj = ""; - object.req_bin = ByteBuffer.wrap(new byte[] { - 0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, - 16, -17, 18, -19, 20, -21, 22, -23, 24, -25, 26, -27, 28, -29, - 30, -31, 32, -33, 34, -35, 36, -37, 38, -39, 40, -41, 42, -43, 44, - -45, 46, -47, 48, -49, 50, -51, 52, -53, 54, -55, 56, -57, 58, -59, - 60, -61, 62, -63, 64, -65, 66, -67, 68, -69, 70, -71, 72, -73, 74, - -75, 76, -77, 78, -79, 80, -81, 82, -83, 84, -85, 86, -87, 88, -89, - 90, -91, 92, -93, 94, -95, 96, -97, 98, -99, 100, -101, 102, -103, - 104, -105, 106, -107, 108, -109, 110, -111, 112, -113, 114, -115, - 116, -117, 118, -119, 120, -121, 122, -123, 124, -125, 126, -127, - }); - - assertEquals("JavaTestHelper(req_int:0, req_obj:, req_bin:"+ - "00 FF 02 FD 04 FB 06 F9 08 F7 0A F5 0C F3 0E F1 10 EF 12 ED 14 "+ - "EB 16 E9 18 E7 1A E5 1C E3 1E E1 20 DF 22 DD 24 DB 26 D9 28 D7 "+ - "2A D5 2C D3 2E D1 30 CF 32 CD 34 CB 36 C9 38 C7 3A C5 3C C3 3E "+ - "C1 40 BF 42 BD 44 BB 46 B9 48 B7 4A B5 4C B3 4E B1 50 AF 52 AD "+ - "54 AB 56 A9 58 A7 5A A5 5C A3 5E A1 60 9F 62 9D 64 9B 66 99 68 "+ - "97 6A 95 6C 93 6E 91 70 8F 72 8D 74 8B 76 89 78 87 7A 85 7C 83 "+ - "7E 81)", + object.req_bin = + ByteBuffer.wrap( + new byte[] { + 0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, 16, -17, 18, -19, 20, + -21, 22, -23, 24, -25, 26, -27, 28, -29, 30, -31, 32, -33, 34, -35, 36, -37, 38, -39, + 40, -41, 42, -43, 44, -45, 46, -47, 48, -49, 50, -51, 52, -53, 54, -55, 56, -57, 58, + -59, 60, -61, 62, -63, 64, -65, 66, -67, 68, -69, 70, -71, 72, -73, 74, -75, 76, -77, + 78, -79, 80, -81, 82, -83, 84, -85, 86, -87, 88, -89, 90, -91, 92, -93, 94, -95, 96, + -97, 98, -99, 100, -101, 102, -103, 104, -105, 106, -107, 108, -109, 110, -111, 112, + -113, 114, -115, 116, -117, 118, -119, 120, -121, 122, -123, 124, -125, 126, -127, + }); + + assertEquals( + "JavaTestHelper(req_int:0, req_obj:, req_bin:" + + "00 FF 02 FD 04 FB 06 F9 08 F7 0A F5 0C F3 0E F1 10 EF 12 ED 14 " + + "EB 16 E9 18 E7 1A E5 1C E3 1E E1 20 DF 22 DD 24 DB 26 D9 28 D7 " + + "2A D5 2C D3 2E D1 30 CF 32 CD 34 CB 36 C9 38 C7 3A C5 3C C3 3E " + + "C1 40 BF 42 BD 44 BB 46 B9 48 B7 4A B5 4C B3 4E B1 50 AF 52 AD " + + "54 AB 56 A9 58 A7 5A A5 5C A3 5E A1 60 9F 62 9D 64 9B 66 99 68 " + + "97 6A 95 6C 93 6E 91 70 8F 72 8D 74 8B 76 89 78 87 7A 85 7C 83 " + + "7E 81)", object.toString()); - object.req_bin = ByteBuffer.wrap(new byte[] { - 0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, - 16, -17, 18, -19, 20, -21, 22, -23, 24, -25, 26, -27, 28, -29, - 30, -31, 32, -33, 34, -35, 36, -37, 38, -39, 40, -41, 42, -43, 44, - -45, 46, -47, 48, -49, 50, -51, 52, -53, 54, -55, 56, -57, 58, -59, - 60, -61, 62, -63, 64, -65, 66, -67, 68, -69, 70, -71, 72, -73, 74, - -75, 76, -77, 78, -79, 80, -81, 82, -83, 84, -85, 86, -87, 88, -89, - 90, -91, 92, -93, 94, -95, 96, -97, 98, -99, 100, -101, 102, -103, - 104, -105, 106, -107, 108, -109, 110, -111, 112, -113, 114, -115, - 116, -117, 118, -119, 120, -121, 122, -123, 124, -125, 126, -127, - 0, - }); - - assertEquals("JavaTestHelper(req_int:0, req_obj:, req_bin:"+ - "00 FF 02 FD 04 FB 06 F9 08 F7 0A F5 0C F3 0E F1 10 EF 12 ED 14 "+ - "EB 16 E9 18 E7 1A E5 1C E3 1E E1 20 DF 22 DD 24 DB 26 D9 28 D7 "+ - "2A D5 2C D3 2E D1 30 CF 32 CD 34 CB 36 C9 38 C7 3A C5 3C C3 3E "+ - "C1 40 BF 42 BD 44 BB 46 B9 48 B7 4A B5 4C B3 4E B1 50 AF 52 AD "+ - "54 AB 56 A9 58 A7 5A A5 5C A3 5E A1 60 9F 62 9D 64 9B 66 99 68 "+ - "97 6A 95 6C 93 6E 91 70 8F 72 8D 74 8B 76 89 78 87 7A 85 7C 83 "+ - "7E 81...)", + object.req_bin = + ByteBuffer.wrap( + new byte[] { + 0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, 16, -17, 18, -19, 20, + -21, 22, -23, 24, -25, 26, -27, 28, -29, 30, -31, 32, -33, 34, -35, 36, -37, 38, -39, + 40, -41, 42, -43, 44, -45, 46, -47, 48, -49, 50, -51, 52, -53, 54, -55, 56, -57, 58, + -59, 60, -61, 62, -63, 64, -65, 66, -67, 68, -69, 70, -71, 72, -73, 74, -75, 76, -77, + 78, -79, 80, -81, 82, -83, 84, -85, 86, -87, 88, -89, 90, -91, 92, -93, 94, -95, 96, + -97, 98, -99, 100, -101, 102, -103, 104, -105, 106, -107, 108, -109, 110, -111, 112, + -113, 114, -115, 116, -117, 118, -119, 120, -121, 122, -123, 124, -125, 126, -127, 0, + }); + + assertEquals( + "JavaTestHelper(req_int:0, req_obj:, req_bin:" + + "00 FF 02 FD 04 FB 06 F9 08 F7 0A F5 0C F3 0E F1 10 EF 12 ED 14 " + + "EB 16 E9 18 E7 1A E5 1C E3 1E E1 20 DF 22 DD 24 DB 26 D9 28 D7 " + + "2A D5 2C D3 2E D1 30 CF 32 CD 34 CB 36 C9 38 C7 3A C5 3C C3 3E " + + "C1 40 BF 42 BD 44 BB 46 B9 48 B7 4A B5 4C B3 4E B1 50 AF 52 AD " + + "54 AB 56 A9 58 A7 5A A5 5C A3 5E A1 60 9F 62 9D 64 9B 66 99 68 " + + "97 6A 95 6C 93 6E 91 70 8F 72 8D 74 8B 76 89 78 87 7A 85 7C 83 " + + "7E 81...)", object.toString()); object.req_bin = ByteBuffer.wrap(new byte[] {}); object.setOpt_binIsSet(true); - assertEquals("JavaTestHelper(req_int:0, req_obj:, req_bin:)", - object.toString()); + assertEquals("JavaTestHelper(req_int:0, req_obj:, req_bin:)", object.toString()); } @Test @@ -326,13 +363,13 @@ public class TestStruct { final String testString = "testBytesBufferFeatures"; final JavaTestHelper o = new JavaTestHelper(); - o.setReq_bin((ByteBuffer)null); + o.setReq_bin((ByteBuffer) null); assertNull(o.getReq_bin()); o.setReq_bin(ByteBuffer.wrap(testString.getBytes())); assertArrayEquals(testString.getBytes(), o.getReq_bin()); - o.setReq_bin((byte[])null); + o.setReq_bin((byte[]) null); assertNull(o.getReq_bin()); o.setReq_bin(testString.getBytes()); diff --git a/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java b/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java index b877afa3b..90ed6fda8 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java @@ -18,7 +18,10 @@ */ package org.apache.thrift; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.util.Arrays; @@ -27,18 +30,12 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - - - -public class TestTBaseHelper { +public class TestTBaseHelper { @Test public void testByteArrayComparison() { - assertTrue(TBaseHelper.compareTo(new byte[]{'a','b'}, new byte[]{'a','c'}) < 0); + assertTrue(TBaseHelper.compareTo(new byte[] {'a', 'b'}, new byte[] {'a', 'c'}) < 0); } @Test @@ -70,10 +67,10 @@ public class TestTBaseHelper { Set<List<String>> a = new HashSet<>(); Set<List<String>> b = new HashSet<>(); - a.add(Arrays.asList("a","b")); - b.add(Arrays.asList("a","b", "c")); - a.add(Arrays.asList("a","b")); - b.add(Arrays.asList("a","b", "c")); + a.add(Arrays.asList("a", "b")); + b.add(Arrays.asList("a", "b", "c")); + a.add(Arrays.asList("a", "b")); + b.add(Arrays.asList("a", "b", "c")); assertTrue(TBaseHelper.compareTo(a, b) < 0); } @@ -103,10 +100,10 @@ public class TestTBaseHelper { assertEquals(0, TBaseHelper.compareTo(a, b)); - a.put(new byte[]{'a','b'}, 1000L); - b.put(new byte[]{'a','b'}, 1000L); - a.put(new byte[]{'a','b', 'd'}, 1000L); - b.put(new byte[]{'a','b', 'a'}, 1000L); + a.put(new byte[] {'a', 'b'}, 1000L); + b.put(new byte[] {'a', 'b'}, 1000L); + a.put(new byte[] {'a', 'b', 'd'}, 1000L); + b.put(new byte[] {'a', 'b', 'a'}, 1000L); assertTrue(TBaseHelper.compareTo(a, b) > 0); } @@ -150,16 +147,16 @@ public class TestTBaseHelper { if (TBaseHelper.compareTo(a, b) != 0) throw new RuntimeException("Set compare failed:" + a + " vs. " + b); - a.add(new byte[]{'a','b'}); - b.add(new byte[]{'a','b'}); - a.add(new byte[]{'a','b', 'd'}); - b.add(new byte[]{'a','b', 'a'}); + a.add(new byte[] {'a', 'b'}); + b.add(new byte[] {'a', 'b'}); + a.add(new byte[] {'a', 'b', 'd'}); + b.add(new byte[] {'a', 'b', 'a'}); assertTrue(TBaseHelper.compareTo(a, b) > 0); } @Test public void testByteBufferToByteArray() throws Exception { - byte[] b1 = {10,9,8,7,6,5,4,3,2,1,0}; + byte[] b1 = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; byte[] b2 = TBaseHelper.byteBufferToByteArray(ByteBuffer.wrap(b1)); assertEquals(b1, b2, "b1 and b2 should be the exact same array (identity) due to fast path"); @@ -175,7 +172,7 @@ public class TestTBaseHelper { @Test public void testByteBufferToString() { - byte[] array = new byte[]{1, 2, 3}; + byte[] array = new byte[] {1, 2, 3}; ByteBuffer bb = ByteBuffer.wrap(array, 1, 2); StringBuilder sb = new StringBuilder(); TBaseHelper.toString(bb, sb); @@ -193,7 +190,7 @@ public class TestTBaseHelper { @Test public void testCopyBinaryWithByteBuffer() throws Exception { - byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5}; + byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5}; ByteBuffer b = ByteBuffer.wrap(bytes); ByteBuffer bCopy = TBaseHelper.copyBinary(b); assertEquals(b, bCopy); @@ -215,16 +212,16 @@ public class TestTBaseHelper { b.reset(); assertEquals(0, b.position()); - assertNull(TBaseHelper.copyBinary((ByteBuffer)null)); + assertNull(TBaseHelper.copyBinary((ByteBuffer) null)); } @Test public void testCopyBinaryWithByteArray() throws Exception { - byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5}; + byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5}; byte[] copy = TBaseHelper.copyBinary(bytes); assertEquals(ByteBuffer.wrap(bytes), ByteBuffer.wrap(copy)); assertNotSame(bytes, copy); - assertNull(TBaseHelper.copyBinary((byte[])null)); + assertNull(TBaseHelper.copyBinary((byte[]) null)); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java b/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java index c3b588e61..8a02e3a75 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java @@ -18,6 +18,9 @@ */ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.ByteBuffer; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TJSONProtocol; @@ -29,21 +32,16 @@ import thrift.test.PrimitiveThenStruct; import thrift.test.StructWithAUnion; import thrift.test.TestUnion; -import java.nio.ByteBuffer; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class TestTDeserializer { +public class TestTDeserializer { - private static final TProtocolFactory[] PROTOCOLS = new TProtocolFactory[] { - new TBinaryProtocol.Factory(), - new TCompactProtocol.Factory(), - new TJSONProtocol.Factory() - }; + private static final TProtocolFactory[] PROTOCOLS = + new TProtocolFactory[] { + new TBinaryProtocol.Factory(), new TCompactProtocol.Factory(), new TJSONProtocol.Factory() + }; @Test public void testPartialDeserialize() throws Exception { - //Root:StructWithAUnion + // Root:StructWithAUnion // 1:Union // 1.3:OneOfEach OneOfEach level3OneOfEach = Fixtures.getOneOfEach(); @@ -55,73 +53,149 @@ public class TestTDeserializer { for (TProtocolFactory factory : PROTOCOLS) { - //Level 2 test - testPartialDeserialize(factory, level1SWU, new TestUnion(), level2TestUnion, StructWithAUnion._Fields.TEST_UNION); - - //Level 3 on 3rd field test - testPartialDeserialize(factory, level1SWU, new OneOfEach(), level3OneOfEach, StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD); - - //Test early termination when traversed path Field.id exceeds the one being searched for - testPartialDeserialize(factory, level1SWU, new OneOfEach(), new OneOfEach(), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.I32_FIELD); - - //Test that readStructBegin isn't called on primitive + // Level 2 test + testPartialDeserialize( + factory, + level1SWU, + new TestUnion(), + level2TestUnion, + StructWithAUnion._Fields.TEST_UNION); + + // Level 3 on 3rd field test + testPartialDeserialize( + factory, + level1SWU, + new OneOfEach(), + level3OneOfEach, + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD); + + // Test early termination when traversed path Field.id exceeds the one being searched for + testPartialDeserialize( + factory, + level1SWU, + new OneOfEach(), + new OneOfEach(), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.I32_FIELD); + + // Test that readStructBegin isn't called on primitive testPartialDeserialize(factory, pts, new Backwards(), bw, PrimitiveThenStruct._Fields.BW); - //Test primitive types + // Test primitive types TDeserializer deserializer = new TDeserializer(factory); Boolean expectedBool = level3OneOfEach.isIm_true(); - Boolean resultBool = deserializer.partialDeserializeBool(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.IM_TRUE); + Boolean resultBool = + deserializer.partialDeserializeBool( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.IM_TRUE); assertEquals(expectedBool, resultBool); Byte expectedByte = level3OneOfEach.getA_bite(); - Byte resultByte = deserializer.partialDeserializeByte(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.A_BITE); + Byte resultByte = + deserializer.partialDeserializeByte( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.A_BITE); assertEquals(expectedByte, resultByte); Double expectedDouble = level3OneOfEach.getDouble_precision(); - Double resultDouble = deserializer.partialDeserializeDouble(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.DOUBLE_PRECISION); + Double resultDouble = + deserializer.partialDeserializeDouble( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.DOUBLE_PRECISION); assertEquals(expectedDouble, resultDouble); Short expectedI16 = level3OneOfEach.getInteger16(); - Short resultI16 = deserializer.partialDeserializeI16(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.INTEGER16); + Short resultI16 = + deserializer.partialDeserializeI16( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.INTEGER16); assertEquals(expectedI16, resultI16); Integer expectedI32 = level3OneOfEach.getInteger32(); - Integer resultI32 = deserializer.partialDeserializeI32(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.INTEGER32); + Integer resultI32 = + deserializer.partialDeserializeI32( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.INTEGER32); assertEquals(expectedI32, resultI32); Long expectedI64 = level3OneOfEach.getInteger64(); - Long resultI64= deserializer.partialDeserializeI64(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.INTEGER64); + Long resultI64 = + deserializer.partialDeserializeI64( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.INTEGER64); assertEquals(expectedI64, resultI64); String expectedString = level3OneOfEach.getSome_characters(); - String resultString = deserializer.partialDeserializeString(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.SOME_CHARACTERS); + String resultString = + deserializer.partialDeserializeString( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.SOME_CHARACTERS); assertEquals(expectedString, resultString); byte[] expectedBinary = level3OneOfEach.getBase64(); - ByteBuffer resultBinary = deserializer.partialDeserializeByteArray(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION, TestUnion._Fields.STRUCT_FIELD, OneOfEach._Fields.BASE64); - assertEquals(expectedBinary.length, resultBinary.limit() - resultBinary.position() - resultBinary.arrayOffset()); + ByteBuffer resultBinary = + deserializer.partialDeserializeByteArray( + serialize(level1SWU, factory), + StructWithAUnion._Fields.TEST_UNION, + TestUnion._Fields.STRUCT_FIELD, + OneOfEach._Fields.BASE64); + assertEquals( + expectedBinary.length, + resultBinary.limit() - resultBinary.position() - resultBinary.arrayOffset()); assertEquals(ByteBuffer.wrap(expectedBinary), resultBinary); // Test field id in Union - short id = deserializer.partialDeserializeSetFieldIdInUnion(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION); + short id = + deserializer.partialDeserializeSetFieldIdInUnion( + serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION); assertEquals(level2TestUnion.getSetField().getThriftFieldId(), id); } } - private void testPartialDeserialize(TProtocolFactory protocolFactory, TBase input, TBase output, TBase expected, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + private void testPartialDeserialize( + TProtocolFactory protocolFactory, + TBase input, + TBase output, + TBase expected, + TFieldIdEnum fieldIdPathFirst, + TFieldIdEnum... fieldIdPathRest) + throws TException { byte[] record = serialize(input, protocolFactory); TDeserializer deserializer = new TDeserializer(protocolFactory); for (int i = 0; i < 2; i++) { TBase outputCopy = output.deepCopy(); deserializer.partialDeserialize(outputCopy, record, fieldIdPathFirst, fieldIdPathRest); - assertEquals(expected, - outputCopy, "on attempt " + i + ", with " + protocolFactory - + ", expected " + expected + " but got " + outputCopy); + assertEquals( + expected, + outputCopy, + "on attempt " + + i + + ", with " + + protocolFactory + + ", expected " + + expected + + " but got " + + outputCopy); } } - private static byte[] serialize(TBase input, TProtocolFactory protocolFactory) throws TException{ + private static byte[] serialize(TBase input, TProtocolFactory protocolFactory) throws TException { return new TSerializer(protocolFactory).serialize(input); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java b/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java index e61b1794b..a05910358 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java @@ -18,17 +18,17 @@ */ package org.apache.thrift; -import org.junit.jupiter.api.Test; -import thrift.test.Numberz; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -public class TestTEnumHelper { +import org.junit.jupiter.api.Test; +import thrift.test.Numberz; + +public class TestTEnumHelper { @Test public void testGetByValue_ValidValues() { - for (Numberz n: Numberz.values()) { + for (Numberz n : Numberz.values()) { int value = n.getValue(); assertEquals(n, TEnumHelper.getByValue(Numberz.class, value)); } diff --git a/lib/java/src/test/java/org/apache/thrift/TestTUnion.java b/lib/java/src/test/java/org/apache/thrift/TestTUnion.java index 36e87c027..9018f47e3 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTUnion.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTUnion.java @@ -18,18 +18,12 @@ */ package org.apache.thrift; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.protocol.TTupleProtocol; -import org.apache.thrift.transport.TMemoryBuffer; -import org.junit.jupiter.api.Test; -import thrift.test.ComparableUnion; -import thrift.test.Empty; -import thrift.test.RandomStuff; -import thrift.test.SomeEnum; -import thrift.test.StructWithAUnion; -import thrift.test.TestUnion; -import thrift.test.TestUnionMinusStringField; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -42,15 +36,20 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.protocol.TTupleProtocol; +import org.apache.thrift.transport.TMemoryBuffer; +import org.junit.jupiter.api.Test; +import thrift.test.ComparableUnion; +import thrift.test.Empty; +import thrift.test.RandomStuff; +import thrift.test.SomeEnum; +import thrift.test.StructWithAUnion; +import thrift.test.TestUnion; +import thrift.test.TestUnionMinusStringField; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class TestTUnion { +public class TestTUnion { @Test public void testBasic() throws Exception { @@ -65,7 +64,9 @@ public class TestTUnion { assertEquals(25, union.getFieldValue()); assertEquals(25, union.getFieldValue(TestUnion._Fields.I32_FIELD)); assertTrue(union.isSetI32_field()); - assertThrows(IllegalArgumentException.class, () -> union.getFieldValue(TestUnion._Fields.STRING_FIELD)); + assertThrows( + IllegalArgumentException.class, + () -> union.getFieldValue(TestUnion._Fields.STRING_FIELD)); } { TestUnion union = new TestUnion(); @@ -104,12 +105,12 @@ public class TestTUnion { assertTrue(cu.compareTo(cu2) < 0); assertTrue(cu2.compareTo(cu) > 0); - cu2 = ComparableUnion.binary_field(ByteBuffer.wrap(new byte[]{2})); + cu2 = ComparableUnion.binary_field(ByteBuffer.wrap(new byte[] {2})); assertTrue(cu.compareTo(cu2) < 0); assertTrue(cu2.compareTo(cu) > 0); - cu = ComparableUnion.binary_field(ByteBuffer.wrap(new byte[]{1})); + cu = ComparableUnion.binary_field(ByteBuffer.wrap(new byte[] {1})); assertTrue(cu.compareTo(cu2) < 0); assertTrue(cu2.compareTo(cu) > 0); @@ -125,7 +126,7 @@ public class TestTUnion { assertTrue(union3.compareTo(union4) < 0); Map<Integer, Integer> i32_map = new HashMap<Integer, Integer>(); - i32_map.put(1,1); + i32_map.put(1, 1); TestUnion union5 = new TestUnion(TestUnion._Fields.I32_MAP, i32_map); TestUnion union6 = new TestUnion(TestUnion._Fields.I32_MAP, new HashMap<Integer, Integer>()); assertTrue(union5.compareTo(union6) > 0); @@ -185,7 +186,7 @@ public class TestTUnion { } @Test - public void testTupleProtocolSerialization () throws Exception { + public void testTupleProtocolSerialization() throws Exception { TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); union.setI32_set(Collections.singleton(42)); diff --git a/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java b/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java index 7e7fc4b9c..15acf9a32 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java +++ b/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java @@ -19,20 +19,19 @@ package org.apache.thrift; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import java.nio.ByteBuffer; import org.junit.jupiter.api.Test; import thrift.test.SafeBytes; import thrift.test.UnsafeBytes; -import java.nio.ByteBuffer; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - // test generating types with un-copied byte[]/ByteBuffer input/output // public class TestUnsafeBinaries { private static byte[] input() { - return new byte[]{1, 1}; + return new byte[] {1, 1}; } // @@ -48,27 +47,26 @@ public class TestUnsafeBinaries { input[0] = 2; - assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); - + assertArrayEquals(new byte[] {2, 1}, struct.getBytes()); } // getter doesn't copy - // note: this behavior is the same with/without the flag, but if this default ever changes, the current behavior + // note: this behavior is the same with/without the flag, but if this default ever changes, the + // current behavior // should be retained when using this flag @Test - public void testUnsafeGetter(){ + public void testUnsafeGetter() { UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); byte[] val = struct.getBytes(); val[0] = 2; - assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); - + assertArrayEquals(new byte[] {2, 1}, struct.getBytes()); } // setter doesn't copy @Test - public void testUnsafeSetter(){ + public void testUnsafeSetter() { UnsafeBytes struct = new UnsafeBytes(); byte[] val = input(); @@ -76,20 +74,18 @@ public class TestUnsafeBinaries { val[0] = 2; - assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); - + assertArrayEquals(new byte[] {2, 1}, struct.getBytes()); } // buffer doens't copy @Test - public void testUnsafeBufferFor(){ + public void testUnsafeBufferFor() { UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); ByteBuffer val = struct.bufferForBytes(); val.array()[0] = 2; - assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); - + assertArrayEquals(new byte[] {2, 1}, struct.getBytes()); } // @@ -104,8 +100,7 @@ public class TestUnsafeBinaries { input[0] = 2; - assertArrayEquals(new byte[]{1, 1}, struct.getBytes()); - + assertArrayEquals(new byte[] {1, 1}, struct.getBytes()); } @Test @@ -116,19 +111,16 @@ public class TestUnsafeBinaries { input[0] = 2; - assertArrayEquals(new byte[]{1, 1}, struct.getBytes()); - + assertArrayEquals(new byte[] {1, 1}, struct.getBytes()); } @Test - public void testSafeBufferFor(){ + public void testSafeBufferFor() { SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input())); ByteBuffer val = struct.bufferForBytes(); val.array()[0] = 2; - assertArrayEquals(new byte[]{1, 1}, struct.getBytes()); - + assertArrayEquals(new byte[] {1, 1}, struct.getBytes()); } - } diff --git a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java index 9a755d3be..863c42ef4 100644 --- a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java +++ b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java @@ -1,23 +1,22 @@ package org.apache.thrift.async; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.thrift.TException; import org.junit.jupiter.api.Test; import thrift.test.Srv; import thrift.test.Srv.AsyncClient; -import static org.junit.jupiter.api.Assertions.assertThrows; - - public class TestTAsyncClient { @Test public void testRaisesExceptionWhenUsedConcurrently() throws Exception { - TAsyncClientManager mockClientManager = new TAsyncClientManager() { - @Override - public void call(TAsyncMethodCall method) throws TException { - // do nothing - } - }; + TAsyncClientManager mockClientManager = + new TAsyncClientManager() { + @Override + public void call(TAsyncMethodCall method) throws TException { + // do nothing + } + }; Srv.AsyncClient c = new AsyncClient(null, mockClientManager, null); c.Janky(0, null); diff --git a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java index 8d12429f7..4dacb0f3b 100644 --- a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java +++ b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java @@ -18,6 +18,23 @@ */ package org.apache.thrift.async; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.ServerTestBase; @@ -35,363 +52,358 @@ import thrift.test.ExceptionWithAMap; import thrift.test.Srv; import thrift.test.Srv.Iface; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class TestTAsyncClientManager { - private THsHaServer server_; - private Thread serverThread_; - private TAsyncClientManager clientManager_; - - @BeforeEach - public void setUp() throws Exception { - server_ = new THsHaServer(new Args(new TNonblockingServerSocket( - new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(ServerTestBase.PORT))). - processor(new Srv.Processor(new SrvHandler()))); - serverThread_ = new Thread(new Runnable() { - public void run() { + private THsHaServer server_; + private Thread serverThread_; + private TAsyncClientManager clientManager_; + + @BeforeEach + public void setUp() throws Exception { + server_ = + new THsHaServer( + new Args( + new TNonblockingServerSocket( + new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs() + .port(ServerTestBase.PORT))) + .processor(new Srv.Processor(new SrvHandler()))); + serverThread_ = + new Thread( + new Runnable() { + public void run() { server_.serve(); - } - }); - serverThread_.start(); - clientManager_ = new TAsyncClientManager(); - Thread.sleep(500); - } - - @AfterEach - public void tearDown() throws Exception { - server_.stop(); - clientManager_.stop(); - serverThread_.join(); - } - - @Test - public void testBasicCall() throws Exception { - Srv.AsyncClient client = getClient(); - basicCall(client); - } - - @Test - public void testBasicCallWithTimeout() throws Exception { - Srv.AsyncClient client = getClient(); - client.setTimeout(5000); - basicCall(client); - } - - private static abstract class ErrorCallTest<C extends TAsyncClient, R> { - final void runTest() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference<Exception> error = new AtomicReference<Exception>(); - C client = executeErroringCall(new AsyncMethodCallback<R>() { + } + }); + serverThread_.start(); + clientManager_ = new TAsyncClientManager(); + Thread.sleep(500); + } + + @AfterEach + public void tearDown() throws Exception { + server_.stop(); + clientManager_.stop(); + serverThread_.join(); + } + + @Test + public void testBasicCall() throws Exception { + Srv.AsyncClient client = getClient(); + basicCall(client); + } + + @Test + public void testBasicCallWithTimeout() throws Exception { + Srv.AsyncClient client = getClient(); + client.setTimeout(5000); + basicCall(client); + } + + private abstract static class ErrorCallTest<C extends TAsyncClient, R> { + final void runTest() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicReference<Exception> error = new AtomicReference<Exception>(); + C client = + executeErroringCall( + new AsyncMethodCallback<R>() { @Override public void onComplete(R response) { - latch.countDown(); + latch.countDown(); } @Override public void onError(Exception exception) { - error.set(exception); - latch.countDown(); + error.set(exception); + latch.countDown(); } - }); - latch.await(2, TimeUnit.SECONDS); - assertTrue(client.hasError()); - Exception exception = error.get(); - assertNotNull(exception); - assertSame(exception, client.getError()); - validateError(client, exception); - } - - /** - * Executes a call that is expected to raise an exception. - * - * @param callback The testing callback that should be installed. - * @return The client the call was made against. - * @throws Exception if there was a problem setting up the client or making the call. - */ - abstract C executeErroringCall(AsyncMethodCallback<R> callback) throws Exception; - - /** - * Further validates the properties of the error raised in the remote call and the state of the - * client after that call. - * - * @param client The client returned from {@link #executeErroringCall(AsyncMethodCallback)}. - * @param error The exception raised by the remote call. - */ - abstract void validateError(C client, Exception error); - } - - @Test - public void testUnexpectedRemoteExceptionCall() throws Exception { - new ErrorCallTest<Srv.AsyncClient, Boolean>() { - @Override - Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { - Srv.AsyncClient client = getClient(); - client.declaredExceptionMethod(false, callback); - return client; - } - - @Override - void validateError(Srv.AsyncClient client, Exception error) { - assertFalse(client.hasTimeout()); - assertTrue(error instanceof TException); - } - }.runTest(); - } - - @Test - public void testDeclaredRemoteExceptionCall() throws Exception { - new ErrorCallTest<Srv.AsyncClient, Boolean>() { - @Override - Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { - Srv.AsyncClient client = getClient(); - client.declaredExceptionMethod(true, callback); - return client; - } - - @Override - void validateError(Srv.AsyncClient client, Exception error) { - assertFalse(client.hasTimeout()); - assertEquals(ExceptionWithAMap.class, error.getClass()); - ExceptionWithAMap exceptionWithAMap = (ExceptionWithAMap) error; - assertEquals("blah", exceptionWithAMap.getBlah()); - assertEquals(new HashMap<String, String>(), exceptionWithAMap.getMap_field()); - } - }.runTest(); + }); + latch.await(2, TimeUnit.SECONDS); + assertTrue(client.hasError()); + Exception exception = error.get(); + assertNotNull(exception); + assertSame(exception, client.getError()); + validateError(client, exception); } - @Test - public void testTimeoutCall() throws Exception { - new ErrorCallTest<Srv.AsyncClient, Integer>() { - @Override - Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Integer> callback) throws Exception { - Srv.AsyncClient client = getClient(); - client.setTimeout(100); - client.primitiveMethod(callback); - return client; - } - - @Override - void validateError(Srv.AsyncClient client, Exception error) { - assertTrue(client.hasTimeout()); - assertTrue(error instanceof TimeoutException); - } - }.runTest(); - } - - @Test - public void testVoidCall() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); + /** + * Executes a call that is expected to raise an exception. + * + * @param callback The testing callback that should be installed. + * @return The client the call was made against. + * @throws Exception if there was a problem setting up the client or making the call. + */ + abstract C executeErroringCall(AsyncMethodCallback<R> callback) throws Exception; + + /** + * Further validates the properties of the error raised in the remote call and the state of the + * client after that call. + * + * @param client The client returned from {@link #executeErroringCall(AsyncMethodCallback)}. + * @param error The exception raised by the remote call. + */ + abstract void validateError(C client, Exception error); + } + + @Test + public void testUnexpectedRemoteExceptionCall() throws Exception { + new ErrorCallTest<Srv.AsyncClient, Boolean>() { + @Override + Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { Srv.AsyncClient client = getClient(); - client.voidMethod(new FailureLessCallback<Void>() { - @Override - public void onComplete(Void response) { - returned.set(true); - latch.countDown(); - } - }); - latch.await(1, TimeUnit.SECONDS); - assertTrue(returned.get()); - } - - @Test - public void testOnewayCall() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); + client.declaredExceptionMethod(false, callback); + return client; + } + + @Override + void validateError(Srv.AsyncClient client, Exception error) { + assertFalse(client.hasTimeout()); + assertTrue(error instanceof TException); + } + }.runTest(); + } + + @Test + public void testDeclaredRemoteExceptionCall() throws Exception { + new ErrorCallTest<Srv.AsyncClient, Boolean>() { + @Override + Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { Srv.AsyncClient client = getClient(); - client.onewayMethod(new FailureLessCallback<Void>() { - @Override - public void onComplete(Void response) { - returned.set(true); - latch.countDown(); - } + client.declaredExceptionMethod(true, callback); + return client; + } + + @Override + void validateError(Srv.AsyncClient client, Exception error) { + assertFalse(client.hasTimeout()); + assertEquals(ExceptionWithAMap.class, error.getClass()); + ExceptionWithAMap exceptionWithAMap = (ExceptionWithAMap) error; + assertEquals("blah", exceptionWithAMap.getBlah()); + assertEquals(new HashMap<String, String>(), exceptionWithAMap.getMap_field()); + } + }.runTest(); + } + + @Test + public void testTimeoutCall() throws Exception { + new ErrorCallTest<Srv.AsyncClient, Integer>() { + @Override + Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Integer> callback) throws Exception { + Srv.AsyncClient client = getClient(); + client.setTimeout(100); + client.primitiveMethod(callback); + return client; + } + + @Override + void validateError(Srv.AsyncClient client, Exception error) { + assertTrue(client.hasTimeout()); + assertTrue(error instanceof TimeoutException); + } + }.runTest(); + } + + @Test + public void testVoidCall() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + Srv.AsyncClient client = getClient(); + client.voidMethod( + new FailureLessCallback<Void>() { + @Override + public void onComplete(Void response) { + returned.set(true); + latch.countDown(); + } }); - latch.await(1, TimeUnit.SECONDS); - assertTrue(returned.get()); + latch.await(1, TimeUnit.SECONDS); + assertTrue(returned.get()); + } + + @Test + public void testOnewayCall() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + Srv.AsyncClient client = getClient(); + client.onewayMethod( + new FailureLessCallback<Void>() { + @Override + public void onComplete(Void response) { + returned.set(true); + latch.countDown(); + } + }); + latch.await(1, TimeUnit.SECONDS); + assertTrue(returned.get()); + } + + @Test + public void testParallelCalls() throws Exception { + // make multiple calls with deserialization in the selector thread (repro Eric's issue) + int numThreads = 50; + int numCallsPerThread = 100; + List<JankyRunnable> runnables = new ArrayList<JankyRunnable>(); + List<Thread> threads = new ArrayList<Thread>(); + for (int i = 0; i < numThreads; i++) { + JankyRunnable runnable = new JankyRunnable(numCallsPerThread); + Thread thread = new Thread(runnable); + thread.start(); + threads.add(thread); + runnables.add(runnable); } - - @Test - public void testParallelCalls() throws Exception { - // make multiple calls with deserialization in the selector thread (repro Eric's issue) - int numThreads = 50; - int numCallsPerThread = 100; - List<JankyRunnable> runnables = new ArrayList<JankyRunnable>(); - List<Thread> threads = new ArrayList<Thread>(); - for (int i = 0; i < numThreads; i++) { - JankyRunnable runnable = new JankyRunnable(numCallsPerThread); - Thread thread = new Thread(runnable); - thread.start(); - threads.add(thread); - runnables.add(runnable); - } - for (Thread thread : threads) { - thread.join(); - } - int numSuccesses = 0; - for (JankyRunnable runnable : runnables) { - numSuccesses += runnable.getNumSuccesses(); - } - assertEquals(numThreads * numCallsPerThread, numSuccesses); + for (Thread thread : threads) { + thread.join(); } - - private Srv.AsyncClient getClient() throws IOException, TTransportException { - TNonblockingSocket clientSocket = new TNonblockingSocket(ServerTestBase.HOST, ServerTestBase.PORT); - return new Srv.AsyncClient(new TBinaryProtocol.Factory(), clientManager_, clientSocket); + int numSuccesses = 0; + for (JankyRunnable runnable : runnables) { + numSuccesses += runnable.getNumSuccesses(); } - - private void basicCall(Srv.AsyncClient client) throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); - client.Janky(1, new FailureLessCallback<Integer>() { - @Override - public void onComplete(Integer response) { - assertEquals(3, response.intValue()); - returned.set(true); - latch.countDown(); - } - - @Override - public void onError(Exception exception) { - try { - StringWriter sink = new StringWriter(); - exception.printStackTrace(new PrintWriter(sink, true)); - Assertions.fail("unexpected onError with exception " + sink.toString()); - } finally { - latch.countDown(); - } + assertEquals(numThreads * numCallsPerThread, numSuccesses); + } + + private Srv.AsyncClient getClient() throws IOException, TTransportException { + TNonblockingSocket clientSocket = + new TNonblockingSocket(ServerTestBase.HOST, ServerTestBase.PORT); + return new Srv.AsyncClient(new TBinaryProtocol.Factory(), clientManager_, clientSocket); + } + + private void basicCall(Srv.AsyncClient client) throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + client.Janky( + 1, + new FailureLessCallback<Integer>() { + @Override + public void onComplete(Integer response) { + assertEquals(3, response.intValue()); + returned.set(true); + latch.countDown(); + } + + @Override + public void onError(Exception exception) { + try { + StringWriter sink = new StringWriter(); + exception.printStackTrace(new PrintWriter(sink, true)); + Assertions.fail("unexpected onError with exception " + sink.toString()); + } finally { + latch.countDown(); } + } }); - latch.await(100, TimeUnit.SECONDS); - assertTrue(returned.get()); + latch.await(100, TimeUnit.SECONDS); + assertTrue(returned.get()); + } + + public static class SrvHandler implements Iface { + // Use this method for a standard call testing + @Override + public int Janky(int arg) throws TException { + assertEquals(1, arg); + return 3; } - public static class SrvHandler implements Iface { - // Use this method for a standard call testing - @Override - public int Janky(int arg) throws TException { - assertEquals(1, arg); - return 3; - } - - // Using this method for timeout testing - sleeps for 1 second before returning - @Override - public int primitiveMethod() throws TException { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return 0; - } + // Using this method for timeout testing - sleeps for 1 second before returning + @Override + public int primitiveMethod() throws TException { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return 0; + } - @Override - public void methodWithDefaultArgs(int something) throws TException { - } + @Override + public void methodWithDefaultArgs(int something) throws TException {} - @Override - public CompactProtoTestStruct structMethod() throws TException { - return null; - } + @Override + public CompactProtoTestStruct structMethod() throws TException { + return null; + } - @Override - public void voidMethod() throws TException { - } + @Override + public void voidMethod() throws TException {} - @Override - public void onewayMethod() throws TException { - } + @Override + public void onewayMethod() throws TException {} - @Override - public boolean declaredExceptionMethod(boolean shouldThrowDeclared) throws TException { - if (shouldThrowDeclared) { - throw new ExceptionWithAMap("blah", new HashMap<String, String>()); - } else { - throw new TException("Unexpected!"); - } - } + @Override + public boolean declaredExceptionMethod(boolean shouldThrowDeclared) throws TException { + if (shouldThrowDeclared) { + throw new ExceptionWithAMap("blah", new HashMap<String, String>()); + } else { + throw new TException("Unexpected!"); + } } + } - private static abstract class FailureLessCallback<T> implements AsyncMethodCallback<T> { - @Override - public void onError(Exception exception) { - fail(exception); - } + private abstract static class FailureLessCallback<T> implements AsyncMethodCallback<T> { + @Override + public void onError(Exception exception) { + fail(exception); + } + } + + private static void fail(Exception exception) { + StringWriter sink = new StringWriter(); + exception.printStackTrace(new PrintWriter(sink, true)); + Assertions.fail("unexpected error " + sink); + } + + private class JankyRunnable implements Runnable { + private final int numCalls_; + private int numSuccesses_ = 0; + private final Srv.AsyncClient client_; + + public JankyRunnable(int numCalls) throws Exception { + numCalls_ = numCalls; + client_ = getClient(); + client_.setTimeout(20000); } - private static void fail(Exception exception) { - StringWriter sink = new StringWriter(); - exception.printStackTrace(new PrintWriter(sink, true)); - Assertions.fail("unexpected error " + sink); + public int getNumSuccesses() { + return numSuccesses_; } - private class JankyRunnable implements Runnable { - private final int numCalls_; - private int numSuccesses_ = 0; - private final Srv.AsyncClient client_; + public void run() { + for (int i = 0; i < numCalls_ && !client_.hasError(); i++) { + final int iteration = i; + try { + // connect an async client + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + client_.Janky( + 1, + new AsyncMethodCallback<Integer>() { - public JankyRunnable(int numCalls) throws Exception { - numCalls_ = numCalls; - client_ = getClient(); - client_.setTimeout(20000); - } - - public int getNumSuccesses() { - return numSuccesses_; - } + @Override + public void onComplete(Integer result) { + assertEquals(3, result.intValue()); + returned.set(true); + latch.countDown(); + } - public void run() { - for (int i = 0; i < numCalls_ && !client_.hasError(); i++) { - final int iteration = i; - try { - // connect an async client - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); - client_.Janky(1, new AsyncMethodCallback<Integer>() { - - @Override - public void onComplete(Integer result) { - assertEquals(3, result.intValue()); - returned.set(true); - latch.countDown(); - } - - @Override - public void onError(Exception exception) { - try { - StringWriter sink = new StringWriter(); - exception.printStackTrace(new PrintWriter(sink, true)); - Assertions.fail("unexpected onError on iteration " + iteration + ": " + sink.toString()); - } finally { - latch.countDown(); - } - } - }); - - boolean calledBack = latch.await(30, TimeUnit.SECONDS); - assertTrue(calledBack, "wasn't called back in time on iteration " + iteration); - assertTrue(returned.get(), "onComplete not called on iteration " + iteration); - this.numSuccesses_++; - } catch (Exception e) { - fail(e); + @Override + public void onError(Exception exception) { + try { + StringWriter sink = new StringWriter(); + exception.printStackTrace(new PrintWriter(sink, true)); + Assertions.fail( + "unexpected onError on iteration " + iteration + ": " + sink.toString()); + } finally { + latch.countDown(); + } } - } + }); + + boolean calledBack = latch.await(30, TimeUnit.SECONDS); + assertTrue(calledBack, "wasn't called back in time on iteration " + iteration); + assertTrue(returned.get(), "onComplete not called on iteration " + iteration); + this.numSuccesses_++; + } catch (Exception e) { + fail(e); } + } } + } } diff --git a/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java b/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java index 152bf4851..3cca54d28 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java @@ -19,16 +19,14 @@ package org.apache.thrift.partial; -import org.apache.thrift.TEnum; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -/** - * Test ThriftCodec serializes and deserializes thrift objects correctly. - */ +import org.apache.thrift.TEnum; +import org.junit.jupiter.api.Test; + +/** Test ThriftCodec serializes and deserializes thrift objects correctly. */ public class EnumCacheTest { enum TestEnum implements TEnum { @@ -54,7 +52,7 @@ public class EnumCacheTest { public static final NotEnum Bob = new NotEnum(10); public static final NotEnum Charlie = new NotEnum(11); - private static final NotEnum[] allValues = { Alice, Bob, Charlie }; + private static final NotEnum[] allValues = {Alice, Bob, Charlie}; private int value; @@ -86,9 +84,7 @@ public class EnumCacheTest { // Verify it throws. assertThrows( - IllegalArgumentException.class, - () -> cache.get(null, 1), - "'enumClass' must not be null"); + IllegalArgumentException.class, () -> cache.get(null, 1), "'enumClass' must not be null"); } @Test diff --git a/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java b/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java index 4498e332a..1888b59b4 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java @@ -19,18 +19,17 @@ package org.apache.thrift.partial; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertTrue; - public class PartialThriftComparerTest { private ThriftSerDe serde; diff --git a/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftTestData.java b/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftTestData.java index 6376075da..14cada1e7 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftTestData.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftTestData.java @@ -28,12 +28,10 @@ import java.util.List; import java.util.Map; import java.util.Set; -/** - * Helpers for creating test data related to partial deserialization. - */ +/** Helpers for creating test data related to partial deserialization. */ public class PartialThriftTestData { - public final byte[] BYTES = new byte[] { 1, 2, 3 }; + public final byte[] BYTES = new byte[] {1, 2, 3}; public SmallStruct createSmallStruct(int id) { return new SmallStruct() @@ -48,16 +46,17 @@ public class PartialThriftTestData { public TestStruct createTestStruct(int id, int numItems) { - TestStruct ts = new TestStruct() - .setByteField((byte) id) - .setI16Field((short) id) - .setI32Field(id) - .setI64Field(id) - .setDoubleField(id) - .setStringField(Integer.toString(id)) - .setEnumField(TstEnum.E_ONE) - .setBinaryField(BYTES) - .setStructField(createSmallStruct(id)); + TestStruct ts = + new TestStruct() + .setByteField((byte) id) + .setI16Field((short) id) + .setI32Field(id) + .setI64Field(id) + .setDoubleField(id) + .setStringField(Integer.toString(id)) + .setEnumField(TstEnum.E_ONE) + .setBinaryField(BYTES) + .setStructField(createSmallStruct(id)); initListFields(ts, id, numItems); initSetFields(ts, id, numItems); @@ -85,7 +84,7 @@ public class PartialThriftTestData { byteList.add((byte) i); i16List.add((short) i); i32List.add(i); - i64List.add((long)i); + i64List.add((long) i); doubleList.add((double) i); stringList.add(Integer.toString(i)); enumList.add(TstEnum.E_ONE); @@ -141,7 +140,7 @@ public class PartialThriftTestData { byteSet.add((byte) i); i16Set.add((short) i); i32Set.add(i); - i64Set.add((long)i); + i64Set.add((long) i); doubleSet.add((double) i); stringSet.add(Integer.toString(i)); enumSet.add(TstEnum.E_ONE); @@ -234,78 +233,76 @@ public class PartialThriftTestData { } public List<String> allFieldsOfTestStruct() { - return new ArrayList<>( - Arrays.asList( - "byteField", - "i16Field", - "i32Field", - "i64Field", - "doubleField", - "stringField", - "structField.byteField", - "structField.i16Field", - "structField.i32Field", - "structField.i64Field", - "structField.doubleField", - "structField.stringField", - "structField.enumField", - "enumField", - "binaryField", - "byteList", - "i16List", - "i32List", - "i64List", - "doubleList", - "stringList", - "enumList", - "listList", - "setList", - "mapList", - "structList.byteField", - "structList.i16Field", - "structList.i32Field", - "structList.i64Field", - "structList.doubleField", - "structList.stringField", - "structList.enumField", - "binaryList", - "byteSet", - "i16Set", - "i32Set", - "i64Set", - "doubleSet", - "stringSet", - "enumSet", - "listSet", - "setSet", - "mapSet", - "structSet.byteField", - "structSet.i16Field", - "structSet.i32Field", - "structSet.i64Field", - "structSet.doubleField", - "structSet.stringField", - "structSet.enumField", - "binarySet", - "byteMap", - "i16Map", - "i32Map", - "i64Map", - "doubleMap", - "stringMap", - "enumMap", - "listMap", - "setMap", - "mapMap", - "structMap.byteField", - "structMap.i16Field", - "structMap.i32Field", - "structMap.i64Field", - "structMap.doubleField", - "structMap.stringField", - "structMap.enumField", - "binaryMap" - ) - ); + return new ArrayList<>( + Arrays.asList( + "byteField", + "i16Field", + "i32Field", + "i64Field", + "doubleField", + "stringField", + "structField.byteField", + "structField.i16Field", + "structField.i32Field", + "structField.i64Field", + "structField.doubleField", + "structField.stringField", + "structField.enumField", + "enumField", + "binaryField", + "byteList", + "i16List", + "i32List", + "i64List", + "doubleList", + "stringList", + "enumList", + "listList", + "setList", + "mapList", + "structList.byteField", + "structList.i16Field", + "structList.i32Field", + "structList.i64Field", + "structList.doubleField", + "structList.stringField", + "structList.enumField", + "binaryList", + "byteSet", + "i16Set", + "i32Set", + "i64Set", + "doubleSet", + "stringSet", + "enumSet", + "listSet", + "setSet", + "mapSet", + "structSet.byteField", + "structSet.i16Field", + "structSet.i32Field", + "structSet.i64Field", + "structSet.doubleField", + "structSet.stringField", + "structSet.enumField", + "binarySet", + "byteMap", + "i16Map", + "i32Map", + "i64Map", + "doubleMap", + "stringMap", + "enumMap", + "listMap", + "setMap", + "mapMap", + "structMap.byteField", + "structMap.i16Field", + "structMap.i32Field", + "structMap.i64Field", + "structMap.doubleField", + "structMap.stringField", + "structMap.enumField", + "binaryMap")); } } diff --git a/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java b/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java index 860f515dd..b4b6c87e4 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java @@ -19,12 +19,12 @@ package org.apache.thrift.partial; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.thrift.protocol.TField; import org.apache.thrift.protocol.TType; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class TFieldDataTest { @Test diff --git a/lib/java/src/test/java/org/apache/thrift/partial/TestData.java b/lib/java/src/test/java/org/apache/thrift/partial/TestData.java index 1779346f7..dc511d8b8 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/TestData.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/TestData.java @@ -23,35 +23,32 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -/** - * Frequently used test data items. - */ +/** Frequently used test data items. */ public final class TestData { private TestData() {} - // Array data. - public static Object[] nullArray = null; - public static Object[] emptyArray = new Object[0]; + public static Object[] nullArray = null; + public static Object[] emptyArray = new Object[0]; public static Object[] nonEmptyArray = new Object[1]; - public static byte[] nullByteArray = null; - public static byte[] emptyByteArray = new byte[0]; - public static byte[] nonEmptyByteArray = new byte[1]; + public static byte[] nullByteArray = null; + public static byte[] emptyByteArray = new byte[0]; + public static byte[] nonEmptyByteArray = new byte[1]; - public static short[] nullShortArray = null; - public static short[] emptyShortArray = new short[0]; + public static short[] nullShortArray = null; + public static short[] emptyShortArray = new short[0]; public static short[] nonEmptyShortArray = new short[1]; - public static int[] nullIntArray = null; - public static int[] emptyIntArray = new int[0]; - public static int[] nonEmptyIntArray = new int[1]; + public static int[] nullIntArray = null; + public static int[] emptyIntArray = new int[0]; + public static int[] nonEmptyIntArray = new int[1]; - public static long[] nullLongArray = null; - public static long[] emptyLongArray = new long[0]; - public static long[] nonEmptyLongArray = new long[1]; + public static long[] nullLongArray = null; + public static long[] emptyLongArray = new long[0]; + public static long[] nonEmptyLongArray = new long[1]; - public static List<Object> nullList = null; + public static List<Object> nullList = null; public static List<Object> emptyList = new ArrayList<Object>(); public static List<Object> validList = Arrays.asList(new Object[1]); } diff --git a/lib/java/src/test/java/org/apache/thrift/partial/TestPartialThriftDeserializer.java b/lib/java/src/test/java/org/apache/thrift/partial/TestPartialThriftDeserializer.java index 722e108ad..e5bdd0fb1 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/TestPartialThriftDeserializer.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/TestPartialThriftDeserializer.java @@ -19,11 +19,12 @@ package org.apache.thrift.partial; -import org.apache.thrift.TDeserializer; -import org.apache.thrift.TException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TCompactProtocol; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.ByteBuffer; @@ -36,13 +37,11 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.thrift.TDeserializer; +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TCompactProtocol; +import org.junit.jupiter.api.Test; public class TestPartialThriftDeserializer { @@ -52,8 +51,7 @@ public class TestPartialThriftDeserializer { private PartialThriftTestData testData = new PartialThriftTestData(); - public TestPartialThriftDeserializer() throws TException { - } + public TestPartialThriftDeserializer() throws TException {} @Test public void testArgChecks() throws TException { @@ -79,8 +77,8 @@ public class TestPartialThriftDeserializer { } /** - * This test does not use partial deserialization. It is used to establish correctness - * of full serialization used in the other tests. + * This test does not use partial deserialization. It is used to establish correctness of full + * serialization used in the other tests. */ @Test public void testRoundTripFull() throws TException { @@ -89,7 +87,7 @@ public class TestPartialThriftDeserializer { byte[] bytesBinary = serde.serializeBinary(ts1); byte[] bytesCompact = serde.serializeCompact(ts1); - TestStruct ts2 = serde.deserializeBinary(bytesBinary, TestStruct.class); + TestStruct ts2 = serde.deserializeBinary(bytesBinary, TestStruct.class); assertEquals(ts1, ts2); ts2 = serde.deserializeCompact(bytesCompact, TestStruct.class); @@ -140,62 +138,61 @@ public class TestPartialThriftDeserializer { byte[] bytesBinary = serde.serializeBinary(ts1); byte[] bytesCompact = serde.serializeCompact(ts1); - List<String> fieldNames = Arrays.asList( - "byteField", - "i16Field", - "i32Field", - "i64Field", - "doubleField", - "stringField", - - "enumField", - "binaryField", - - // List fields - "byteList", - "i16List", - "i32List", - "i64List", - "doubleList", - "stringList", - "enumList", - "listList", - "setList", - "mapList", - "structList", - "binaryList", - - // Set fields - "byteSet", - "i16Set", - "i32Set", - "i64Set", - "doubleSet", - "stringSet", - "enumSet", - "listSet", - "setSet", - "mapSet", - "structSet", - "binarySet", - - // Map fields - "byteMap", - "i16Map", - "i32Map", - "i64Map", - "doubleMap", - "stringMap", - "enumMap", - "listMap", - "setMap", - "mapMap", - "structMap", - "binaryMap", - - // Struct field - "structField" - ); + List<String> fieldNames = + Arrays.asList( + "byteField", + "i16Field", + "i32Field", + "i64Field", + "doubleField", + "stringField", + "enumField", + "binaryField", + + // List fields + "byteList", + "i16List", + "i32List", + "i64List", + "doubleList", + "stringList", + "enumList", + "listList", + "setList", + "mapList", + "structList", + "binaryList", + + // Set fields + "byteSet", + "i16Set", + "i32Set", + "i64Set", + "doubleSet", + "stringSet", + "enumSet", + "listSet", + "setSet", + "mapSet", + "structSet", + "binarySet", + + // Map fields + "byteMap", + "i16Map", + "i32Map", + "i64Map", + "doubleMap", + "stringMap", + "enumMap", + "listMap", + "setMap", + "mapMap", + "structMap", + "binaryMap", + + // Struct field + "structField"); StringBuilder sb = new StringBuilder(); TDeserializer partialBinaryDeserializer = new TDeserializer(TestStruct.class, fieldNames, binaryProtocolFactory); @@ -381,15 +378,15 @@ public class TestPartialThriftDeserializer { for (int i = 0; i < numItems; i++) { if (clasz == Byte.class) { - assertTrue(set.contains((byte)i)); + assertTrue(set.contains((byte) i)); } else if (clasz == Short.class) { - assertTrue(set.contains((short)i)); + assertTrue(set.contains((short) i)); } else if (clasz == Integer.class) { assertTrue(set.contains(i)); } else if (clasz == Long.class) { - assertTrue(set.contains((long)i)); + assertTrue(set.contains((long) i)); } else if (clasz == Double.class) { - assertTrue(set.contains((double)i)); + assertTrue(set.contains((double) i)); } } } @@ -472,19 +469,19 @@ public class TestPartialThriftDeserializer { for (int i = 0; i < numItems; i++) { if (clasz == Byte.class) { - assertTrue(map.containsKey((byte)i)); + assertTrue(map.containsKey((byte) i)); assertEquals((byte) i, map.get((byte) i)); } else if (clasz == Short.class) { - assertTrue(map.containsKey((short)i)); + assertTrue(map.containsKey((short) i)); assertEquals((short) i, map.get((short) i)); } else if (clasz == Integer.class) { assertTrue(map.containsKey(i)); assertEquals(i, map.get(i)); } else if (clasz == Long.class) { - assertTrue(map.containsKey((long)i)); + assertTrue(map.containsKey((long) i)); assertEquals((long) i, map.get((long) i)); } else if (clasz == Double.class) { - assertTrue(map.containsKey((double)i)); + assertTrue(map.containsKey((double) i)); assertEquals((double) i, map.get((double) i)); } } diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java index 115726ed0..0e0f1a669 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java @@ -19,18 +19,16 @@ package org.apache.thrift.partial; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; public class ThriftFieldTest { @@ -46,9 +44,9 @@ public class ThriftFieldTest { // Verify it throws. assertThrows( - IllegalArgumentException.class, - () -> new ThriftField(null, Collections.emptyList()), - "'name' must not be null"); + IllegalArgumentException.class, + () -> new ThriftField(null, Collections.emptyList()), + "'name' must not be null"); assertThrows( IllegalArgumentException.class, @@ -68,13 +66,8 @@ public class ThriftFieldTest { @Test public void testFromNames() { - List<String> fieldNames = Arrays.asList( - "f1", - "f2.f21", - "f3.f31.f311", - "f3.f32.f321", - "f3.f32.f322" - ); + List<String> fieldNames = + Arrays.asList("f1", "f2.f21", "f3.f31.f311", "f3.f32.f321", "f3.f32.f322"); List<ThriftField> testFields = ThriftField.fromNames(fieldNames); @@ -113,16 +106,10 @@ public class ThriftFieldTest { assertEquals(0, f322.fields.size()); } - @Test public void testEquality() { - List<String> fieldNames = Arrays.asList( - "f1", - "f2.f21", - "f3.f31.f311", - "f3.f32.f321", - "f3.f32.f322" - ); + List<String> fieldNames = + Arrays.asList("f1", "f2.f21", "f3.f31.f311", "f3.f32.f321", "f3.f32.f322"); List<ThriftField> testFields = ThriftField.fromNames(fieldNames); List<ThriftField> testFields2 = testFields; @@ -135,13 +122,8 @@ public class ThriftFieldTest { assertEquals(testFields, testFields3); assertEquals(testFields.hashCode(), testFields3.hashCode()); - List<String> fieldNamesDiff = Arrays.asList( - "f1", - "f2.f21", - "f3.f31.f311", - "f3.f32.f323", - "f3.f32.f322" - ); + List<String> fieldNamesDiff = + Arrays.asList("f1", "f2.f21", "f3.f31.f311", "f3.f32.f323", "f3.f32.f322"); List<ThriftField> testFields4 = ThriftField.fromNames(fieldNamesDiff); assertNotSame(testFields, testFields4); diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java index f47657245..5180578b4 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java @@ -19,6 +19,15 @@ package org.apache.thrift.partial; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; import org.apache.thrift.TBase; import org.apache.thrift.meta_data.EnumMetaData; import org.apache.thrift.meta_data.FieldValueMetaData; @@ -29,16 +38,6 @@ import org.apache.thrift.meta_data.StructMetaData; import org.apache.thrift.protocol.TType; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class ThriftMetadataTest { private PartialThriftTestData testData = new PartialThriftTestData(); @@ -122,9 +121,7 @@ public class ThriftMetadataTest { } private ThriftMetadata.ThriftObject validateBasicFieldMetadata( - ThriftMetadata.ThriftStruct testStruct, - int id, - String fieldName) { + ThriftMetadata.ThriftStruct testStruct, int id, String fieldName) { return validateBasicFieldMetadata(testStruct, TestStruct.class, id, fieldName); } @@ -153,17 +150,14 @@ public class ThriftMetadataTest { } private void validateBasicFieldValueMetadata( - ThriftMetadata.ThriftObject fieldMetadata, - String fieldName, - byte ttype) { + ThriftMetadata.ThriftObject fieldMetadata, String fieldName, byte ttype) { assertEquals(ttype, fieldMetadata.data.valueMetaData.type); assertEquals(getMetaDataClassForTType(ttype), fieldMetadata.data.valueMetaData.getClass()); Class<? extends ThriftMetadata.ThriftObject> fieldMetadataClass = getClassForTType(ttype); assertEquals(fieldMetadataClass, fieldMetadata.getClass()); if (fieldMetadataClass == ThriftMetadata.ThriftPrimitive.class) { - ThriftMetadata.ThriftPrimitive primitive - = (ThriftMetadata.ThriftPrimitive) fieldMetadata; + ThriftMetadata.ThriftPrimitive primitive = (ThriftMetadata.ThriftPrimitive) fieldMetadata; if (fieldName.startsWith("binary") && (ttype == TType.STRING)) { assertTrue(primitive.isBinary()); } else { @@ -173,10 +167,7 @@ public class ThriftMetadataTest { } private void validateFieldMetadata( - ThriftMetadata.ThriftStruct testStruct, - int id, - String fieldName, - byte ttype) { + ThriftMetadata.ThriftStruct testStruct, int id, String fieldName, byte ttype) { ThriftMetadata.ThriftObject fieldMetadata = validateBasicFieldMetadata(testStruct, id, fieldName); @@ -184,10 +175,7 @@ public class ThriftMetadataTest { } private void validateListFieldMetadata( - ThriftMetadata.ThriftStruct testStruct, - int id, - String fieldName, - byte ttype) { + ThriftMetadata.ThriftStruct testStruct, int id, String fieldName, byte ttype) { ThriftMetadata.ThriftObject fieldMetadata = validateBasicFieldMetadata(testStruct, id, fieldName); @@ -199,10 +187,7 @@ public class ThriftMetadataTest { } private void validateSetFieldMetadata( - ThriftMetadata.ThriftStruct testStruct, - int id, - String fieldName, - byte ttype) { + ThriftMetadata.ThriftStruct testStruct, int id, String fieldName, byte ttype) { ThriftMetadata.ThriftObject fieldMetadata = validateBasicFieldMetadata(testStruct, id, fieldName); @@ -234,7 +219,7 @@ public class ThriftMetadataTest { private Class<? extends FieldValueMetaData> getMetaDataClassForTType(byte ttype) { switch (ttype) { case TType.STRUCT: - return StructMetaData.class; + return StructMetaData.class; case TType.LIST: return ListMetaData.class; @@ -265,7 +250,7 @@ public class ThriftMetadataTest { private Class<? extends ThriftMetadata.ThriftObject> getClassForTType(byte ttype) { switch (ttype) { case TType.STRUCT: - return ThriftMetadata.ThriftStruct.class; + return ThriftMetadata.ThriftStruct.class; case TType.LIST: return ThriftMetadata.ThriftList.class; diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java index a8b0dac8f..210263f1e 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java @@ -19,10 +19,13 @@ package org.apache.thrift.partial; -import org.apache.thrift.TBase; -import org.apache.thrift.TException; -import org.apache.thrift.TFieldIdEnum; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -34,14 +37,10 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.thrift.TBase; +import org.apache.thrift.TException; +import org.apache.thrift.TFieldIdEnum; +import org.junit.jupiter.api.Test; public class ThriftStructProcessorTest { @@ -160,18 +159,17 @@ public class ThriftStructProcessorTest { @Test public void testStructPrimitiveFields() throws TException { - List<ThriftField> fields = ThriftField.fromNames( - Arrays.asList( - "byteField", - "i16Field", - "i32Field", - "i64Field", - "doubleField", - "stringField", - - "enumField", - "binaryField" - )); + List<ThriftField> fields = + ThriftField.fromNames( + Arrays.asList( + "byteField", + "i16Field", + "i32Field", + "i64Field", + "doubleField", + "stringField", + "enumField", + "binaryField")); ThriftMetadata.ThriftStruct metadata = ThriftMetadata.ThriftStruct.fromFields(TestStruct.class, fields); @@ -233,20 +231,20 @@ public class ThriftStructProcessorTest { @Test public void testStructContainerFields() throws TException { - List<ThriftField> fields = ThriftField.fromNames( - Arrays.asList( - // List field - "i32List", + List<ThriftField> fields = + ThriftField.fromNames( + Arrays.asList( + // List field + "i32List", - // Set field - "stringSet", + // Set field + "stringSet", - // Map field - "stringMap", + // Map field + "stringMap", - // Struct field - "structField" - )); + // Struct field + "structField")); ThriftMetadata.ThriftStruct metadata = ThriftMetadata.ThriftStruct.fromFields(TestStruct.class, fields); @@ -261,7 +259,7 @@ public class ThriftStructProcessorTest { // list TFieldIdEnum fieldId = findFieldId(metadata, "i32List"); assertNull(getFieldValue(struct, fieldId)); - Integer[] ints = new Integer[] { 1, 2, 3 }; + Integer[] ints = new Integer[] {1, 2, 3}; List<Integer> intList = Arrays.asList(ints); processor.setListField(struct, fieldId, intList); assertArrayEquals(ints, struct.getI32List().toArray()); @@ -269,7 +267,7 @@ public class ThriftStructProcessorTest { // set fieldId = findFieldId(metadata, "stringSet"); assertNull(getFieldValue(struct, fieldId)); - String[] strings = new String[] { "Hello", "World!" }; + String[] strings = new String[] {"Hello", "World!"}; Set<String> stringSet = new HashSet<>(Arrays.asList(strings)); processor.setSetField(struct, fieldId, stringSet); assertEquals(stringSet, struct.getStringSet()); diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java index d2e8eaa18..861d03e19 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java @@ -19,15 +19,14 @@ package org.apache.thrift.partial; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; public class ValidateTest { @Test @@ -212,15 +211,13 @@ public class ValidateTest { assertThrows( IllegalArgumentException.class, () -> Validate.checkNotNullAndNumberOfElements(null, 3, "arg"), - "'arg' must not be null" - ); + "'arg' must not be null"); // Verify it throws. assertThrows( IllegalArgumentException.class, () -> Validate.checkNotNullAndNumberOfElements(Arrays.asList(1, 2), 3, "arg"), - "Number of elements in 'arg' must be exactly 3, 2 given." - ); + "Number of elements in 'arg' must be exactly 3, 2 given."); } @Test @@ -292,7 +289,7 @@ public class ValidateTest { @Test public void testCheckPathExists() throws IOException { Path tempFile = Files.createTempFile("foo", "bar"); - Path tempDir = tempFile.getParent(); + Path tempDir = tempFile.getParent(); Path notFound = Paths.get("<not-found>"); // Should not throw. diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java b/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java index 6b60c99bb..493214fc7 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java @@ -7,18 +7,20 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.thrift.Fixtures; import org.apache.thrift.TException; import org.apache.thrift.transport.TMemoryBuffer; public class BenchmarkProtocols { - private static final Set<TProtocolFactory> FACTORIES = new LinkedHashSet<TProtocolFactory>(){{ - add(new TTupleProtocol.Factory()); - add(new TCompactProtocol.Factory()); - add(new TBinaryProtocol.Factory()); - }}; + private static final Set<TProtocolFactory> FACTORIES = + new LinkedHashSet<TProtocolFactory>() { + { + add(new TTupleProtocol.Factory()); + add(new TCompactProtocol.Factory()); + add(new TBinaryProtocol.Factory()); + } + }; private static final int NUM_REPS = 100000; private static final int NUM_TRIALS = 10; @@ -30,30 +32,29 @@ public class BenchmarkProtocols { for (int i = 0; i < 16; i++) { System.gc(); } -// TProtocol proto = factory.getProtocol(new TTransport() { -// @Override -// public void write(byte[] buf, int off, int len) throws TTransportException { -// } -// -// @Override -// public int read(byte[] buf, int off, int len) throws TTransportException { -// return 0; -// } -// -// @Override -// public void open() throws TTransportException { -// } -// -// @Override -// public boolean isOpen() { -// return true; -// } -// -// @Override -// public void close() { -// } -// }); - + // TProtocol proto = factory.getProtocol(new TTransport() { + // @Override + // public void write(byte[] buf, int off, int len) throws TTransportException { + // } + // + // @Override + // public int read(byte[] buf, int off, int len) throws TTransportException { + // return 0; + // } + // + // @Override + // public void open() throws TTransportException { + // } + // + // @Override + // public boolean isOpen() { + // return true; + // } + // + // @Override + // public void close() { + // } + // }); for (TProtocolFactory factory : FACTORIES) { if (timesByFactory.get(factory) == null) { @@ -62,27 +63,27 @@ public class BenchmarkProtocols { long start = System.currentTimeMillis(); for (int rep = 0; rep < NUM_REPS; rep++) { - TProtocol proto = factory.getProtocol(new TMemoryBuffer(128*1024)); + TProtocol proto = factory.getProtocol(new TMemoryBuffer(128 * 1024)); Fixtures.getCompactProtoTestStruct().write(proto); Fixtures.getNesting().write(proto); } long end = System.currentTimeMillis(); - timesByFactory.get(factory).add(end-start); + timesByFactory.get(factory).add(end - start); } } for (TProtocolFactory factory : FACTORIES) { List<Long> times = timesByFactory.get(factory); -// System.out.println("raw times pre-drop: " + times ); + // System.out.println("raw times pre-drop: " + times ); times.remove(Collections.max(times)); long total = 0; for (long t : times) { total += t; } Collections.sort(times); - System.out.println(factory.getClass().getName() + " average time: " + (total / times.size()) + "ms"); + System.out.println( + factory.getClass().getName() + " average time: " + (total / times.size()) + "ms"); System.out.println("raw times: " + times); } } - } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java b/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java index 8bf5c6e44..a111292d3 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java @@ -18,6 +18,17 @@ */ package org.apache.thrift.protocol; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.thrift.Fixtures; import org.apache.thrift.TBase; import org.apache.thrift.TConfiguration; @@ -35,18 +46,6 @@ import thrift.test.OneOfEach; import thrift.test.Srv; import thrift.test.ThriftTest; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - public abstract class ProtocolTestBase { /** Does it make sense to call methods like writeI32 directly on your protocol? */ @@ -64,17 +63,18 @@ public abstract class ProtocolTestBase { assertEquals(123.456, proto.readDouble()); } - internalTestStructField(new StructFieldTestCase(TType.DOUBLE, (short)15) { - @Override - public void readMethod(TProtocol proto) throws TException { - assertEquals(123.456, proto.readDouble()); - } + internalTestStructField( + new StructFieldTestCase(TType.DOUBLE, (short) 15) { + @Override + public void readMethod(TProtocol proto) throws TException { + assertEquals(123.456, proto.readDouble()); + } - @Override - public void writeMethod(TProtocol proto) throws TException { - proto.writeDouble(123.456); - } - }); + @Override + public void writeMethod(TProtocol proto) throws TException { + proto.writeDouble(123.456); + } + }); } @Test @@ -87,13 +87,15 @@ public abstract class ProtocolTestBase { @Test public void testBinary() throws Exception { - for (byte[] b : Arrays.asList(new byte[0], - new byte[]{0,1,2,3,4,5,6,7,8,9,10}, - new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14}, - new byte[]{0x5D}, - new byte[]{(byte)0xD5,(byte)0x5D}, - new byte[]{(byte)0xFF,(byte)0xD5,(byte)0x5D}, - new byte[128])) { + for (byte[] b : + Arrays.asList( + new byte[0], + new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}, + new byte[] {0x5D}, + new byte[] {(byte) 0xD5, (byte) 0x5D}, + new byte[] {(byte) 0xFF, (byte) 0xD5, (byte) 0x5D}, + new byte[128])) { if (canBeUsedNaked()) { internalTestNakedBinary(b); } @@ -111,9 +113,11 @@ public abstract class ProtocolTestBase { assertEquals(ByteBuffer.wrap(data, 1, 5), proto.readBinary()); } } -@Test + + @Test public void testString() throws Exception { - for (String s : Arrays.asList("", "short", "borderlinetiny", "a bit longer than the smallest possible")) { + for (String s : + Arrays.asList("", "short", "borderlinetiny", "a bit longer than the smallest possible")) { if (canBeUsedNaked()) { internalTestNakedString(s); } @@ -139,7 +143,10 @@ public abstract class ProtocolTestBase { @Test public void testInt() throws Exception { - for (int i : Arrays.asList(0, 1, 7, 150, 15000, 31337, 0xffff, 0xffffff, -1, -7, -150, -15000, -0xffff, -0xffffff)) { + for (int i : + Arrays.asList( + 0, 1, 7, 150, 15000, 31337, 0xffff, 0xffffff, -1, -7, -150, -15000, -0xffff, + -0xffffff)) { if (canBeUsedNaked()) { internalTestNakedI32(i); } @@ -151,9 +158,9 @@ public abstract class ProtocolTestBase { public void testShort() throws Exception { for (int s : Arrays.asList(0, 1, 7, 150, 15000, 0x7fff, -1, -7, -150, -15000, -0x7fff)) { if (canBeUsedNaked()) { - internalTestNakedI16((short)s); + internalTestNakedI16((short) s); } - internalTestI16Field((short)s); + internalTestI16Field((short) s); } } @@ -163,28 +170,29 @@ public abstract class ProtocolTestBase { internalTestNakedByte(); } for (int i = 0; i < 128; i++) { - internalTestByteField((byte)i); - internalTestByteField((byte)-i); + internalTestByteField((byte) i); + internalTestByteField((byte) -i); } } private void internalTestNakedByte() throws Exception { TMemoryBuffer buf = new TMemoryBuffer(1000); TProtocol proto = getFactory().getProtocol(buf); - proto.writeByte((byte)123); + proto.writeByte((byte) 123); assertEquals((byte) 123, proto.readByte()); } private void internalTestByteField(final byte b) throws Exception { - internalTestStructField(new StructFieldTestCase(TType.BYTE, (short)15) { - public void writeMethod(TProtocol proto) throws TException { - proto.writeByte(b); - } + internalTestStructField( + new StructFieldTestCase(TType.BYTE, (short) 15) { + public void writeMethod(TProtocol proto) throws TException { + proto.writeByte(b); + } - public void readMethod(TProtocol proto) throws TException { - assertEquals(b, proto.readByte()); - } - }); + public void readMethod(TProtocol proto) throws TException { + assertEquals(b, proto.readByte()); + } + }); } private void internalTestNakedI16(short n) throws Exception { @@ -195,15 +203,16 @@ public abstract class ProtocolTestBase { } private void internalTestI16Field(final short n) throws Exception { - internalTestStructField(new StructFieldTestCase(TType.I16, (short)15) { - public void writeMethod(TProtocol proto) throws TException { - proto.writeI16(n); - } + internalTestStructField( + new StructFieldTestCase(TType.I16, (short) 15) { + public void writeMethod(TProtocol proto) throws TException { + proto.writeI16(n); + } - public void readMethod(TProtocol proto) throws TException { - assertEquals(n, proto.readI16()); - } - }); + public void readMethod(TProtocol proto) throws TException { + assertEquals(n, proto.readI16()); + } + }); } private void internalTestNakedI32(int n) throws Exception { @@ -214,15 +223,16 @@ public abstract class ProtocolTestBase { } private void internalTestI32Field(final int n) throws Exception { - internalTestStructField(new StructFieldTestCase(TType.I32, (short)15) { - public void writeMethod(TProtocol proto) throws TException { - proto.writeI32(n); - } + internalTestStructField( + new StructFieldTestCase(TType.I32, (short) 15) { + public void writeMethod(TProtocol proto) throws TException { + proto.writeI32(n); + } - public void readMethod(TProtocol proto) throws TException { - assertEquals(n, proto.readI32()); - } - }); + public void readMethod(TProtocol proto) throws TException { + assertEquals(n, proto.readI32()); + } + }); } private void internalTestNakedI64(long n) throws Exception { @@ -233,15 +243,16 @@ public abstract class ProtocolTestBase { } private void internalTestI64Field(final long n) throws Exception { - internalTestStructField(new StructFieldTestCase(TType.I64, (short)15) { - public void writeMethod(TProtocol proto) throws TException { - proto.writeI64(n); - } + internalTestStructField( + new StructFieldTestCase(TType.I64, (short) 15) { + public void writeMethod(TProtocol proto) throws TException { + proto.writeI64(n); + } - public void readMethod(TProtocol proto) throws TException { - assertEquals(n, proto.readI64()); - } - }); + public void readMethod(TProtocol proto) throws TException { + assertEquals(n, proto.readI64()); + } + }); } private void internalTestNakedString(String str) throws Exception { @@ -252,15 +263,16 @@ public abstract class ProtocolTestBase { } private void internalTestStringField(final String str) throws Exception { - internalTestStructField(new StructFieldTestCase(TType.STRING, (short)15) { - public void writeMethod(TProtocol proto) throws TException { - proto.writeString(str); - } + internalTestStructField( + new StructFieldTestCase(TType.STRING, (short) 15) { + public void writeMethod(TProtocol proto) throws TException { + proto.writeString(str); + } - public void readMethod(TProtocol proto) throws TException { - assertEquals(str, proto.readString()); - } - }); + public void readMethod(TProtocol proto) throws TException { + assertEquals(str, proto.readString()); + } + }); } private void internalTestNakedBinary(byte[] data) throws Exception { @@ -271,18 +283,20 @@ public abstract class ProtocolTestBase { } private void internalTestBinaryField(final byte[] data) throws Exception { - internalTestStructField(new StructFieldTestCase(TType.STRING, (short)15) { - public void writeMethod(TProtocol proto) throws TException { - proto.writeBinary(ByteBuffer.wrap(data)); - } + internalTestStructField( + new StructFieldTestCase(TType.STRING, (short) 15) { + public void writeMethod(TProtocol proto) throws TException { + proto.writeBinary(ByteBuffer.wrap(data)); + } - public void readMethod(TProtocol proto) throws TException { - assertEquals(ByteBuffer.wrap(data), proto.readBinary()); - } - }); + public void readMethod(TProtocol proto) throws TException { + assertEquals(ByteBuffer.wrap(data), proto.readBinary()); + } + }); } - private <T extends TBase> void internalTestSerialization(Class<T> klass, T expected) throws Exception { + private <T extends TBase> void internalTestSerialization(Class<T> klass, T expected) + throws Exception { TMemoryBuffer buf = new TMemoryBuffer(0); TBinaryProtocol binproto = new TBinaryProtocol(buf); @@ -292,7 +306,7 @@ public abstract class ProtocolTestBase { TProtocol proto = getFactory().getProtocol(buf); expected.write(proto); - System.out.println("Size in " + proto.getClass().getSimpleName() + ": " + buf.length()); + System.out.println("Size in " + proto.getClass().getSimpleName() + ": " + buf.length()); T actual = klass.newInstance(); actual.read(proto); @@ -301,12 +315,15 @@ public abstract class ProtocolTestBase { @Test public void testMessage() throws Exception { - List<TMessage> msgs = Arrays.asList(new TMessage[]{ - new TMessage("short message name", TMessageType.CALL, 0), - new TMessage("1", TMessageType.REPLY, 12345), - new TMessage("loooooooooooooooooooooooooooooooooong", TMessageType.EXCEPTION, 1 << 16), - new TMessage("Janky", TMessageType.CALL, 0), - }); + List<TMessage> msgs = + Arrays.asList( + new TMessage[] { + new TMessage("short message name", TMessageType.CALL, 0), + new TMessage("1", TMessageType.REPLY, 12345), + new TMessage( + "loooooooooooooooooooooooooooooooooong", TMessageType.EXCEPTION, 1 << 16), + new TMessage("Janky", TMessageType.CALL, 0), + }); for (TMessage msg : msgs) { TMemoryBuffer buf = new TMemoryBuffer(0); @@ -324,34 +341,32 @@ public abstract class ProtocolTestBase { @Test public void testServerRequest() throws Exception { - Srv.Iface handler = new Srv.Iface() { - public int Janky(int i32arg) throws TException { - return i32arg * 2; - } + Srv.Iface handler = + new Srv.Iface() { + public int Janky(int i32arg) throws TException { + return i32arg * 2; + } - public int primitiveMethod() throws TException { - return 0; - } + public int primitiveMethod() throws TException { + return 0; + } - public CompactProtoTestStruct structMethod() throws TException { - return null; - } + public CompactProtoTestStruct structMethod() throws TException { + return null; + } - public void voidMethod() throws TException { - } + public void voidMethod() throws TException {} - public void methodWithDefaultArgs(int something) throws TException { - } + public void methodWithDefaultArgs(int something) throws TException {} - @Override - public void onewayMethod() throws TException { - } + @Override + public void onewayMethod() throws TException {} - @Override - public boolean declaredExceptionMethod(boolean shouldThrow) throws TException { - return shouldThrow; - } - }; + @Override + public boolean declaredExceptionMethod(boolean shouldThrow) throws TException { + return shouldThrow; + } + }; Srv.Processor testProcessor = new Srv.Processor(handler); @@ -404,15 +419,17 @@ public abstract class ProtocolTestBase { proto.readStructEnd(); } - private static abstract class StructFieldTestCase { + private abstract static class StructFieldTestCase { byte type_; short id_; + public StructFieldTestCase(byte type, short id) { type_ = type; id_ = id; } public abstract void writeMethod(TProtocol proto) throws TException; + public abstract void readMethod(TProtocol proto) throws TException; } @@ -429,8 +446,12 @@ public abstract class ProtocolTestBase { } long serEnd = System.currentTimeMillis(); long serElapsed = serEnd - serStart; - System.out.println("Ser:\t" + serElapsed + "ms\t" - + ((double)serElapsed / NUM_REPS) + "ms per serialization"); + System.out.println( + "Ser:\t" + + serElapsed + + "ms\t" + + ((double) serElapsed / NUM_REPS) + + "ms per serialization"); HolyMoley cpts = new HolyMoley(); TDeserializer deser = new TDeserializer(getFactory()); @@ -440,52 +461,57 @@ public abstract class ProtocolTestBase { } long deserEnd = System.currentTimeMillis(); long deserElapsed = deserEnd - deserStart; - System.out.println("Des:\t" + deserElapsed + "ms\t" - + ((double)deserElapsed / NUM_REPS) + "ms per deserialization"); + System.out.println( + "Des:\t" + + deserElapsed + + "ms\t" + + ((double) deserElapsed / NUM_REPS) + + "ms per deserialization"); } } - private final ServerTestBase.TestHandler testHandler = new ServerTestBase.TestHandler() { - @Override - public String testString(String thing) { - thing = thing + " Apache Thrift Java " + thing; - return thing; - } - - @Override - public List<Integer> testList(List<Integer> thing) { - thing.addAll(thing); - thing.addAll(thing); - return thing; - } - - @Override - public Set<Integer> testSet(Set<Integer> thing) { - thing.addAll(thing.stream().map( x -> x + 100).collect(Collectors.toSet())); - return thing; - } - - @Override - public Map<String, String> testStringMap(Map<String, String> thing) { - thing.put("a", "123"); - thing.put(" x y ", " with spaces "); - thing.put("same", "same"); - thing.put("0", "numeric key"); - thing.put("1", ""); - thing.put("ok", "2355555"); - thing.put("end", "0"); - return thing; - } - }; - - private TProtocol initConfig(int maxSize) throws TException{ + private final ServerTestBase.TestHandler testHandler = + new ServerTestBase.TestHandler() { + @Override + public String testString(String thing) { + thing = thing + " Apache Thrift Java " + thing; + return thing; + } + + @Override + public List<Integer> testList(List<Integer> thing) { + thing.addAll(thing); + thing.addAll(thing); + return thing; + } + + @Override + public Set<Integer> testSet(Set<Integer> thing) { + thing.addAll(thing.stream().map(x -> x + 100).collect(Collectors.toSet())); + return thing; + } + + @Override + public Map<String, String> testStringMap(Map<String, String> thing) { + thing.put("a", "123"); + thing.put(" x y ", " with spaces "); + thing.put("same", "same"); + thing.put("0", "numeric key"); + thing.put("1", ""); + thing.put("ok", "2355555"); + thing.put("end", "0"); + return thing; + } + }; + + private TProtocol initConfig(int maxSize) throws TException { TConfiguration config = TConfiguration.custom().setMaxMessageSize(maxSize).build(); TMemoryBuffer bufferTrans = new TMemoryBuffer(config, 0); return getFactory().getProtocol(bufferTrans); } @Test - public void testReadCheckMaxMessageRequestForString() throws TException{ + public void testReadCheckMaxMessageRequestForString() throws TException { TProtocol clientOutProto = initConfig(15); TProtocol clientInProto = initConfig(15); ThriftTest.Client testClient = new ThriftTest.Client(clientInProto, clientOutProto); @@ -494,28 +520,32 @@ public abstract class ProtocolTestBase { testClient.send_testString("test"); testProcessor.process(clientOutProto, clientInProto); String result = testClient.recv_testString(); - System.out.println("----result: "+result); + System.out.println("----result: " + result); } catch (TException e) { assertEquals("MaxMessageSize reached", e.getMessage()); } } @Test - public void testReadCheckMaxMessageRequestForList() throws TException{ + public void testReadCheckMaxMessageRequestForList() throws TException { TProtocol clientOutProto = initConfig(15); TProtocol clientInProto = initConfig(15); ThriftTest.Client testClient = new ThriftTest.Client(clientInProto, clientOutProto); ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); - TTransportException e = assertThrows(TTransportException.class, () -> { - testClient.send_testList(Arrays.asList(1, 23242346, 888888, 90)); - testProcessor.process(clientOutProto, clientInProto); - testClient.recv_testList(); - }, "Limitations not achieved as expected"); + TTransportException e = + assertThrows( + TTransportException.class, + () -> { + testClient.send_testList(Arrays.asList(1, 23242346, 888888, 90)); + testProcessor.process(clientOutProto, clientInProto); + testClient.recv_testList(); + }, + "Limitations not achieved as expected"); assertEquals("MaxMessageSize reached", e.getMessage()); } @Test - public void testReadCheckMaxMessageRequestForMap() throws TException{ + public void testReadCheckMaxMessageRequestForMap() throws TException { TProtocol clientOutProto = initConfig(13); TProtocol clientInProto = initConfig(13); ThriftTest.Client testClient = new ThriftTest.Client(clientInProto, clientOutProto); @@ -523,27 +553,35 @@ public abstract class ProtocolTestBase { Map<String, String> thing = new HashMap<>(); thing.put("key", "Thrift"); - TTransportException e = assertThrows(TTransportException.class, () -> { - testClient.send_testStringMap(thing); - testProcessor.process(clientOutProto, clientInProto); - testClient.recv_testStringMap(); - }, "Limitations not achieved as expected"); + TTransportException e = + assertThrows( + TTransportException.class, + () -> { + testClient.send_testStringMap(thing); + testProcessor.process(clientOutProto, clientInProto); + testClient.recv_testStringMap(); + }, + "Limitations not achieved as expected"); assertEquals("MaxMessageSize reached", e.getMessage()); } @Test - public void testReadCheckMaxMessageRequestForSet() throws TException{ + public void testReadCheckMaxMessageRequestForSet() throws TException { TProtocol clientOutProto = initConfig(10); TProtocol clientInProto = initConfig(10); ThriftTest.Client testClient = new ThriftTest.Client(clientInProto, clientOutProto); ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); TTransportException e = - assertThrows(TTransportException.class, () -> { - testClient.send_testSet(Stream.of(234, 0, 987087, 45, 88888888, 9).collect(Collectors.toSet())); + assertThrows( + TTransportException.class, + () -> { + testClient.send_testSet( + Stream.of(234, 0, 987087, 45, 88888888, 9).collect(Collectors.toSet())); testProcessor.process(clientOutProto, clientInProto); testClient.recv_testSet(); - }, "Limitations not achieved as expected"); + }, + "Limitations not achieved as expected"); assertEquals("MaxMessageSize reached", e.getMessage()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java index 24541ebef..d2a458fb1 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java @@ -18,25 +18,24 @@ */ package org.apache.thrift.protocol; - -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -public class TestShortStack { +import org.junit.jupiter.api.Test; + +public class TestShortStack { @Test public void testOps() throws Exception { ShortStack s = new ShortStack(1); - s.push((short)10); - s.push((short)11); - s.push((short)12); - assertEquals((short)12, s.pop()); - assertEquals((short)11, s.pop()); - s.push((short)40); - assertEquals((short)40, s.pop()); - assertEquals((short)10, s.pop()); + s.push((short) 10); + s.push((short) 11); + s.push((short) 12); + assertEquals((short) 12, s.pop()); + assertEquals((short) 11, s.pop()); + s.push((short) 40); + assertEquals((short) 40, s.pop()); + assertEquals((short) 10, s.pop()); assertThrows(Exception.class, s::pop); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java index acc46e9d8..0cfd9377a 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.protocol; public class TestTBinaryProtocol extends ProtocolTestBase { @@ -30,5 +29,4 @@ public class TestTBinaryProtocol extends ProtocolTestBase { protected boolean canBeUsedNaked() { return true; } - } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java index b2c29f7dd..4aa71db82 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java @@ -17,12 +17,10 @@ * under the License. */ - package org.apache.thrift.protocol; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; - import org.junit.jupiter.api.Test; import thrift.test.Bonk; @@ -41,14 +39,13 @@ public class TestTCompactProtocol extends ProtocolTestBase { public void testOOMDenialOfService() throws Exception { // Struct header, Integer.MAX_VALUE length, and only one real // byte of data - byte [] bytes = {24, -1, -1, -1, -17, 49}; - TDeserializer deser = new TDeserializer(new TCompactProtocol - .Factory(1000)); + byte[] bytes = {24, -1, -1, -1, -17, 49}; + TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory(1000)); Bonk bonk = new Bonk(); try { - deser.deserialize(bonk, bytes); + deser.deserialize(bonk, bytes); } catch (TException e) { - // Ignore as we are only checking for OOM in the failure case + // Ignore as we are only checking for OOM in the failure case } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java index 62b8d3f66..0b71f47d2 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java @@ -18,13 +18,12 @@ */ package org.apache.thrift.protocol; - -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -public abstract class TestTField { +import org.junit.jupiter.api.Test; + +public abstract class TestTField { @Test public void testConstructor() { @@ -33,7 +32,7 @@ public abstract class TestTField { assertEquals(TType.STOP, uut.type); assertEquals(0, uut.id); - uut = new TField("foo", TType.VOID, (short)42); + uut = new TField("foo", TType.VOID, (short) 42); assertEquals("foo", uut.name); assertEquals(TType.VOID, uut.type); assertEquals(42, uut.id); @@ -46,20 +45,19 @@ public abstract class TestTField { assertEquals(uut1, uut2); assertEquals(uut1.hashCode(), uut2.hashCode()); - uut1 = new TField("foo", TType.I32, (short)1); - uut2 = new TField("foo", TType.I32, (short)2); + uut1 = new TField("foo", TType.I32, (short) 1); + uut2 = new TField("foo", TType.I32, (short) 2); assertNotEquals(uut1, uut2); assertNotEquals(uut1.hashCode(), uut2.hashCode()); - uut1 = new TField("foo", TType.VOID, (short)1); - uut2 = new TField("foo", TType.I32, (short)1); + uut1 = new TField("foo", TType.VOID, (short) 1); + uut2 = new TField("foo", TType.I32, (short) 1); assertNotEquals(uut1, uut2); assertNotEquals(uut1.hashCode(), uut2.hashCode()); - uut1 = new TField("foo", TType.VOID, (short)5); - uut2 = new TField("bar", TType.I32, (short)5); + uut1 = new TField("foo", TType.VOID, (short) 5); + uut2 = new TField("bar", TType.I32, (short) 5); assertEquals(uut1, uut2); // name field is ignored assertEquals(uut1.hashCode(), uut2.hashCode()); } - } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java index 993362993..9f5f4a09c 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java @@ -18,14 +18,13 @@ */ package org.apache.thrift.protocol; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; import org.apache.thrift.TException; import org.apache.thrift.transport.TMemoryBuffer; import org.junit.jupiter.api.Test; -import java.nio.charset.StandardCharsets; - -import static org.junit.jupiter.api.Assertions.assertEquals; - public class TestTJSONProtocol extends ProtocolTestBase { @Override protected TProtocolFactory getFactory() { diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java index 937e9130e..f37627df7 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java @@ -18,27 +18,28 @@ */ package org.apache.thrift.protocol; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.thrift.TSerializer; import org.junit.jupiter.api.Test; import thrift.test.GuessProtocolStruct; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class TestTProtocolUtil { +public class TestTProtocolUtil { @Test public void testGuessProtocolFactory_JSON() throws Exception { byte[] data = "{foo}".getBytes(); - TProtocolFactory factory = TProtocolUtil.guessProtocolFactory(data, new TCompactProtocol.Factory()); + TProtocolFactory factory = + TProtocolUtil.guessProtocolFactory(data, new TCompactProtocol.Factory()); assertTrue(factory instanceof TJSONProtocol.Factory); // Make sure data serialized with TCompact and which starts with '{' // is not mistakenly guessed as serialized with JSON. GuessProtocolStruct s = new GuessProtocolStruct(); - s.putToMap_field("}","}"); + s.putToMap_field("}", "}"); byte[] ser = new TSerializer(new TCompactProtocol.Factory()).serialize(s); factory = TProtocolUtil.guessProtocolFactory(ser, new TCompactProtocol.Factory()); assertFalse(factory instanceof TJSONProtocol.Factory); @@ -51,13 +52,15 @@ public class TestTProtocolUtil { byte[] buf = new byte[1]; for (int i = 1; i < 256; i++) { buf[0] = (byte) i; - TProtocolFactory factory = TProtocolUtil.guessProtocolFactory(buf, new TCompactProtocol.Factory()); + TProtocolFactory factory = + TProtocolUtil.guessProtocolFactory(buf, new TCompactProtocol.Factory()); assertTrue(factory instanceof TBinaryProtocol.Factory); } // Check that a second byte set to 0 is reported as Binary buf = new byte[2]; - TProtocolFactory factory = TProtocolUtil.guessProtocolFactory(buf, new TCompactProtocol.Factory()); + TProtocolFactory factory = + TProtocolUtil.guessProtocolFactory(buf, new TCompactProtocol.Factory()); assertTrue(factory instanceof TBinaryProtocol.Factory); } @@ -66,7 +69,8 @@ public class TestTProtocolUtil { // Check that a first byte > 0x10 is reported as Compact byte[] buf = new byte[3]; buf[0] = 0x11; - TProtocolFactory factory = TProtocolUtil.guessProtocolFactory(buf, new TBinaryProtocol.Factory()); + TProtocolFactory factory = + TProtocolUtil.guessProtocolFactory(buf, new TBinaryProtocol.Factory()); assertTrue(factory instanceof TCompactProtocol.Factory); // Check that second byte >= 0x80 is reported as Compact @@ -82,7 +86,8 @@ public class TestTProtocolUtil { public void testGuessProtocolFactory_Undecided() throws Exception { byte[] buf = new byte[3]; buf[1] = 0x7e; - TProtocolFactory factory = TProtocolUtil.guessProtocolFactory(buf, new TSimpleJSONProtocol.Factory()); + TProtocolFactory factory = + TProtocolUtil.guessProtocolFactory(buf, new TSimpleJSONProtocol.Factory()); assertTrue(factory instanceof TSimpleJSONProtocol.Factory); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java index b1fc04e4f..7fe5ba769 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java @@ -18,6 +18,10 @@ */ package org.apache.thrift.protocol; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.charset.StandardCharsets; import org.apache.thrift.Fixtures; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; @@ -28,11 +32,6 @@ import org.junit.jupiter.api.Test; import thrift.test.CompactProtoTestStruct; import thrift.test.HolyMoley; -import java.nio.charset.StandardCharsets; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - public class TestTSimpleJSONProtocol { private TMemoryBuffer buf; private TSimpleJSONProtocol proto; @@ -54,19 +53,25 @@ public class TestTSimpleJSONProtocol { holyMoley.unsetBonks(); holyMoley.unsetContain(); holyMoley.write(proto); - assertEquals("{\"big\":[{\"im_true\":1,\"im_false\":0,\"a_bite\":35,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]},{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}]}", bufToString()); + assertEquals( + "{\"big\":[{\"im_true\":1,\"im_false\":0,\"a_bite\":35,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]},{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}]}", + bufToString()); } @Test public void testNesting() throws TException { Fixtures.getNesting().write(proto); - assertEquals("{\"my_bonk\":{\"type\":31337,\"message\":\"I am a bonk... xor!\"},\"my_ooe\":{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}}", bufToString()); + assertEquals( + "{\"my_bonk\":{\"type\":31337,\"message\":\"I am a bonk... xor!\"},\"my_ooe\":{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}}", + bufToString()); } @Test public void testOneOfEach() throws TException { Fixtures.getOneOfEach().write(proto); - assertEquals("{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}", bufToString()); + assertEquals( + "{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}", + bufToString()); } @Test @@ -88,21 +93,28 @@ public class TestTSimpleJSONProtocol { struct.unsetDouble_byte_map(); struct.unsetString_byte_map(); struct.write(proto); - assertEquals("{\"a_byte\":127,\"a_i16\":32000,\"a_i32\":1000000000,\"a_i64\":1099511627775,\"a_double\":5.6789,\"a_string\":\"my string\",\"a_binary\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\",\"true_field\":1,\"false_field\":0,\"empty_struct_field\":{},\"byte_list\":[-127,-1,0,1,127],\"i16_list\":[-1,0,1,32767],\"i32_list\":[-1,0,255,65535,16777215,2147483647],\"i64_list\":[-1,0,255,65535,16777215,4294967295,1099511627775,281474976710655,72057594037927935,9223372036854775807],\"double_list\":[0.1,0.2,0.3],\"string_list\":[\"first\",\"second\",\"third\"],\"boolean_list\":[1,1,1,0,0,0],\"struct_list\":[{},{}],\"i32_set\":[1,2,3],\"boolean_set\":[0,1],\"struct_set\":[{}],\"byte_byte_map\":{\"1\":2},\"boolean_byte_map\":{\"0\":0,\"1\":1},\"byte_i16_map\":{\"1\":1,\"2\":-1,\"3\":32767},\"byte_i32_map\":{\"1\":1,\"2\":-1,\"3\":2147483647},\"byte_i64_map\":{\"1\":1,\"2\":-1,\"3\":9223372036854775807},\"byte_double_map\":{\"1\":0.1,\"2\":-0.1,\"3\":1000000.1},\"byte_string_map\":{\"1\":\"\",\"2\":\"blah\",\"3\":\"loooooooooooooong string\"},\"byte_boolean_map\":{\"1\":1,\"2\":0},\"byte_map_map\":{\"0\":{},\"1\":{\"1\":1},\"2\":{\"1\":1,\"2\":2}},\"byte_set_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"byte_list_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"field500\":500,\"field5000\":5000,\"field20000\":20000}", bufToString()); + assertEquals( + "{\"a_byte\":127,\"a_i16\":32000,\"a_i32\":1000000000,\"a_i64\":1099511627775,\"a_double\":5.6789,\"a_string\":\"my string\",\"a_binary\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\",\"true_field\":1,\"false_field\":0,\"empty_struct_field\":{},\"byte_list\":[-127,-1,0,1,127],\"i16_list\":[-1,0,1,32767],\"i32_list\":[-1,0,255,65535,16777215,2147483647],\"i64_list\":[-1,0,255,65535,16777215,4294967295,1099511627775,281474976710655,72057594037927935,9223372036854775807],\"double_list\":[0.1,0.2,0.3],\"string_list\":[\"first\",\"second\",\"third\"],\"boolean_list\":[1,1,1,0,0,0],\"struct_list\":[{},{}],\"i32_set\":[1,2,3],\"boolean_set\":[0,1],\"struct_set\":[{}],\"byte_byte_map\":{\"1\":2},\"boolean_byte_map\":{\"0\":0,\"1\":1},\"byte_i16_map\":{\"1\":1,\"2\":-1,\"3\":32767},\"byte_i32_map\":{\"1\":1,\"2\":-1,\"3\":2147483647},\"byte_i64_map\":{\"1\":1,\"2\":-1,\"3\":9223372036854775807},\"byte_double_map\":{\"1\":0.1,\"2\":-0.1,\"3\":1000000.1},\"byte_string_map\":{\"1\":\"\",\"2\":\"blah\",\"3\":\"loooooooooooooong string\"},\"byte_boolean_map\":{\"1\":1,\"2\":0},\"byte_map_map\":{\"0\":{},\"1\":{\"1\":1},\"2\":{\"1\":1,\"2\":2}},\"byte_set_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"byte_list_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"field500\":500,\"field5000\":5000,\"field20000\":20000}", + bufToString()); } @Test public void testThrowsOnCollectionKeys() throws TException { - assertThrows(TSimpleJSONProtocol.CollectionMapKeyException.class, () -> Fixtures.getCompactProtoTestStruct().write(proto)); + assertThrows( + TSimpleJSONProtocol.CollectionMapKeyException.class, + () -> Fixtures.getCompactProtoTestStruct().write(proto)); } @Test public void testReadingThrows() throws TTransportException { String input = "{\"test\": \"value\"}"; TDeserializer deserializer = new TDeserializer(new TSimpleJSONProtocol.Factory()); - TException e = assertThrows(TException.class, ()->{ - deserializer.fromString(Fixtures.getOneOfEach(), input); - }); + TException e = + assertThrows( + TException.class, + () -> { + deserializer.fromString(Fixtures.getOneOfEach(), input); + }); assertEquals("Not implemented", e.getMessage()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java index b0e3bcda5..f39ca65da 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java @@ -5,7 +5,6 @@ import org.apache.thrift.TSerializer; import org.junit.jupiter.api.Test; import thrift.test.TupleProtocolTestStruct; - public class TestTTupleProtocol extends ProtocolTestBase { @Override @@ -23,6 +22,9 @@ public class TestTTupleProtocol extends ProtocolTestBase { final TupleProtocolTestStruct t1 = new TupleProtocolTestStruct(); t1.setField1(0); t1.setField2(12); - new TDeserializer(new TTupleProtocol.Factory()).deserialize(new TupleProtocolTestStruct(), new TSerializer(new TTupleProtocol.Factory()).serialize(t1)); + new TDeserializer(new TTupleProtocol.Factory()) + .deserialize( + new TupleProtocolTestStruct(), + new TSerializer(new TTupleProtocol.Factory()).serialize(t1)); } } diff --git a/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java b/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java index f5f0e0bb8..76efc6c48 100644 --- a/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java +++ b/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java @@ -1,5 +1,7 @@ package org.apache.thrift.scheme; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.thrift.Fixtures; import org.apache.thrift.TBase; import org.apache.thrift.TDeserializer; @@ -15,23 +17,22 @@ import thrift.test.HolyMoley; import thrift.test.Nesting; import thrift.test.OneOfEach; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class TestStandardScheme { TSerializer serializer = new TSerializer(); TDeserializer deserializer = new TDeserializer(); - public TestStandardScheme() throws TTransportException { - } + public TestStandardScheme() throws TTransportException {} /** - * This tests whether the Standard Scheme properly reads structs serialized - * using an older version of thrift. + * This tests whether the Standard Scheme properly reads structs serialized using an older version + * of thrift. */ @Test public void testPersistentStructs() throws TException { - readAndCompare(new OneOfEach(), Fixtures.getOneOfEach(), Fixtures.getPersistentBytesOneOfEach()); - readAndCompare(new HolyMoley(), Fixtures.getHolyMoley(), Fixtures.getPersistentBytesHolyMoley()); + readAndCompare( + new OneOfEach(), Fixtures.getOneOfEach(), Fixtures.getPersistentBytesOneOfEach()); + readAndCompare( + new HolyMoley(), Fixtures.getHolyMoley(), Fixtures.getPersistentBytesHolyMoley()); readAndCompare(new Nesting(), Fixtures.getNesting(), Fixtures.getPersistentBytesNesting()); } diff --git a/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java b/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java index 3c40262b4..a1e19ebdf 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java +++ b/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java @@ -18,6 +18,17 @@ */ package org.apache.thrift.server; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.async.AsyncMethodCallback; @@ -40,19 +51,7 @@ import thrift.test.Xception2; import thrift.test.Xtruct; import thrift.test.Xtruct2; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public abstract class ServerTestBase { +public abstract class ServerTestBase { public static class TestHandler implements ThriftTest.Iface { @@ -103,12 +102,12 @@ public abstract class ServerTestBase { public ByteBuffer testBinary(ByteBuffer thing) { StringBuilder sb = new StringBuilder(thing.remaining() * 3); thing.mark(); - int limit = 0; // limit output to keep the log size sane + int limit = 0; // limit output to keep the log size sane while ((thing.remaining() > 0) && (++limit < 1024)) { sb.append(String.format("%02X ", thing.get())); } - if(thing.remaining() > 0) { - sb.append("..."); // indicate we have more date + if (thing.remaining() > 0) { + sb.append("..."); // indicate we have more date } System.out.print("testBinary(" + sb + ")\n"); thing.reset(); @@ -117,29 +116,43 @@ public abstract class ServerTestBase { @Override public Xtruct testStruct(Xtruct thing) { - System.out.print("testStruct({" + - "\"" + thing.string_thing + "\", " + - thing.byte_thing + ", " + - thing.i32_thing + ", " + - thing.i64_thing + "})\n"); + System.out.print( + "testStruct({" + + "\"" + + thing.string_thing + + "\", " + + thing.byte_thing + + ", " + + thing.i32_thing + + ", " + + thing.i64_thing + + "})\n"); return thing; } @Override public Xtruct2 testNest(Xtruct2 nest) { Xtruct thing = nest.struct_thing; - System.out.print("testNest({" + - nest.byte_thing + ", {" + - "\"" + thing.string_thing + "\", " + - thing.byte_thing + ", " + - thing.i32_thing + ", " + - thing.i64_thing + "}, " + - nest.i32_thing + "})\n"); + System.out.print( + "testNest({" + + nest.byte_thing + + ", {" + + "\"" + + thing.string_thing + + "\", " + + thing.byte_thing + + ", " + + thing.i32_thing + + ", " + + thing.i64_thing + + "}, " + + nest.i32_thing + + "})\n"); return nest; } @Override - public Map<Integer,Integer> testMap(Map<Integer,Integer> thing) { + public Map<Integer, Integer> testMap(Map<Integer, Integer> thing) { System.out.print("testMap({"); System.out.print(thing); System.out.print("})\n"); @@ -147,7 +160,7 @@ public abstract class ServerTestBase { } @Override - public Map<String,String> testStringMap(Map<String,String> thing) { + public Map<String, String> testStringMap(Map<String, String> thing) { System.out.print("testStringMap({"); System.out.print(thing); System.out.print("})\n"); @@ -199,13 +212,12 @@ public abstract class ServerTestBase { } @Override - public Map<Integer,Map<Integer,Integer>> testMapMap(int hello) { + public Map<Integer, Map<Integer, Integer>> testMapMap(int hello) { System.out.print("testMapMap(" + hello + ")\n"); - Map<Integer,Map<Integer,Integer>> mapmap = - new HashMap<>(); + Map<Integer, Map<Integer, Integer>> mapmap = new HashMap<>(); - HashMap<Integer,Integer> pos = new HashMap<>(); - HashMap<Integer,Integer> neg = new HashMap<>(); + HashMap<Integer, Integer> pos = new HashMap<>(); + HashMap<Integer, Integer> neg = new HashMap<>(); for (int i = 1; i < 5; i++) { pos.put(i, i); neg.put(-i, -i); @@ -218,11 +230,11 @@ public abstract class ServerTestBase { } @Override - public Map<Long, Map<Numberz,Insanity>> testInsanity(Insanity argument) { + public Map<Long, Map<Numberz, Insanity>> testInsanity(Insanity argument) { System.out.print("testInsanity()\n"); - HashMap<Numberz,Insanity> first_map = new HashMap<>(); - HashMap<Numberz,Insanity> second_map = new HashMap<>(); + HashMap<Numberz, Insanity> first_map = new HashMap<>(); + HashMap<Numberz, Insanity> second_map = new HashMap<>(); first_map.put(Numberz.TWO, argument); first_map.put(Numberz.THREE, argument); @@ -230,16 +242,16 @@ public abstract class ServerTestBase { Insanity looney = new Insanity(); second_map.put(Numberz.SIX, looney); - Map<Long,Map<Numberz,Insanity>> insane = - new HashMap<>(); - insane.put((long)1, first_map); - insane.put((long)2, second_map); + Map<Long, Map<Numberz, Insanity>> insane = new HashMap<>(); + insane.put((long) 1, first_map); + insane.put((long) 2, second_map); return insane; } @Override - public Xtruct testMulti(byte arg0, int arg1, long arg2, Map<Short,String> arg3, Numberz arg4, long arg5) { + public Xtruct testMulti( + byte arg0, int arg1, long arg2, Map<Short, String> arg3, Numberz arg4, long arg5) { System.out.print("testMulti()\n"); Xtruct hello = new Xtruct(); @@ -252,7 +264,7 @@ public abstract class ServerTestBase { @Override public void testException(String arg) throws TException { - System.out.print("testException("+arg+")\n"); + System.out.print("testException(" + arg + ")\n"); if ("Xception".equals(arg)) { Xception x = new Xception(); x.errorCode = 1001; @@ -291,8 +303,7 @@ public abstract class ServerTestBase { @Override public void testOneway(int sleepFor) { - System.out.println("testOneway(" + sleepFor + - ") => sleeping..."); + System.out.println("testOneway(" + sleepFor + ") => sleeping..."); try { Thread.sleep(sleepFor * SLEEP_DELAY); System.out.println("Done sleeping!"); @@ -302,23 +313,23 @@ public abstract class ServerTestBase { } } // class TestHandler - private static final List<TProtocolFactory> PROTOCOLS = Arrays.asList( - new TBinaryProtocol.Factory(), - new TCompactProtocol.Factory()); + private static final List<TProtocolFactory> PROTOCOLS = + Arrays.asList(new TBinaryProtocol.Factory(), new TCompactProtocol.Factory()); public static final String HOST = "localhost"; - public static final int PORT = Integer.parseInt( - System.getProperty("test.port", "9090")); + public static final int PORT = Integer.parseInt(System.getProperty("test.port", "9090")); protected static final long SLEEP_DELAY = 1000; protected static final int SOCKET_TIMEOUT = 1500; private static final Xtruct XSTRUCT = new Xtruct("Zero", (byte) 1, -3, -5); - private static final Xtruct2 XSTRUCT2 = new Xtruct2((byte)1, XSTRUCT, 5); + private static final Xtruct2 XSTRUCT2 = new Xtruct2((byte) 1, XSTRUCT, 5); - public void startServer(TProcessor processor, TProtocolFactory protoFactory) throws Exception{ + public void startServer(TProcessor processor, TProtocolFactory protoFactory) throws Exception { startServer(processor, protoFactory, null); } - public abstract void startServer(TProcessor processor, TProtocolFactory protoFactory, TTransportFactory factory) throws Exception; + public abstract void startServer( + TProcessor processor, TProtocolFactory protoFactory, TTransportFactory factory) + throws Exception; public abstract void stopServer() throws Exception; @@ -332,7 +343,7 @@ public abstract class ServerTestBase { } private void testByte(ThriftTest.Client testClient) throws TException { - byte i8 = testClient.testByte((byte)1); + byte i8 = testClient.testByte((byte) 1); assertEquals(1, i8); } @@ -365,20 +376,19 @@ public abstract class ServerTestBase { insane = new Insanity(); insane.userMap = new HashMap<>(); - insane.userMap.put(Numberz.FIVE, (long)5000); + insane.userMap.put(Numberz.FIVE, (long) 5000); Xtruct truck = new Xtruct(); truck.string_thing = "Truck"; - truck.byte_thing = (byte)8; + truck.byte_thing = (byte) 8; truck.i32_thing = 8; truck.i64_thing = 8; insane.xtructs = new ArrayList<>(); insane.xtructs.add(truck); System.out.print("testInsanity()"); - Map<Long,Map<Numberz,Insanity>> whoa = - testClient.testInsanity(insane); + Map<Long, Map<Numberz, Insanity>> whoa = testClient.testInsanity(insane); System.out.print(" = {"); for (long key : whoa.keySet()) { - Map<Numberz,Insanity> val = whoa.get(key); + Map<Numberz, Insanity> val = whoa.get(key); System.out.print(key + " => {"); for (Numberz k2 : val.keySet()) { @@ -397,7 +407,17 @@ public abstract class ServerTestBase { System.out.print("{"); if (xtructs != null) { for (Xtruct x : xtructs) { - System.out.print("{" + "\"" + x.string_thing + "\", " + x.byte_thing + ", " + x.i32_thing + ", "+ x.i64_thing + "}, "); + System.out.print( + "{" + + "\"" + + x.string_thing + + "\", " + + x.byte_thing + + ", " + + x.i32_thing + + ", " + + x.i64_thing + + "}, "); } } System.out.print("}"); @@ -410,14 +430,17 @@ public abstract class ServerTestBase { } public boolean useAsyncProcessor() { - return false; + return false; } @Test public void testIt() throws Exception { for (TProtocolFactory protoFactory : getProtocols()) { - TProcessor processor = useAsyncProcessor() ? new ThriftTest.AsyncProcessor<>(new AsyncTestHandler()) : new ThriftTest.Processor<>(new TestHandler()); + TProcessor processor = + useAsyncProcessor() + ? new ThriftTest.AsyncProcessor<>(new AsyncTestHandler()) + : new ThriftTest.Processor<>(new TestHandler()); startServer(processor, protoFactory); @@ -474,32 +497,30 @@ public abstract class ServerTestBase { } private void testMap(ThriftTest.Client testClient) throws TException { - Map<Integer,Integer> mapout = new HashMap<>(); + Map<Integer, Integer> mapout = new HashMap<>(); for (int i = 0; i < 5; ++i) { - mapout.put(i, i-10); + mapout.put(i, i - 10); } - Map<Integer,Integer> mapin = testClient.testMap(mapout); + Map<Integer, Integer> mapin = testClient.testMap(mapout); assertEquals(mapout, mapin); } private void testStringMap(ThriftTest.Client testClient) throws TException { - Map<String,String> mapout = new HashMap<>(); + Map<String, String> mapout = new HashMap<>(); mapout.put("a", "123"); mapout.put(" x y ", " with spaces "); mapout.put("same", "same"); mapout.put("0", "numeric key"); - Map<String,String> mapin = testClient.testStringMap(mapout); + Map<String, String> mapin = testClient.testStringMap(mapout); assertEquals(mapout, mapin); } private void testNestedMap(ThriftTest.Client testClient) throws TException { - Map<Integer,Map<Integer,Integer>> mm = - testClient.testMapMap(1); - Map<Integer,Map<Integer,Integer>> mapmap = - new HashMap<>(); + Map<Integer, Map<Integer, Integer>> mm = testClient.testMapMap(1); + Map<Integer, Map<Integer, Integer>> mapmap = new HashMap<>(); - HashMap<Integer,Integer> pos = new HashMap<>(); - HashMap<Integer,Integer> neg = new HashMap<>(); + HashMap<Integer, Integer> pos = new HashMap<>(); + HashMap<Integer, Integer> neg = new HashMap<>(); for (int i = 1; i < 5; i++) { pos.put(i, i); neg.put(-i, -i); @@ -569,7 +590,8 @@ public abstract class ServerTestBase { TestHandler handler = new TestHandler(); ThriftTest.Processor<TestHandler> processor = new ThriftTest.Processor<>(handler); - final CallCountingTransportFactory factory = new CallCountingTransportFactory(new TFramedTransport.Factory()); + final CallCountingTransportFactory factory = + new CallCountingTransportFactory(new TFramedTransport.Factory()); startServer(processor, protoFactory, factory); assertEquals(0, factory.count); @@ -592,19 +614,18 @@ public abstract class ServerTestBase { try { testClient.testException("Xception"); assert false; - } catch(Xception e) { + } catch (Xception e) { assertEquals(e.message, "Xception"); assertEquals(e.errorCode, 1001); } try { testClient.testException("TException"); assert false; - } catch(TException e) { + } catch (TException e) { } testClient.testException("no Exception"); } - public static class AsyncTestHandler implements ThriftTest.AsyncIface { TestHandler handler = new TestHandler(); @@ -615,12 +636,14 @@ public abstract class ServerTestBase { } @Override - public void testString(String thing, AsyncMethodCallback<String> resultHandler) throws TException { + public void testString(String thing, AsyncMethodCallback<String> resultHandler) + throws TException { resultHandler.onComplete(handler.testString(thing)); } @Override - public void testBool(boolean thing, AsyncMethodCallback<Boolean> resultHandler) throws TException { + public void testBool(boolean thing, AsyncMethodCallback<Boolean> resultHandler) + throws TException { resultHandler.onComplete(handler.testBool(thing)); } @@ -640,47 +663,58 @@ public abstract class ServerTestBase { } @Override - public void testDouble(double thing, AsyncMethodCallback<Double> resultHandler) throws TException { + public void testDouble(double thing, AsyncMethodCallback<Double> resultHandler) + throws TException { resultHandler.onComplete(handler.testDouble(thing)); } @Override - public void testBinary(ByteBuffer thing, AsyncMethodCallback<ByteBuffer> resultHandler) throws TException { + public void testBinary(ByteBuffer thing, AsyncMethodCallback<ByteBuffer> resultHandler) + throws TException { resultHandler.onComplete(handler.testBinary(thing)); } @Override - public void testStruct(Xtruct thing, AsyncMethodCallback<Xtruct> resultHandler) throws TException { + public void testStruct(Xtruct thing, AsyncMethodCallback<Xtruct> resultHandler) + throws TException { resultHandler.onComplete(handler.testStruct(thing)); } @Override - public void testNest(Xtruct2 thing, AsyncMethodCallback<Xtruct2> resultHandler) throws TException { + public void testNest(Xtruct2 thing, AsyncMethodCallback<Xtruct2> resultHandler) + throws TException { resultHandler.onComplete(handler.testNest(thing)); } @Override - public void testMap(Map<Integer, Integer> thing, AsyncMethodCallback<Map<Integer, Integer>> resultHandler) throws TException { + public void testMap( + Map<Integer, Integer> thing, AsyncMethodCallback<Map<Integer, Integer>> resultHandler) + throws TException { resultHandler.onComplete(handler.testMap(thing)); } @Override - public void testStringMap(Map<String, String> thing, AsyncMethodCallback<Map<String, String>> resultHandler) throws TException { + public void testStringMap( + Map<String, String> thing, AsyncMethodCallback<Map<String, String>> resultHandler) + throws TException { resultHandler.onComplete(handler.testStringMap(thing)); } @Override - public void testSet(Set<Integer> thing, AsyncMethodCallback<Set<Integer>> resultHandler) throws TException { + public void testSet(Set<Integer> thing, AsyncMethodCallback<Set<Integer>> resultHandler) + throws TException { resultHandler.onComplete(handler.testSet(thing)); } @Override - public void testList(List<Integer> thing, AsyncMethodCallback<List<Integer>> resultHandler) throws TException { + public void testList(List<Integer> thing, AsyncMethodCallback<List<Integer>> resultHandler) + throws TException { resultHandler.onComplete(handler.testList(thing)); } @Override - public void testEnum(Numberz thing, AsyncMethodCallback<Numberz> resultHandler) throws TException { + public void testEnum(Numberz thing, AsyncMethodCallback<Numberz> resultHandler) + throws TException { resultHandler.onComplete(handler.testEnum(thing)); } @@ -690,23 +724,36 @@ public abstract class ServerTestBase { } @Override - public void testMapMap(int hello, AsyncMethodCallback<Map<Integer,Map<Integer,Integer>>> resultHandler) throws TException { + public void testMapMap( + int hello, AsyncMethodCallback<Map<Integer, Map<Integer, Integer>>> resultHandler) + throws TException { resultHandler.onComplete(handler.testMapMap(hello)); } @Override - public void testInsanity(Insanity argument, AsyncMethodCallback<Map<Long, Map<Numberz,Insanity>>> resultHandler) throws TException { + public void testInsanity( + Insanity argument, AsyncMethodCallback<Map<Long, Map<Numberz, Insanity>>> resultHandler) + throws TException { resultHandler.onComplete(handler.testInsanity(argument)); } @Override - public void testMulti(byte arg0, int arg1, long arg2, Map<Short, String> arg3, Numberz arg4, long arg5, AsyncMethodCallback<Xtruct> resultHandler) throws TException { - resultHandler.onComplete(handler.testMulti(arg0,arg1,arg2,arg3,arg4,arg5)); + public void testMulti( + byte arg0, + int arg1, + long arg2, + Map<Short, String> arg3, + Numberz arg4, + long arg5, + AsyncMethodCallback<Xtruct> resultHandler) + throws TException { + resultHandler.onComplete(handler.testMulti(arg0, arg1, arg2, arg3, arg4, arg5)); } @Override - public void testException(String arg, AsyncMethodCallback<Void> resultHandler) throws TException { - System.out.print("testException("+arg+")\n"); + public void testException(String arg, AsyncMethodCallback<Void> resultHandler) + throws TException { + System.out.print("testException(" + arg + ")\n"); if ("Xception".equals(arg)) { Xception x = new Xception(); x.errorCode = 1001; @@ -726,15 +773,16 @@ public abstract class ServerTestBase { } @Override - public void testMultiException(String arg0, String arg1, AsyncMethodCallback<Xtruct> resultHandler) throws TException { - //To change body of implemented methods use File | Settings | File Templates. + public void testMultiException( + String arg0, String arg1, AsyncMethodCallback<Xtruct> resultHandler) throws TException { + // To change body of implemented methods use File | Settings | File Templates. } @Override - public void testOneway(int secondsToSleep, AsyncMethodCallback<Void> resultHandler) throws TException { + public void testOneway(int secondsToSleep, AsyncMethodCallback<Void> resultHandler) + throws TException { handler.testOneway(secondsToSleep); resultHandler.onComplete(null); } } - } diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestAsyncServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestAsyncServer.java index 29c54cbbc..f8b538304 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestAsyncServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestAsyncServer.java @@ -20,9 +20,8 @@ package org.apache.thrift.server; public class TestAsyncServer extends TestNonblockingServer { - @Override - public boolean useAsyncProcessor(){ - return true; - } - + @Override + public boolean useAsyncProcessor() { + return true; + } } diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestHsHaServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestHsHaServer.java index 6638a333f..2ea818d7e 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestHsHaServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestHsHaServer.java @@ -24,7 +24,8 @@ import org.apache.thrift.server.THsHaServer.Args; import org.apache.thrift.transport.TNonblockingServerSocket; public class TestHsHaServer extends TestNonblockingServer { - protected TServer getServer(TProcessor processor, TNonblockingServerSocket socket, TProtocolFactory protoFactory) { + protected TServer getServer( + TProcessor processor, TNonblockingServerSocket socket, TProtocolFactory protoFactory) { return new THsHaServer(new Args(socket).processor(processor).protocolFactory(protoFactory)); } } diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java index 927635b61..29a81ef80 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java @@ -18,6 +18,8 @@ */ package org.apache.thrift.server; +import static org.junit.jupiter.api.Assertions.fail; + import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; @@ -31,15 +33,17 @@ import org.apache.thrift.transport.layered.TFramedTransport; import org.junit.jupiter.api.Test; import thrift.test.ThriftTest; -import static org.junit.jupiter.api.Assertions.fail; - public class TestNonblockingServer extends ServerTestBase { private Thread serverThread; private TServer server; private static final int NUM_QUERIES = 1000; - protected TServer getServer(TProcessor processor, TNonblockingServerSocket socket, TProtocolFactory protoFactory, TTransportFactory factory) { + protected TServer getServer( + TProcessor processor, + TNonblockingServerSocket socket, + TProtocolFactory protoFactory, + TTransportFactory factory) { final Args args = new Args(socket).processor(processor).protocolFactory(protoFactory); if (factory != null) { args.transportFactory(factory); @@ -48,25 +52,32 @@ public class TestNonblockingServer extends ServerTestBase { } @Override - public void startServer(final TProcessor processor, final TProtocolFactory protoFactory, final TTransportFactory factory) throws Exception { - serverThread = new Thread() { - public void run() { - try { - // Transport - TNonblockingServerSocket tServerSocket = - new TNonblockingServerSocket(new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(PORT)); - - server = getServer(processor, tServerSocket, protoFactory, factory); - - // Run it - System.out.println("Starting the server on port " + PORT + "..."); - server.serve(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } - }; + public void startServer( + final TProcessor processor, + final TProtocolFactory protoFactory, + final TTransportFactory factory) + throws Exception { + serverThread = + new Thread() { + public void run() { + try { + // Transport + TNonblockingServerSocket tServerSocket = + new TNonblockingServerSocket( + new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs() + .port(PORT)); + + server = getServer(processor, tServerSocket, protoFactory, factory); + + // Run it + System.out.println("Starting the server on port " + PORT + "..."); + server.serve(); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + }; serverThread.start(); Thread.sleep(1000); } @@ -76,7 +87,8 @@ public class TestNonblockingServer extends ServerTestBase { server.stop(); try { serverThread.join(); - } catch (InterruptedException e) {} + } catch (InterruptedException e) { + } } @Override @@ -84,7 +96,6 @@ public class TestNonblockingServer extends ServerTestBase { return new TFramedTransport(underlyingTransport); } - @Test public void testCleanupAllSelectionKeys() throws Exception { for (TProtocolFactory protoFactory : getProtocols()) { @@ -109,7 +120,7 @@ public class TestNonblockingServer extends ServerTestBase { for (int i = 0; i < NUM_QUERIES; ++i) { try { testClient.testI32(1); - } catch(TTransportException e) { + } catch (TTransportException e) { System.err.println(e); e.printStackTrace(); if (e.getCause() instanceof java.net.SocketTimeoutException) { diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java index fb7bbdc13..42afcd3c7 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java @@ -19,6 +19,10 @@ package org.apache.thrift.server; +import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.AUTHENTICATION_FAILURE; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocolFactory; @@ -34,26 +38,28 @@ import org.apache.thrift.transport.sasl.TSaslNegotiationException; import org.junit.jupiter.api.Test; import thrift.test.ThriftTest; -import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.AUTHENTICATION_FAILURE; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class TestSaslNonblockingServer extends TestTSaslTransports.TestTSaslTransportsWithServer { private TSaslNonblockingServer server; @Override - public void startServer(TProcessor processor, TProtocolFactory protoFactory, TTransportFactory factory) + public void startServer( + TProcessor processor, TProtocolFactory protoFactory, TTransportFactory factory) throws Exception { - TNonblockingServerTransport serverSocket = new TNonblockingServerSocket( - new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(PORT)); - TSaslNonblockingServer.Args args = new TSaslNonblockingServer.Args(serverSocket) - .processor(processor) - .transportFactory(factory) - .protocolFactory(protoFactory) - .addSaslMechanism(TestTSaslTransports.WRAPPED_MECHANISM, TestTSaslTransports.SERVICE, - TestTSaslTransports.HOST, TestTSaslTransports.WRAPPED_PROPS, - new TestSaslCallbackHandler(TestTSaslTransports.PASSWORD)); + TNonblockingServerTransport serverSocket = + new TNonblockingServerSocket( + new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(PORT)); + TSaslNonblockingServer.Args args = + new TSaslNonblockingServer.Args(serverSocket) + .processor(processor) + .transportFactory(factory) + .protocolFactory(protoFactory) + .addSaslMechanism( + TestTSaslTransports.WRAPPED_MECHANISM, + TestTSaslTransports.SERVICE, + TestTSaslTransports.HOST, + TestTSaslTransports.WRAPPED_PROPS, + new TestSaslCallbackHandler(TestTSaslTransports.PASSWORD)); server = new TSaslNonblockingServer(args); server.serve(); } @@ -77,14 +83,25 @@ public class TestSaslNonblockingServer extends TestTSaslTransports.TestTSaslTran TSocket socket = new TSocket(HOST, PORT); socket.setTimeout(SOCKET_TIMEOUT); - try (TSaslClientTransport client = new TSaslClientTransport(TestTSaslTransports.WRAPPED_MECHANISM, - TestTSaslTransports.PRINCIPAL, TestTSaslTransports.SERVICE, TestTSaslTransports.HOST, - TestTSaslTransports.WRAPPED_PROPS, new TestSaslCallbackHandler("bad_password"), socket)) { - TTransportException error = assertThrows(TTransportException.class, client::open, "Client should fail with sasl negotiation."); - TSaslNegotiationException serverSideError = new TSaslNegotiationException(AUTHENTICATION_FAILURE, + try (TSaslClientTransport client = + new TSaslClientTransport( + TestTSaslTransports.WRAPPED_MECHANISM, + TestTSaslTransports.PRINCIPAL, + TestTSaslTransports.SERVICE, + TestTSaslTransports.HOST, + TestTSaslTransports.WRAPPED_PROPS, + new TestSaslCallbackHandler("bad_password"), + socket)) { + TTransportException error = + assertThrows( + TTransportException.class, client::open, "Client should fail with sasl negotiation."); + TSaslNegotiationException serverSideError = + new TSaslNegotiationException( + AUTHENTICATION_FAILURE, "Authentication failed with " + TestTSaslTransports.WRAPPED_MECHANISM); - assertTrue(error.getMessage().contains(serverSideError.getSummary()), - "Server should return error message \"" + serverSideError.getSummary() + "\""); + assertTrue( + error.getMessage().contains(serverSideError.getSummary()), + "Server should return error message \"" + serverSideError.getSummary() + "\""); } finally { stopServer(); } diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java index f532ed4c2..74205c735 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java @@ -19,6 +19,10 @@ package org.apache.thrift.server; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.ThreadPoolExecutor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; @@ -26,16 +30,9 @@ import org.apache.thrift.transport.TSocket; import org.junit.jupiter.api.Test; import thrift.test.ThriftTest; -import java.util.concurrent.ThreadPoolExecutor; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class TestThreadPoolServer { - /** - * Test server is shut down properly even with some open clients. - */ + /** Test server is shut down properly even with some open clients. */ @Test public void testStopServerWithOpenClient() throws Exception { TServerSocket serverSocket = new TServerSocket(0, 3000); @@ -53,7 +50,8 @@ public class TestThreadPoolServer { assertTrue(server.waitForShutdown()); // After server is stopped, the executor thread pool should be shut down - assertTrue(server.getExecutorService().isTerminated(), "Server thread pool should be terminated"); + assertTrue( + server.getExecutorService().isTerminated(), "Server thread pool should be terminated"); // TODO: The socket is actually closed (timeout) but the client code // ignores the timeout Exception and maintains the socket open state @@ -62,9 +60,10 @@ public class TestThreadPoolServer { } private TThreadPoolServer buildServer(TServerTransport serverSocket) { - TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverSocket) - .protocolFactory(new TBinaryProtocol.Factory()) - .processor(new ThriftTest.Processor<>(new ServerTestBase.TestHandler())); + TThreadPoolServer.Args args = + new TThreadPoolServer.Args(serverSocket) + .protocolFactory(new TBinaryProtocol.Factory()) + .processor(new ThriftTest.Processor<>(new ServerTestBase.TestHandler())); return new TThreadPoolServer(args); } } diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestThreadedSelectorServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestThreadedSelectorServer.java index ed729a296..390f6a0db 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestThreadedSelectorServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestThreadedSelectorServer.java @@ -24,7 +24,9 @@ import org.apache.thrift.server.TThreadedSelectorServer.Args; import org.apache.thrift.transport.TNonblockingServerSocket; public class TestThreadedSelectorServer extends TestNonblockingServer { - protected TServer getServer(TProcessor processor, TNonblockingServerSocket socket, TProtocolFactory protoFactory) { - return new TThreadedSelectorServer(new Args(socket).processor(processor).protocolFactory(protoFactory)); + protected TServer getServer( + TProcessor processor, TNonblockingServerSocket socket, TProtocolFactory protoFactory) { + return new TThreadedSelectorServer( + new Args(socket).processor(processor).protocolFactory(protoFactory)); } } diff --git a/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java b/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java index 94ba543a8..fee495ca7 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java +++ b/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java @@ -130,26 +130,21 @@ package org.apache.thrift.test; // Generated code import java.nio.ByteBuffer; - import thrift.test.JavaTestHelper; -/** - */ +/** */ public class EqualityTest { public static void main(String[] args) throws Exception { JavaTestHelper lhs, rhs; - lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); lhs.req_int = 1; rhs.req_int = 1; // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -157,8 +152,7 @@ public class EqualityTest { rhs.req_int = 2; // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -167,10 +161,8 @@ public class EqualityTest { rhs.setReq_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -179,8 +171,7 @@ public class EqualityTest { rhs.setReq_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -189,10 +180,8 @@ public class EqualityTest { lhs.setReq_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -201,8 +190,7 @@ public class EqualityTest { lhs.setReq_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -212,10 +200,8 @@ public class EqualityTest { rhs.setReq_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -225,8 +211,7 @@ public class EqualityTest { rhs.setReq_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -234,10 +219,8 @@ public class EqualityTest { rhs.opt_int = 1; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -245,10 +228,8 @@ public class EqualityTest { rhs.opt_int = 2; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -257,8 +238,7 @@ public class EqualityTest { rhs.setOpt_intIsSet(true); // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -267,8 +247,7 @@ public class EqualityTest { rhs.setOpt_intIsSet(true); // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -277,8 +256,7 @@ public class EqualityTest { lhs.setOpt_intIsSet(true); // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -287,8 +265,7 @@ public class EqualityTest { lhs.setOpt_intIsSet(true); // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -298,10 +275,8 @@ public class EqualityTest { rhs.setOpt_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -311,8 +286,7 @@ public class EqualityTest { rhs.setOpt_intIsSet(true); // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -322,10 +296,8 @@ public class EqualityTest { rhs.req_obj = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -335,10 +307,8 @@ public class EqualityTest { rhs.req_obj = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -347,8 +317,7 @@ public class EqualityTest { lhs.req_obj = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -357,8 +326,7 @@ public class EqualityTest { lhs.req_obj = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -367,8 +335,7 @@ public class EqualityTest { rhs.req_obj = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -377,8 +344,7 @@ public class EqualityTest { rhs.req_obj = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -386,10 +352,8 @@ public class EqualityTest { rhs.req_obj = "foo"; // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -397,8 +361,7 @@ public class EqualityTest { rhs.req_obj = "bar"; // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -408,10 +371,8 @@ public class EqualityTest { rhs.opt_obj = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -421,10 +382,8 @@ public class EqualityTest { rhs.opt_obj = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -433,8 +392,7 @@ public class EqualityTest { lhs.opt_obj = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -443,8 +401,7 @@ public class EqualityTest { lhs.opt_obj = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -453,8 +410,7 @@ public class EqualityTest { rhs.opt_obj = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -463,8 +419,7 @@ public class EqualityTest { rhs.opt_obj = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -472,10 +427,8 @@ public class EqualityTest { rhs.opt_obj = "foo"; // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); @@ -483,181 +436,156 @@ public class EqualityTest { rhs.opt_obj = "bar"; // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); lhs.req_bin = null; rhs.req_bin = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {3, 4}); lhs.req_bin = null; rhs.req_bin = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); lhs.req_bin = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {3, 4}); lhs.req_bin = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); rhs.req_bin = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {3, 4}); rhs.req_bin = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.req_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.req_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.req_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.req_bin = ByteBuffer.wrap(new byte[] {3, 4}); // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); lhs.opt_bin = null; rhs.opt_bin = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {3, 4}); lhs.opt_bin = null; rhs.opt_bin = null; // this_present = False // that_present = False - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); lhs.opt_bin = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {3, 4}); lhs.opt_bin = null; // this_present = False // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); rhs.opt_bin = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {3, 4}); rhs.opt_bin = null; // this_present = True // that_present = False - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); // this_present = True // that_present = True - if (lhs.equals(rhs) != true) - throw new RuntimeException("Failure"); - if (lhs.hashCode() != rhs.hashCode()) - throw new RuntimeException("Failure"); + if (lhs.equals(rhs) != true) throw new RuntimeException("Failure"); + if (lhs.hashCode() != rhs.hashCode()) throw new RuntimeException("Failure"); lhs = new JavaTestHelper(); rhs = new JavaTestHelper(); - lhs.opt_bin = ByteBuffer.wrap(new byte[]{1,2}); - rhs.opt_bin = ByteBuffer.wrap(new byte[]{3,4}); + lhs.opt_bin = ByteBuffer.wrap(new byte[] {1, 2}); + rhs.opt_bin = ByteBuffer.wrap(new byte[] {3, 4}); // this_present = True // that_present = True - if (lhs.equals(rhs) != false) - throw new RuntimeException("Failure"); - + if (lhs.equals(rhs) != false) throw new RuntimeException("Failure"); } } - diff --git a/lib/java/src/test/java/org/apache/thrift/test/JavaBeansTest.java b/lib/java/src/test/java/org/apache/thrift/test/JavaBeansTest.java index 0bfcefec0..f5d81ca03 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/JavaBeansTest.java +++ b/lib/java/src/test/java/org/apache/thrift/test/JavaBeansTest.java @@ -21,7 +21,6 @@ package org.apache.thrift.test; import java.nio.ByteBuffer; import java.util.LinkedList; - import thrift.test.OneOfEachBeans; public class JavaBeansTest { @@ -53,7 +52,7 @@ public class JavaBeansTest { if (ooe.is_set_some_characters()) throw new RuntimeException("isSet method error: unset field returned as set!"); - for (int i = 1; i < 12; i++){ + for (int i = 1; i < 12; i++) { if (ooe.isSet(ooe.fieldForId(i))) throw new RuntimeException("isSet method error: unset field " + i + " returned as set!"); } @@ -94,19 +93,20 @@ public class JavaBeansTest { if (!ooe.is_set_some_characters()) throw new RuntimeException("isSet method error: set field returned as unset!"); - for (int i = 1; i < 12; i++){ + for (int i = 1; i < 12; i++) { if (!ooe.isSet(ooe.fieldForId(i))) throw new RuntimeException("isSet method error: set field " + i + " returned as unset!"); } // Should throw exception when field doesn't exist boolean exceptionThrown = false; - try{ + try { ooe.isSet(ooe.fieldForId(100)); - } catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { exceptionThrown = true; } if (!exceptionThrown) - throw new RuntimeException("isSet method error: non-existent field provided as agument but no exception thrown!"); + throw new RuntimeException( + "isSet method error: non-existent field provided as agument but no exception thrown!"); } } diff --git a/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java b/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java index 4cc8f8003..f1e14e256 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java +++ b/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java @@ -21,25 +21,26 @@ package org.apache.thrift.test; import java.io.BufferedInputStream; import java.io.FileInputStream; - import org.apache.thrift.Fixtures; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TIOStreamTransport; import org.apache.thrift.transport.TTransport; - import thrift.test.CompactProtoTestStruct; public class ReadStruct { public static void main(String[] args) throws Exception { if (args.length != 2) { - System.out.println("usage: java -cp build/classes org.apache.thrift.test.ReadStruct filename proto_factory_class"); - System.out.println("Read in an instance of CompactProtocolTestStruct from 'file', making sure that it is equivalent to Fixtures.compactProtoTestStruct. Use a protocol from 'proto_factory_class'."); + System.out.println( + "usage: java -cp build/classes org.apache.thrift.test.ReadStruct filename proto_factory_class"); + System.out.println( + "Read in an instance of CompactProtocolTestStruct from 'file', making sure that it is equivalent to Fixtures.compactProtoTestStruct. Use a protocol from 'proto_factory_class'."); } - TTransport trans = new TIOStreamTransport(new BufferedInputStream(new FileInputStream(args[0]))); + TTransport trans = + new TIOStreamTransport(new BufferedInputStream(new FileInputStream(args[0]))); - TProtocolFactory factory = (TProtocolFactory)Class.forName(args[1]).newInstance(); + TProtocolFactory factory = (TProtocolFactory) Class.forName(args[1]).newInstance(); TProtocol proto = factory.getProtocol(trans); @@ -58,5 +59,4 @@ public class ReadStruct { System.out.println("Expected: " + Fixtures.getCompactProtoTestStruct() + " but got " + cpts); } } - } diff --git a/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java b/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java index 8085ef485..50c64924b 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java +++ b/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java @@ -17,7 +17,6 @@ * under the License. */ - package org.apache.thrift.test; import org.apache.thrift.Fixtures; @@ -30,11 +29,10 @@ import org.apache.thrift.transport.TMemoryBuffer; import org.apache.thrift.transport.TMemoryInputTransport; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; - import thrift.test.OneOfEach; public class SerializationBenchmark { - private final static int HOW_MANY = 10000000; + private static final int HOW_MANY = 10000000; public static void main(String[] args) throws Exception { TProtocolFactory factory = new TBinaryProtocol.Factory(); @@ -44,16 +42,30 @@ public class SerializationBenchmark { } public static void testSerialization(TProtocolFactory factory, TBase object) throws Exception { - TTransport trans = new TTransport() { - public void write(byte[] bin, int x, int y) throws TTransportException {} - public TConfiguration getConfiguration() {return new TConfiguration(); } - public void updateKnownMessageSize(long size) throws TTransportException {} - public void checkReadBytesAvailable(long numBytes) throws TTransportException {} - public int read(byte[] bin, int x, int y) throws TTransportException {return 0;} - public void close() {} - public void open() {} - public boolean isOpen() {return true;} - }; + TTransport trans = + new TTransport() { + public void write(byte[] bin, int x, int y) throws TTransportException {} + + public TConfiguration getConfiguration() { + return new TConfiguration(); + } + + public void updateKnownMessageSize(long size) throws TTransportException {} + + public void checkReadBytesAvailable(long numBytes) throws TTransportException {} + + public int read(byte[] bin, int x, int y) throws TTransportException { + return 0; + } + + public void close() {} + + public void open() {} + + public boolean isOpen() { + return true; + } + }; TProtocol proto = factory.getProtocol(trans); @@ -66,11 +78,12 @@ public class SerializationBenchmark { System.out.println("Serialization test time: " + (endTime - startTime) + " ms"); } - public static <T extends TBase> void testDeserialization(TProtocolFactory factory, T object, Class<T> klass) throws Exception { + public static <T extends TBase> void testDeserialization( + TProtocolFactory factory, T object, Class<T> klass) throws Exception { TMemoryBuffer buf = new TMemoryBuffer(0); object.write(factory.getProtocol(buf)); - byte[] serialized = new byte[100*1024]; - buf.read(serialized, 0, 100*1024); + byte[] serialized = new byte[100 * 1024]; + buf.read(serialized, 0, 100 * 1024); long startTime = System.currentTimeMillis(); for (int i = 0; i < HOW_MANY; i++) { diff --git a/lib/java/src/test/java/org/apache/thrift/test/TestServlet.java b/lib/java/src/test/java/org/apache/thrift/test/TestServlet.java index e63109da8..a23cc69e1 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/TestServlet.java +++ b/lib/java/src/test/java/org/apache/thrift/test/TestServlet.java @@ -24,29 +24,28 @@ import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.server.ServerTestBase.TestHandler; import org.apache.thrift.server.TExtensibleServlet; - import thrift.test.ThriftTest; @SuppressWarnings("serial") public class TestServlet extends TExtensibleServlet { @Override - protected TProtocolFactory getInProtocolFactory(){ - TProtocolFactory tProtocolFactory = new TCompactProtocol.Factory(); - return tProtocolFactory; + protected TProtocolFactory getInProtocolFactory() { + TProtocolFactory tProtocolFactory = new TCompactProtocol.Factory(); + return tProtocolFactory; } @Override - protected TProtocolFactory getOutProtocolFactory(){ - TProtocolFactory tProtocolFactory = new TCompactProtocol.Factory(); - return tProtocolFactory; + protected TProtocolFactory getOutProtocolFactory() { + TProtocolFactory tProtocolFactory = new TCompactProtocol.Factory(); + return tProtocolFactory; } @SuppressWarnings({"rawtypes", "unchecked"}) @Override - protected TProcessor getProcessor(){ - TestHandler testHandler = new TestHandler(); - ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); - return testProcessor; + protected TProcessor getProcessor() { + TestHandler testHandler = new TestHandler(); + ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); + return testProcessor; } } diff --git a/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java b/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java index cb60bcaa7..c17cdaad4 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java +++ b/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java @@ -21,7 +21,6 @@ package org.apache.thrift.test; import java.io.BufferedOutputStream; import java.io.FileOutputStream; - import org.apache.thrift.Fixtures; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; @@ -31,18 +30,20 @@ import org.apache.thrift.transport.TTransport; public class WriteStruct { public static void main(String[] args) throws Exception { if (args.length != 2) { - System.out.println("usage: java -cp build/classes org.apache.thrift.test.WriteStruct filename proto_factory_class"); - System.out.println("Write out an instance of Fixtures.compactProtocolTestStruct to 'file'. Use a protocol from 'proto_factory_class'."); + System.out.println( + "usage: java -cp build/classes org.apache.thrift.test.WriteStruct filename proto_factory_class"); + System.out.println( + "Write out an instance of Fixtures.compactProtocolTestStruct to 'file'. Use a protocol from 'proto_factory_class'."); } - TTransport trans = new TIOStreamTransport(new BufferedOutputStream(new FileOutputStream(args[0]))); + TTransport trans = + new TIOStreamTransport(new BufferedOutputStream(new FileOutputStream(args[0]))); - TProtocolFactory factory = (TProtocolFactory)Class.forName(args[1]).newInstance(); + TProtocolFactory factory = (TProtocolFactory) Class.forName(args[1]).newInstance(); TProtocol proto = factory.getProtocol(trans); Fixtures.getCompactProtoTestStruct().write(proto); trans.flush(); } - } diff --git a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceAsyncImp.java b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceAsyncImp.java index 419e327de..9f0733f07 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceAsyncImp.java +++ b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceAsyncImp.java @@ -28,9 +28,9 @@ import thrift.test.voidmethexceptions.TExampleException; public class ServiceAsyncImp extends ServiceBase implements TAppService01.AsyncIface { @Override - public void returnString(String msg, - boolean throwException, - AsyncMethodCallback<String> resultHandler) throws TException { + public void returnString( + String msg, boolean throwException, AsyncMethodCallback<String> resultHandler) + throws TException { if (throwException) { resultHandler.onError(new TExampleException(msg)); } else { @@ -39,9 +39,9 @@ public class ServiceAsyncImp extends ServiceBase implements TAppService01.AsyncI } @Override - public void returnVoidThrows(String msg, - boolean throwException, - AsyncMethodCallback<Void> resultHandler) throws TException { + public void returnVoidThrows( + String msg, boolean throwException, AsyncMethodCallback<Void> resultHandler) + throws TException { if (throwException) { resultHandler.onError(new TExampleException(msg)); } else { @@ -50,9 +50,9 @@ public class ServiceAsyncImp extends ServiceBase implements TAppService01.AsyncI } @Override - public void returnVoidNoThrowsRuntimeException(String msg, - boolean throwException, - AsyncMethodCallback<Void> resultHandler) throws TException { + public void returnVoidNoThrowsRuntimeException( + String msg, boolean throwException, AsyncMethodCallback<Void> resultHandler) + throws TException { if (throwException) { resultHandler.onError(new RuntimeException(msg)); } else { @@ -61,9 +61,9 @@ public class ServiceAsyncImp extends ServiceBase implements TAppService01.AsyncI } @Override - public void returnVoidNoThrowsTApplicationException(String msg, - boolean throwException, - AsyncMethodCallback<Void> resultHandler) throws TException { + public void returnVoidNoThrowsTApplicationException( + String msg, boolean throwException, AsyncMethodCallback<Void> resultHandler) + throws TException { if (throwException) { resultHandler.onError(new TApplicationException(TApplicationException.INTERNAL_ERROR, msg)); } else { @@ -72,14 +72,13 @@ public class ServiceAsyncImp extends ServiceBase implements TAppService01.AsyncI } @Override - public void onewayVoidNoThrows(String msg, - boolean throwException, - AsyncMethodCallback<Void> resultHandler) throws TException { + public void onewayVoidNoThrows( + String msg, boolean throwException, AsyncMethodCallback<Void> resultHandler) + throws TException { if (throwException) { resultHandler.onError(new TApplicationException(TApplicationException.INTERNAL_ERROR, msg)); } else { // simulate hang up } } - } diff --git a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceBase.java b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceBase.java index 5502b09cd..e12a29a52 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceBase.java +++ b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceBase.java @@ -40,5 +40,4 @@ public class ServiceBase { } } } - } diff --git a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceSyncImp.java b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceSyncImp.java index a8a08b5b9..502dc8fef 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceSyncImp.java +++ b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/ServiceSyncImp.java @@ -27,8 +27,8 @@ import thrift.test.voidmethexceptions.TExampleException; public class ServiceSyncImp extends ServiceBase implements TAppService01.Iface { @Override - public String returnString(String msg, - boolean throwException) throws TExampleException, TException { + public String returnString(String msg, boolean throwException) + throws TExampleException, TException { if (throwException) { throw new TExampleException(msg); } @@ -36,24 +36,24 @@ public class ServiceSyncImp extends ServiceBase implements TAppService01.Iface { } @Override - public void returnVoidThrows(String msg, - boolean throwException) throws TExampleException, TException { + public void returnVoidThrows(String msg, boolean throwException) + throws TExampleException, TException { if (throwException) { throw new TExampleException(msg); } } @Override - public void returnVoidNoThrowsRuntimeException(String msg, - boolean throwException) throws TException { + public void returnVoidNoThrowsRuntimeException(String msg, boolean throwException) + throws TException { if (throwException) { throw new RuntimeException(msg); } } @Override - public void returnVoidNoThrowsTApplicationException(String msg, - boolean throwException) throws TException { + public void returnVoidNoThrowsTApplicationException(String msg, boolean throwException) + throws TException { if (throwException) { throw new TApplicationException(TApplicationException.INTERNAL_ERROR, msg); } @@ -68,5 +68,4 @@ public class ServiceSyncImp extends ServiceBase implements TAppService01.Iface { waitForCancel(); } } - } diff --git a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java index b6853bd2b..a85c4d12c 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java +++ b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java @@ -19,6 +19,15 @@ package org.apache.thrift.test.voidmethexceptions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.commons.lang3.tuple.Pair; import org.apache.thrift.TApplicationException; import org.apache.thrift.TConfiguration; @@ -40,521 +49,554 @@ import org.slf4j.LoggerFactory; import thrift.test.voidmethexceptions.TAppService01; import thrift.test.voidmethexceptions.TExampleException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - public class TestVoidMethExceptions { - private static final Logger log = LoggerFactory.getLogger(TestVoidMethExceptions.class); - - private static Stream<TestParameters> provideParameters() throws Exception { - return Stream.<TestParameters>builder() - .add(new TestParameters(ServerImplementationType.SYNC_SERVER)) - .add(new TestParameters(ServerImplementationType.ASYNC_SERVER)) - .build(); + private static final Logger log = LoggerFactory.getLogger(TestVoidMethExceptions.class); + + private static Stream<TestParameters> provideParameters() throws Exception { + return Stream.<TestParameters>builder() + .add(new TestParameters(ServerImplementationType.SYNC_SERVER)) + .add(new TestParameters(ServerImplementationType.ASYNC_SERVER)) + .build(); + } + + public static class TestParameters { + private static final int TIMEOUT_MILLIS = 5_000; + private final TServer server; + private final Thread serverThread; + private final TNonblockingServerSocket serverTransport; + private int serverPort; + private final ServerImplementationType serverImplementationType; + private final CompletableFuture<Void> futureServerStarted = new CompletableFuture<>(); + + TestParameters(ServerImplementationType serverImplementationType) throws Exception { + this.serverImplementationType = serverImplementationType; + serverPort = -1; + serverImplementationType.service.setCancelled(false); + serverTransport = new TNonblockingServerSocket(0); + TNonblockingServer.Args args = new TNonblockingServer.Args(serverTransport); + args.processor(serverImplementationType.processor); + server = + new TNonblockingServer(args) { + @Override + protected void setServing(boolean serving) { + super.setServing(serving); + + if (serving) { + serverPort = serverTransport.getPort(); + futureServerStarted.complete(null); + } + } + }; + serverThread = new Thread(server::serve, "thrift-server"); + serverThread.setDaemon(true); } - public static class TestParameters { - private static final int TIMEOUT_MILLIS = 5_000; - private final TServer server; - private final Thread serverThread; - private final TNonblockingServerSocket serverTransport; - private int serverPort; - private final ServerImplementationType serverImplementationType; - private final CompletableFuture<Void> futureServerStarted = new CompletableFuture<>(); - - TestParameters(ServerImplementationType serverImplementationType) throws Exception { - this.serverImplementationType = serverImplementationType; - serverPort = -1; - serverImplementationType.service.setCancelled(false); - serverTransport = new TNonblockingServerSocket(0); - TNonblockingServer.Args args = new TNonblockingServer.Args(serverTransport); - args.processor(serverImplementationType.processor); - server = new TNonblockingServer(args) { - @Override - protected void setServing(boolean serving) { - super.setServing(serving); - - if (serving) { - serverPort = serverTransport.getPort(); - futureServerStarted.complete(null); - } - } + public AutoCloseable start() throws Exception { + serverThread.start(); + futureServerStarted.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + return () -> { + serverImplementationType.service.setCancelled(true); + server.stop(); + serverThread.join(TIMEOUT_MILLIS); + }; + } - }; - serverThread = new Thread(server::serve, "thrift-server"); - serverThread.setDaemon(true); + private void checkSyncClient( + String desc, + String msg, + boolean throwException, + String expectedResult, + Class<? extends Exception> expectedExceptionClass, + String expectedExceptionMsg, + SyncCall<TAppService01.Iface, String, Boolean, String> call) + throws Exception { + if (log.isInfoEnabled()) { + log.info( + "start test checkSyncClient::" + + desc + + ", throwException: " + + throwException + + ", serverImplementationType: " + + serverImplementationType); + } + assertNotEquals(-1, serverPort); + try (TTransport clientTransport = + new TFramedTransport( + new TSocket(new TConfiguration(), "localhost", serverPort, TIMEOUT_MILLIS))) { + clientTransport.open(); + TAppService01.Iface client = new TAppService01.Client(new TBinaryProtocol(clientTransport)); + if (throwException && expectedExceptionClass != null) { + Exception ex = + assertThrows( + expectedExceptionClass, + () -> { + call.apply(client, msg, throwException); + }); + assertEquals(expectedExceptionClass, ex.getClass()); + if (expectedExceptionMsg != null) { + assertEquals(expectedExceptionMsg, ex.getMessage()); + } + } else { + // expected + String result = call.apply(client, msg, throwException); + assertEquals(expectedResult, result); } + } + } - public AutoCloseable start() throws Exception { - serverThread.start(); - futureServerStarted.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - return () -> { - serverImplementationType.service.setCancelled(true); - server.stop(); - serverThread.join(TIMEOUT_MILLIS); - }; - } + private <T> void checkAsyncClient( + String desc, + String msg, + boolean throwException, + T expectedResult, + Class<? extends Exception> expectedExceptionClass, + String expectedExceptionMsg, + AsyncCall<TAppService01.AsyncClient, String, Boolean, AsyncMethodCallback<T>> call) + throws Throwable { + if (log.isInfoEnabled()) { + log.info( + "start test checkAsyncClient::" + + desc + + ", throwException: " + + throwException + + ", serverImplementationType: " + + serverImplementationType); + } + assertNotEquals(serverPort, -1); + try (TNonblockingSocket clientTransportAsync = + new TNonblockingSocket("localhost", serverPort, TIMEOUT_MILLIS)) { + TAsyncClientManager asyncClientManager = new TAsyncClientManager(); + try { + TAppService01.AsyncClient asyncClient = + new TAppService01.AsyncClient( + new TBinaryProtocol.Factory(), asyncClientManager, clientTransportAsync); + asyncClient.setTimeout(TIMEOUT_MILLIS); + + CompletableFuture<T> futureResult = new CompletableFuture<>(); + + call.apply( + asyncClient, + msg, + throwException, + new AsyncMethodCallback<T>() { - private void checkSyncClient(String desc, - String msg, - boolean throwException, - String expectedResult, - Class<? extends Exception> expectedExceptionClass, - String expectedExceptionMsg, - SyncCall<TAppService01.Iface, String, Boolean, String> call) throws Exception { - if (log.isInfoEnabled()) { - log.info("start test checkSyncClient::" + desc + ", throwException: " + throwException - + ", serverImplementationType: " - + serverImplementationType); - } - assertNotEquals(-1, serverPort); - try (TTransport clientTransport = new TFramedTransport(new TSocket(new TConfiguration(), - "localhost", - serverPort, - TIMEOUT_MILLIS))) { - clientTransport.open(); - TAppService01.Iface client = new TAppService01.Client(new TBinaryProtocol(clientTransport)); - if (throwException && expectedExceptionClass != null) { - Exception ex = assertThrows(expectedExceptionClass, () -> { - call.apply(client, msg, throwException); - }); - assertEquals(expectedExceptionClass, ex.getClass()); - if (expectedExceptionMsg != null) { - assertEquals(expectedExceptionMsg, ex.getMessage()); - } - } else { - // expected - String result = call.apply(client, msg, throwException); - assertEquals(expectedResult, result); + @Override + public void onError(Exception exception) { + futureResult.completeExceptionally(exception); } - } - } - - private <T> void checkAsyncClient(String desc, - String msg, - boolean throwException, - T expectedResult, - Class<? extends Exception> expectedExceptionClass, - String expectedExceptionMsg, - AsyncCall<TAppService01.AsyncClient, String, Boolean, AsyncMethodCallback<T>> call) throws Throwable { - if (log.isInfoEnabled()) { - log.info("start test checkAsyncClient::" + desc + ", throwException: " + throwException - + ", serverImplementationType: " - + serverImplementationType); - } - assertNotEquals(serverPort, -1); - try (TNonblockingSocket clientTransportAsync = new TNonblockingSocket("localhost", serverPort, TIMEOUT_MILLIS)) { - TAsyncClientManager asyncClientManager = new TAsyncClientManager(); - try { - TAppService01.AsyncClient asyncClient = new TAppService01.AsyncClient(new TBinaryProtocol.Factory(), - asyncClientManager, - clientTransportAsync); - asyncClient.setTimeout(TIMEOUT_MILLIS); - CompletableFuture<T> futureResult = new CompletableFuture<>(); - - call.apply(asyncClient, msg, throwException, new AsyncMethodCallback<T>() { - - @Override - public void onError(Exception exception) { - futureResult.completeExceptionally(exception); - } - - @Override - public void onComplete(T response) { - futureResult.complete(response); - } - - }); - if (throwException && expectedExceptionClass != null) { - Exception ex = assertThrows(expectedExceptionClass, () -> { - try { - futureResult.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } catch (ExecutionException x) { - throw x.getCause(); - } - }); - assertEquals(expectedExceptionClass, ex.getClass()); - if (expectedExceptionMsg != null) { - assertEquals(expectedExceptionMsg, ex.getMessage()); - } - } else { - T result; - try { - result = futureResult.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } catch (ExecutionException x) { - throw x.getCause(); - } - assertEquals(expectedResult, result); - } - } finally { - asyncClientManager.stop(); + @Override + public void onComplete(T response) { + futureResult.complete(response); } + }); + if (throwException && expectedExceptionClass != null) { + Exception ex = + assertThrows( + expectedExceptionClass, + () -> { + try { + futureResult.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (ExecutionException x) { + throw x.getCause(); + } + }); + assertEquals(expectedExceptionClass, ex.getClass()); + if (expectedExceptionMsg != null) { + assertEquals(expectedExceptionMsg, ex.getMessage()); } + } else { + T result; + try { + result = futureResult.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (ExecutionException x) { + throw x.getCause(); + } + assertEquals(expectedResult, result); + } + } finally { + asyncClientManager.stop(); } - - public TServer getServer() { - return server; - } + } } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustReturnResultReturnString(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnString", - "sent msg", - false, - "sent msg", - null, - null, - TAppService01.Iface::returnString); - } + public TServer getServer() { + return server; } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustReturnResultReturnVoidThrows(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnVoidThrows", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.returnVoidThrows(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnString(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnString", + "sent msg", + false, + "sent msg", + null, + null, + TAppService01.Iface::returnString); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustReturnResultReturnVoidNoThrowsRuntimeException(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.returnVoidNoThrowsRuntimeException(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnVoidThrows(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnVoidThrows", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.returnVoidThrows(msg, throwException); + return null; + }); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustReturnResultReturnVoidNoThrowsTApplicationException(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.returnVoidNoThrowsTApplicationException(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnVoidNoThrowsRuntimeException(TestParameters p) + throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnVoidNoThrowsRuntimeException", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.returnVoidNoThrowsRuntimeException(msg, throwException); + return null; + }); } - - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustThrowExceptionReturnString(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnString", - "sent msg", - true, - null, - TExampleException.class, - "sent msg", - TAppService01.Iface::returnString); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnVoidNoThrowsTApplicationException( + TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnVoidNoThrowsTApplicationException", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.returnVoidNoThrowsTApplicationException(msg, throwException); + return null; + }); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustThrowExceptionReturnVoidThrows(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnVoidThrows", - "sent msg", - true, - null, - TExampleException.class, - "sent msg", - (client, msg, throwException) -> { - client.returnVoidThrows(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnString(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnString", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + TAppService01.Iface::returnString); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException(TestParameters p) throws - Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - true, - null, - TApplicationException.class, - p.serverImplementationType == ServerImplementationType.ASYNC_SERVER ? "sent msg" - : null, // sync server return "Internal error processing returnVoidNoThrowsRuntimeException" message - (client, msg, throwException) -> { - client.returnVoidNoThrowsRuntimeException(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnVoidThrows(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnVoidThrows", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + (client, msg, throwException) -> { + client.returnVoidThrows(msg, throwException); + return null; + }); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException(TestParameters p) throws - Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - true, - null, - TApplicationException.class, - "sent msg", - (client, msg, throwException) -> { - client.returnVoidNoThrowsTApplicationException(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException(TestParameters p) + throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnVoidNoThrowsRuntimeException", + "sent msg", + true, + null, + TApplicationException.class, + p.serverImplementationType == ServerImplementationType.ASYNC_SERVER + ? "sent msg" + : null, // sync server return "Internal error processing + // returnVoidNoThrowsRuntimeException" message + (client, msg, throwException) -> { + client.returnVoidNoThrowsRuntimeException(msg, throwException); + return null; + }); } - - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustReturnResultReturnString(TestParameters p) throws Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnString", - "sent msg", - false, - "sent msg", - null, - null, - TAppService01.AsyncClient::returnString); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException( + TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "returnVoidNoThrowsTApplicationException", + "sent msg", + true, + null, + TApplicationException.class, + "sent msg", + (client, msg, throwException) -> { + client.returnVoidNoThrowsTApplicationException(msg, throwException); + return null; + }); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustReturnResultReturnVoidThrows(TestParameters p) throws Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnVoidThrows", - "sent msg", - false, - null, - null, - null, - TAppService01.AsyncClient::returnVoidThrows); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnString(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnString", + "sent msg", + false, + "sent msg", + null, + null, + TAppService01.AsyncClient::returnString); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustReturnResultReturnVoidNoThrowsRuntimeException(TestParameters p) throws - Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - false, - null, - null, - null, - TAppService01.AsyncClient::returnVoidNoThrowsRuntimeException); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnVoidThrows(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnVoidThrows", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::returnVoidThrows); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustReturnResultReturnVoidNoThrowsTApplicationException(TestParameters p) throws - Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - false, - null, - null, - null, - TAppService01.AsyncClient::returnVoidNoThrowsTApplicationException); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnVoidNoThrowsRuntimeException(TestParameters p) + throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnVoidNoThrowsRuntimeException", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::returnVoidNoThrowsRuntimeException); } - - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustThrowExceptionReturnString(TestParameters p) throws Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnString", - "sent msg", - true, - null, - TExampleException.class, - "sent msg", - TAppService01.AsyncClient::returnString); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnVoidNoThrowsTApplicationException( + TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnVoidNoThrowsTApplicationException", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::returnVoidNoThrowsTApplicationException); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustThrowExceptionReturnVoidThrows(TestParameters p) throws Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnVoidThrows", - "sent msg", - true, - null, - TExampleException.class, - "sent msg", - TAppService01.AsyncClient::returnVoidThrows); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnString(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnString", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + TAppService01.AsyncClient::returnString); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException(TestParameters p) throws - Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - true, - null, - TApplicationException.class, - p.serverImplementationType == ServerImplementationType.ASYNC_SERVER ? "sent msg" - : null, // sync server return "Internal error processing returnVoidNoThrowsRuntimeException" message - TAppService01.AsyncClient::returnVoidNoThrowsRuntimeException); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnVoidThrows(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnVoidThrows", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + TAppService01.AsyncClient::returnVoidThrows); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException(TestParameters p) throws - Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - true, - null, - TApplicationException.class, - "sent msg", - TAppService01.AsyncClient::returnVoidNoThrowsTApplicationException); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException(TestParameters p) + throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnVoidNoThrowsRuntimeException", + "sent msg", + true, + null, + TApplicationException.class, + p.serverImplementationType == ServerImplementationType.ASYNC_SERVER + ? "sent msg" + : null, // sync server return "Internal error processing + // returnVoidNoThrowsRuntimeException" message + TAppService01.AsyncClient::returnVoidNoThrowsRuntimeException); } - - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("onewayVoidNoThrows", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.onewayVoidNoThrows(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException( + TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "returnVoidNoThrowsTApplicationException", + "sent msg", + true, + null, + TApplicationException.class, + "sent msg", + TAppService01.AsyncClient::returnVoidNoThrowsTApplicationException); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testSyncClientNoWaitForResultExceptionOnewayVoidNoThrows(TestParameters p) throws Exception { - try (AutoCloseable ignored = p.start()) { - p.checkSyncClient("onewayVoidNoThrows", - "sent msg", - true, - null, - null, - null, - (client, msg, throwException) -> { - client.onewayVoidNoThrows(msg, throwException); - return null; - }); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows(TestParameters p) + throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "onewayVoidNoThrows", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.onewayVoidNoThrows(msg, throwException); + return null; + }); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows(TestParameters p) throws Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("onewayVoidNoThrows", - "sent msg", - false, - null, - null, - null, - TAppService01.AsyncClient::onewayVoidNoThrows); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientNoWaitForResultExceptionOnewayVoidNoThrows(TestParameters p) + throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient( + "onewayVoidNoThrows", + "sent msg", + true, + null, + null, + null, + (client, msg, throwException) -> { + client.onewayVoidNoThrows(msg, throwException); + return null; + }); } - - @ParameterizedTest - @MethodSource("provideParameters") - public void testAsyncClientNoWaitForResultExceptionOnewayVoidNoThrows(TestParameters p) throws Throwable { - try (AutoCloseable ignored = p.start()) { - p.checkAsyncClient("onewayVoidNoThrows", - "sent msg", - true, - null, - null, - null, - TAppService01.AsyncClient::onewayVoidNoThrows); - } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows(TestParameters p) + throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "onewayVoidNoThrows", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::onewayVoidNoThrows); } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientNoWaitForResultExceptionOnewayVoidNoThrows(TestParameters p) + throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient( + "onewayVoidNoThrows", + "sent msg", + true, + null, + null, + null, + TAppService01.AsyncClient::onewayVoidNoThrows); + } + } - - private enum ServerImplementationType { - - SYNC_SERVER(() -> { - ServiceSyncImp service = new ServiceSyncImp(); - return Pair.of(new TAppService01.Processor<>(service), service); + private enum ServerImplementationType { + SYNC_SERVER( + () -> { + ServiceSyncImp service = new ServiceSyncImp(); + return Pair.of(new TAppService01.Processor<>(service), service); }), - ASYNC_SERVER(() -> { - ServiceAsyncImp service = new ServiceAsyncImp(); - return Pair.of(new TAppService01.AsyncProcessor<>(service), service); + ASYNC_SERVER( + () -> { + ServiceAsyncImp service = new ServiceAsyncImp(); + return Pair.of(new TAppService01.AsyncProcessor<>(service), service); }); - final TProcessor processor; - final ServiceBase service; + final TProcessor processor; + final ServiceBase service; - ServerImplementationType(Supplier<Pair<TProcessor, ServiceBase>> supplier) { - Pair<TProcessor, ServiceBase> pair = supplier.get(); - this.processor = pair.getLeft(); - this.service = pair.getRight(); - } - } - - - @FunctionalInterface - private interface SyncCall<T, U, V, R> { - R apply(T t, U u, V v) throws Exception; + ServerImplementationType(Supplier<Pair<TProcessor, ServiceBase>> supplier) { + Pair<TProcessor, ServiceBase> pair = supplier.get(); + this.processor = pair.getLeft(); + this.service = pair.getRight(); } + } + @FunctionalInterface + private interface SyncCall<T, U, V, R> { + R apply(T t, U u, V v) throws Exception; + } - @FunctionalInterface - private interface AsyncCall<T, U, V, X> { - void apply(T t, U u, V v, X x) throws Exception; - } - + @FunctionalInterface + private interface AsyncCall<T, U, V, X> { + void apply(T t, U u, V v, X x) throws Exception; + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/ReadCountingTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/ReadCountingTransport.java index 1b2073cb5..078287f1e 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/ReadCountingTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/ReadCountingTransport.java @@ -18,7 +18,6 @@ */ package org.apache.thrift.transport; - import org.apache.thrift.TConfiguration; public class ReadCountingTransport extends TTransport { diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java index 0b7e4ada8..621ea094d 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java @@ -18,13 +18,12 @@ */ package org.apache.thrift.transport; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -public class TestAutoExpandingBuffer { +public class TestAutoExpandingBuffer { @Test public void testExpands() throws Exception { // has expected initial capacity diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java index 090191312..8d5783c5d 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java @@ -18,14 +18,13 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.ByteBuffer; +import org.apache.thrift.TConfiguration; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class TestAutoExpandingBufferReadTransport { +public class TestAutoExpandingBufferReadTransport { private static final byte[] HUNDRED_BYTES = new byte[100]; static { @@ -36,7 +35,8 @@ public class TestAutoExpandingBufferReadTransport { @Test public void testIt() throws Exception { - AutoExpandingBufferReadTransport t = new AutoExpandingBufferReadTransport(new TConfiguration(), 150); + AutoExpandingBufferReadTransport t = + new AutoExpandingBufferReadTransport(new TConfiguration(), 150); TMemoryInputTransport membuf = new TMemoryInputTransport(new TConfiguration(), HUNDRED_BYTES); diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java index 24249908a..44ac63f8a 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java @@ -18,59 +18,61 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; -import org.junit.jupiter.api.Test; - -import java.nio.ByteBuffer; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.nio.ByteBuffer; +import org.apache.thrift.TConfiguration; +import org.junit.jupiter.api.Test; + public class TestAutoExpandingBufferWriteTransport { - private final TConfiguration config = new TConfiguration(); + private final TConfiguration config = new TConfiguration(); - @Test - public void testIt() throws Exception { - AutoExpandingBufferWriteTransport t = new AutoExpandingBufferWriteTransport(config, 1, 0); - assertEquals(0, t.getLength()); - assertEquals(1, t.getBuf().array().length); - byte[] b1 = new byte[]{1, 2, 3}; - t.write(b1); - assertEquals(3, t.getLength()); - assertTrue(t.getBuf().array().length >= 3); - assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(t.getBuf().array(), 0, 3)); + @Test + public void testIt() throws Exception { + AutoExpandingBufferWriteTransport t = new AutoExpandingBufferWriteTransport(config, 1, 0); + assertEquals(0, t.getLength()); + assertEquals(1, t.getBuf().array().length); + byte[] b1 = new byte[] {1, 2, 3}; + t.write(b1); + assertEquals(3, t.getLength()); + assertTrue(t.getBuf().array().length >= 3); + assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(t.getBuf().array(), 0, 3)); - t.reset(); - assertEquals(0, t.getLength()); - assertTrue(t.getBuf().array().length >= 3); - byte[] b2 = new byte[]{4, 5}; - t.write(b2); - assertEquals(2, t.getLength()); - assertEquals(ByteBuffer.wrap(b2), ByteBuffer.wrap(t.getBuf().array(), 0, 2)); + t.reset(); + assertEquals(0, t.getLength()); + assertTrue(t.getBuf().array().length >= 3); + byte[] b2 = new byte[] {4, 5}; + t.write(b2); + assertEquals(2, t.getLength()); + assertEquals(ByteBuffer.wrap(b2), ByteBuffer.wrap(t.getBuf().array(), 0, 2)); - AutoExpandingBufferWriteTransport uut = new AutoExpandingBufferWriteTransport(config, 8, 4); - assertEquals(4, uut.getLength()); - assertEquals(8, uut.getBuf().array().length); - uut.write(b1); - assertEquals(7, uut.getLength()); - assertEquals(8, uut.getBuf().array().length); - assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(uut.getBuf().array(), 4, 3)); - } + AutoExpandingBufferWriteTransport uut = new AutoExpandingBufferWriteTransport(config, 8, 4); + assertEquals(4, uut.getLength()); + assertEquals(8, uut.getBuf().array().length); + uut.write(b1); + assertEquals(7, uut.getLength()); + assertEquals(8, uut.getBuf().array().length); + assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(uut.getBuf().array(), 4, 3)); + } - @Test - public void testBadInitialSize() throws TTransportException { - assertThrows(IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 0, 0)); - } + @Test + public void testBadInitialSize() throws TTransportException { + assertThrows( + IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 0, 0)); + } - @Test - public void testBadFrontReserveSize() throws IllegalArgumentException, TTransportException { - assertThrows(IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 4, -1)); - } + @Test + public void testBadFrontReserveSize() throws IllegalArgumentException, TTransportException { + assertThrows( + IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 4, -1)); + } - @Test - public void testTooSmallFrontReserveSize() throws IllegalArgumentException, TTransportException { - assertThrows(IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 4, 5)); - } + @Test + public void testTooSmallFrontReserveSize() throws IllegalArgumentException, TTransportException { + assertThrows( + IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 4, 5)); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java b/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java index 6bde36c15..57a3739cb 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java @@ -19,17 +19,16 @@ package org.apache.thrift.transport; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.nio.channels.ServerSocketChannel; - -import static org.junit.jupiter.api.Assertions.assertFalse; +import org.junit.jupiter.api.Test; public class TestNonblockingServerSocket { @Test public void testSocketChannelBlockingMode() throws TTransportException { - try (TNonblockingServerSocket nonblockingServer = new TNonblockingServerSocket(0)){ + try (TNonblockingServerSocket nonblockingServer = new TNonblockingServerSocket(0)) { ServerSocketChannel socketChannel = nonblockingServer.getServerSocketChannel(); assertFalse(socketChannel.isBlocking(), "Socket channel should be nonblocking"); } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java index 33977645d..748de121e 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java @@ -1,37 +1,42 @@ package org.apache.thrift.transport; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class TestTByteBuffer { +public class TestTByteBuffer { @Test public void testReadWrite() throws Exception { final TByteBuffer byteBuffer = new TByteBuffer(ByteBuffer.allocate(16)); byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8)); - assertEquals("Hello World", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); + assertEquals( + "Hello World", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); } @Test public void testReuseReadWrite() throws Exception { final TByteBuffer byteBuffer = new TByteBuffer(ByteBuffer.allocate(16)); byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8)); - assertEquals("Hello World", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); + assertEquals( + "Hello World", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); byteBuffer.clear(); byteBuffer.write("Goodbye Horses".getBytes(StandardCharsets.UTF_8)); - assertEquals("Goodbye Horses", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); + assertEquals( + "Goodbye Horses", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); } @Test public void testOverflow() throws Exception { final TByteBuffer byteBuffer = new TByteBuffer(ByteBuffer.allocate(4)); - TTransportException e = assertThrows(TTransportException.class, ()-> byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8))); + TTransportException e = + assertThrows( + TTransportException.class, + () -> byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8))); assertEquals("Not enough room in output buffer", e.getMessage()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTFastFramedTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTFastFramedTransport.java index 6fa23807b..51568fdbe 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTFastFramedTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTFastFramedTransport.java @@ -21,7 +21,7 @@ package org.apache.thrift.transport; import org.apache.thrift.transport.layered.TFastFramedTransport; public class TestTFastFramedTransport extends TestTFramedTransport { - protected final static int INITIAL_CAPACITY = 50; + protected static final int INITIAL_CAPACITY = 50; @Override protected TTransport getTransport(TTransport underlying) throws TTransportException { @@ -29,7 +29,8 @@ public class TestTFastFramedTransport extends TestTFramedTransport { } @Override - protected TTransport getTransport(TTransport underlying, int maxLength) throws TTransportException { + protected TTransport getTransport(TTransport underlying, int maxLength) + throws TTransportException { return new TFastFramedTransport(underlying, INITIAL_CAPACITY, maxLength); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java index 0d861bdc6..5ceefa711 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java @@ -18,9 +18,12 @@ */ package org.apache.thrift.transport; -import org.apache.thrift.transport.layered.TFastFramedTransport; -import org.apache.thrift.transport.layered.TFramedTransport; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; @@ -28,13 +31,9 @@ import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.thrift.transport.layered.TFastFramedTransport; +import org.apache.thrift.transport.layered.TFramedTransport; +import org.junit.jupiter.api.Test; public class TestTFramedTransport { @@ -42,14 +41,15 @@ public class TestTFramedTransport { return new TFramedTransport(underlying); } - protected TTransport getTransport(TTransport underlying, int maxLength) throws TTransportException { + protected TTransport getTransport(TTransport underlying, int maxLength) + throws TTransportException { return new TFramedTransport(underlying, maxLength); } public static byte[] byteSequence(int start, int end) { - byte[] result = new byte[end-start+1]; - for (int i = 0; i <= (end-start); i++) { - result[i] = (byte)(start+i); + byte[] result = new byte[end - start + 1]; + for (int i = 0; i <= (end - start); i++) { + result[i] = (byte) (start + i); } return result; } @@ -105,12 +105,15 @@ public class TestTFramedTransport { TTransport trans = getTransport(countTrans, maxLength); byte[] readBuf = new byte[10]; - TTransportException e = assertThrows(TTransportException.class, () -> trans.read(readBuf, 0, 4)); - // We expect this exception because the frame we're trying to read is larger than our max frame length + TTransportException e = + assertThrows(TTransportException.class, () -> trans.read(readBuf, 0, 4)); + // We expect this exception because the frame we're trying to read is larger than our max frame + // length assertEquals(TTransportException.CORRUPTED_DATA, e.getType()); assertFalse(trans.isOpen()); - TTransportException e2 = assertThrows(TTransportException.class, () -> trans.read(readBuf, 0, 4)); + TTransportException e2 = + assertThrows(TTransportException.class, () -> trans.read(readBuf, 0, 4)); // This time we get an exception indicating the connection was closed assertEquals(TTransportException.NOT_OPEN, e2.getType()); } @@ -118,13 +121,14 @@ public class TestTFramedTransport { @Test public void testWrite() throws TTransportException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); + WriteCountingTransport countingTrans = + new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); TTransport trans = getTransport(countingTrans); - trans.write(byteSequence(0,100)); + trans.write(byteSequence(0, 100)); assertEquals(0, countingTrans.writeCount); - trans.write(byteSequence(101,200)); - trans.write(byteSequence(201,255)); + trans.write(byteSequence(101, 200)); + trans.write(byteSequence(201, 255)); assertEquals(0, countingTrans.writeCount); trans.flush(); diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java index 4e66cf5fa..f5ae3ccad 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java @@ -18,50 +18,49 @@ package org.apache.thrift.transport; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public class TestTIOStreamTransport { - // THRIFT-5022 - @Test - public void testOpenClose_2streams() throws TTransportException { - byte[] dummy = {20}; // So the input stream isn't EOF immediately. - InputStream input = new ByteArrayInputStream(dummy); - OutputStream output = new ByteArrayOutputStream(); - TTransport transport = new TIOStreamTransport(input, output); - runOpenClose(transport); - } + // THRIFT-5022 + @Test + public void testOpenClose_2streams() throws TTransportException { + byte[] dummy = {20}; // So the input stream isn't EOF immediately. + InputStream input = new ByteArrayInputStream(dummy); + OutputStream output = new ByteArrayOutputStream(); + TTransport transport = new TIOStreamTransport(input, output); + runOpenClose(transport); + } - // THRIFT-5022 - @Test - public void testOpenClose_1input() throws TTransportException { - byte[] dummy = {20}; - InputStream input = new ByteArrayInputStream(dummy); - TTransport transport = new TIOStreamTransport(input); - runOpenClose(transport); - } + // THRIFT-5022 + @Test + public void testOpenClose_1input() throws TTransportException { + byte[] dummy = {20}; + InputStream input = new ByteArrayInputStream(dummy); + TTransport transport = new TIOStreamTransport(input); + runOpenClose(transport); + } - // THRIFT-5022 - @Test - public void testIOpenClose_1output() throws TTransportException { - OutputStream output = new ByteArrayOutputStream(); - TTransport transport = new TIOStreamTransport(output); - runOpenClose(transport); - } + // THRIFT-5022 + @Test + public void testIOpenClose_1output() throws TTransportException { + OutputStream output = new ByteArrayOutputStream(); + TTransport transport = new TIOStreamTransport(output); + runOpenClose(transport); + } - private void runOpenClose(TTransport transport) throws TTransportException { - transport.open(); - boolean b1 = transport.isOpen(); - assertTrue(b1); - transport.close(); - boolean b2 = transport.isOpen(); - assertFalse(b2); - } + private void runOpenClose(TTransport transport) throws TTransportException { + transport.open(); + boolean b1 = transport.isOpen(); + assertTrue(b1); + transport.close(); + boolean b2 = transport.isOpen(); + assertFalse(b2); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java index 482bb3a3a..888eef159 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java @@ -18,16 +18,16 @@ */ package org.apache.thrift.transport; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -public class TestTMemoryInputTransport { +import org.junit.jupiter.api.Test; + +public class TestTMemoryInputTransport { @Test public void testFresh() throws Exception { - byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + byte[] input_buf = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TMemoryInputTransport trans = new TMemoryInputTransport(input_buf); assertEquals(0, trans.getBufferPosition()); assertEquals(input_buf, trans.getBuffer()); @@ -35,7 +35,7 @@ public class TestTMemoryInputTransport { byte[] buf1 = new byte[4]; trans.readAll(buf1, 0, 4); - assertArrayEquals(new byte[]{1, 2, 3, 4}, buf1); + assertArrayEquals(new byte[] {1, 2, 3, 4}, buf1); assertEquals(4, trans.getBufferPosition()); assertEquals(6, trans.getBytesRemainingInBuffer()); @@ -45,20 +45,20 @@ public class TestTMemoryInputTransport { assertEquals(4, trans.getBytesRemainingInBuffer()); trans.readAll(buf1, 0, 4); - assertArrayEquals(new byte[]{7, 8, 9, 10}, buf1); + assertArrayEquals(new byte[] {7, 8, 9, 10}, buf1); assertEquals(10, trans.getBufferPosition()); assertEquals(0, trans.getBytesRemainingInBuffer()); } @Test public void testReused() throws Exception { - byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + byte[] input_buf = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TMemoryInputTransport trans = new TMemoryInputTransport(input_buf); assertEquals(0, trans.getBufferPosition()); assertEquals(input_buf, trans.getBuffer()); assertEquals(10, trans.getBytesRemainingInBuffer()); - byte[] new_buf = new byte[]{10, 9, 8}; + byte[] new_buf = new byte[] {10, 9, 8}; trans.reset(new_buf); assertEquals(0, trans.getBufferPosition()); assertEquals(new_buf, trans.getBuffer()); @@ -67,7 +67,7 @@ public class TestTMemoryInputTransport { @Test public void testWithOffsetAndLength() throws TTransportException { - byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + byte[] input_buf = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TMemoryInputTransport trans = new TMemoryInputTransport(input_buf, 1, 3); assertEquals(1, trans.getBufferPosition()); assertEquals(3, trans.getBytesRemainingInBuffer()); @@ -75,7 +75,7 @@ public class TestTMemoryInputTransport { { byte[] readBuffer = new byte[3]; trans.readAll(readBuffer, 0, 3); - assertArrayEquals(new byte[]{2, 3, 4}, readBuffer); + assertArrayEquals(new byte[] {2, 3, 4}, readBuffer); assertThrows(Exception.class, () -> trans.readAll(readBuffer, 0, 3)); } @@ -83,7 +83,7 @@ public class TestTMemoryInputTransport { trans.reset(input_buf, 3, 4); byte[] readBuffer2 = new byte[4]; trans.readAll(readBuffer2, 0, 4); - assertArrayEquals(new byte[]{4, 5, 6, 7}, readBuffer2); + assertArrayEquals(new byte[] {4, 5, 6, 7}, readBuffer2); } } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java index 6d221db96..9575610a0 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java @@ -19,15 +19,14 @@ package org.apache.thrift.transport; -import org.apache.thrift.TByteArrayOutputStream; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.nio.ByteBuffer; import java.util.Random; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.apache.thrift.TByteArrayOutputStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; public class TestTMemoryTransport { @@ -51,12 +50,14 @@ public class TestTMemoryTransport { public void testReadMoreThanRemaining() throws TTransportException { TMemoryTransport transport = new TMemoryTransport(new byte[] {0x00, 0x32}); byte[] read = new byte[3]; - assertThrows(TTransportException.class, new Executable() { - @Override - public void execute() throws Throwable { - transport.read(read, 0, 3); - } - }); + assertThrows( + TTransportException.class, + new Executable() { + @Override + public void execute() throws Throwable { + transport.read(read, 0, 3); + } + }); } @Test @@ -68,6 +69,8 @@ public class TestTMemoryTransport { transport.write(output2, 0, 2); byte[] expected = {0x72, 0x56, 0x29, (byte) 0xAF, (byte) 0x9B, (byte) 0x83, 0x10}; TByteArrayOutputStream outputByteArray = transport.getOutput(); - assertEquals(ByteBuffer.wrap(expected), ByteBuffer.wrap(outputByteArray.get(), 0, outputByteArray.len())); + assertEquals( + ByteBuffer.wrap(expected), + ByteBuffer.wrap(outputByteArray.get(), 0, outputByteArray.len())); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java index b5186c060..b0f709b9a 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java @@ -19,10 +19,8 @@ package org.apache.thrift.transport; -import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocolFactory; @@ -36,12 +34,15 @@ public class TestTSSLTransportFactory extends ServerTestBase { private TServer server; // TODO: Only supported on TBinaryProtocol. Doesn't work for TCompactProtocol - private static final List<TProtocolFactory> protocols = Collections.singletonList(new TBinaryProtocol.Factory()); + private static final List<TProtocolFactory> protocols = + Collections.singletonList(new TBinaryProtocol.Factory()); private static final String keyStoreLocation = System.getProperty("javax.net.ssl.keyStore"); - private static final String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); + private static final String keyStorePassword = + System.getProperty("javax.net.ssl.keyStorePassword"); private static final String trustStoreLocation = System.getProperty("javax.net.ssl.trustStore"); - private static final String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); + private static final String trustStorePassword = + System.getProperty("javax.net.ssl.trustStorePassword"); protected final String getKeyStoreLocation() { return keyStoreLocation; @@ -60,8 +61,7 @@ public class TestTSSLTransportFactory extends ServerTestBase { } @Override - public TTransport getClientTransport(TTransport underlyingTransport) - throws Exception { + public TTransport getClientTransport(TTransport underlyingTransport) throws Exception { return TSSLTransportFactory.getClientSocket(HOST, PORT); } @@ -70,19 +70,24 @@ public class TestTSSLTransportFactory extends ServerTestBase { } @Override - public void startServer(final TProcessor processor, final TProtocolFactory protoFactory, final TTransportFactory factory) - throws Exception { - serverThread = new Thread(() -> { - try { - TServerTransport serverTransport = getServerTransport(); - final Args args = new Args(serverTransport).processor(processor); - server = new TSimpleServer(args); - server.serve(); - } catch (Exception e) { - e.printStackTrace(); - assert false; - } - }); + public void startServer( + final TProcessor processor, + final TProtocolFactory protoFactory, + final TTransportFactory factory) + throws Exception { + serverThread = + new Thread( + () -> { + try { + TServerTransport serverTransport = getServerTransport(); + final Args args = new Args(serverTransport).processor(processor); + server = new TSimpleServer(args); + server.serve(); + } catch (Exception e) { + e.printStackTrace(); + assert false; + } + }); serverThread.start(); Thread.sleep(SLEEP_DELAY); diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java index 6b543e3a3..6a69872e8 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java @@ -22,11 +22,10 @@ package org.apache.thrift.transport; public class TestTSSLTransportFactoryCustomClient1 extends TestTSSLTransportFactory { @Override - public TTransport getClientTransport(TTransport underlyingTransport) - throws Exception { - TSSLTransportFactory.TSSLTransportParameters params = new - TSSLTransportFactory.TSSLTransportParameters(); + public TTransport getClientTransport(TTransport underlyingTransport) throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = + new TSSLTransportFactory.TSSLTransportParameters(); params.setTrustStore(getTrustStoreLocation(), getTrustStorePassword()); - return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0 /*timeout*/, params); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java index 2427b9be3..cd0229f2a 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java @@ -22,11 +22,10 @@ package org.apache.thrift.transport; public class TestTSSLTransportFactoryCustomClient2 extends TestTSSLTransportFactory { @Override - public TTransport getClientTransport(TTransport underlyingTransport) - throws Exception { - TSSLTransportFactory.TSSLTransportParameters params = new - TSSLTransportFactory.TSSLTransportParameters(); + public TTransport getClientTransport(TTransport underlyingTransport) throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = + new TSSLTransportFactory.TSSLTransportParameters(); params.setTrustStore(getTrustStoreLocation(), null); - return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0 /*timeout*/, params); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java index cc3cb68ca..55b965f75 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java @@ -25,23 +25,23 @@ import java.net.InetAddress; public class TestTSSLTransportFactoryStreamedStore extends TestTSSLTransportFactory { @Override - public TTransport getClientTransport(TTransport underlyingTransport) - throws Exception { - TSSLTransportFactory.TSSLTransportParameters params = new - TSSLTransportFactory.TSSLTransportParameters(); + public TTransport getClientTransport(TTransport underlyingTransport) throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = + new TSSLTransportFactory.TSSLTransportParameters(); params.setTrustStore(new FileInputStream(getTrustStoreLocation()), getTrustStorePassword()); - return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0 /*timeout*/, params); } @Override protected TServerSocket getServerTransport() throws Exception { - TSSLTransportFactory.TSSLTransportParameters params = new - TSSLTransportFactory.TSSLTransportParameters(); + TSSLTransportFactory.TSSLTransportParameters params = + new TSSLTransportFactory.TSSLTransportParameters(); params.setKeyStore(new FileInputStream(getKeyStoreLocation()), getKeyStorePassword()); - return TSSLTransportFactory.getServerSocket(PORT, 0/*timeout*/, InetAddress.getByName(HOST), params); + return TSSLTransportFactory.getServerSocket( + PORT, 0 /*timeout*/, InetAddress.getByName(HOST), params); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java index 7cc5ca6c6..224da216d 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java @@ -19,17 +19,17 @@ package org.apache.thrift.transport; -import org.apache.thrift.TConfiguration; -import org.apache.thrift.TProcessor; -import org.apache.thrift.protocol.TProtocolFactory; -import org.apache.thrift.server.ServerTestBase; -import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TServer.Args; -import org.apache.thrift.server.TSimpleServer; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; @@ -43,19 +43,18 @@ import javax.security.sasl.SaslClientFactory; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import org.apache.thrift.TConfiguration; +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TProtocolFactory; +import org.apache.thrift.server.ServerTestBase; +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TServer.Args; +import org.apache.thrift.server.TSimpleServer; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -public class TestTSaslTransports { +public class TestTSaslTransports { private static final Logger LOGGER = LoggerFactory.getLogger(TestTSaslTransports.class); @@ -76,15 +75,16 @@ public class TestTSaslTransports { WRAPPED_PROPS.put("com.sun.security.sasl.digest.realm", REALM); } - private static final String testMessage1 = "Hello, world! Also, four " - + "score and seven years ago our fathers brought forth on this " - + "continent a new nation, conceived in liberty, and dedicated to the " - + "proposition that all men are created equal."; - - private static final String testMessage2 = "I have a dream that one day " - + "this nation will rise up and live out the true meaning of its creed: " - + "'We hold these truths to be self-evident, that all men are created equal.'"; + private static final String testMessage1 = + "Hello, world! Also, four " + + "score and seven years ago our fathers brought forth on this " + + "continent a new nation, conceived in liberty, and dedicated to the " + + "proposition that all men are created equal."; + private static final String testMessage2 = + "I have a dream that one day " + + "this nation will rise up and live out the true meaning of its creed: " + + "'We hold these truths to be self-evident, that all men are created equal.'"; public static class TestSaslCallbackHandler implements CallbackHandler { private final String password; @@ -130,19 +130,23 @@ public class TestTSaslTransports { } private void internalRun() throws Exception { - try (TServerSocket serverSocket = new TServerSocket( - new TServerSocket.ServerSocketTransportArgs(). - port(ServerTestBase.PORT))) { + try (TServerSocket serverSocket = + new TServerSocket( + new TServerSocket.ServerSocketTransportArgs().port(ServerTestBase.PORT))) { acceptAndWrite(serverSocket); } } - private void acceptAndWrite(TServerSocket serverSocket) - throws Exception { + private void acceptAndWrite(TServerSocket serverSocket) throws Exception { TTransport serverTransport = serverSocket.accept(); - TTransport saslServerTransport = new TSaslServerTransport( - mechanism, SERVICE, HOST, - props, new TestSaslCallbackHandler(PASSWORD), serverTransport); + TTransport saslServerTransport = + new TSaslServerTransport( + mechanism, + SERVICE, + HOST, + props, + new TestSaslCallbackHandler(PASSWORD), + serverTransport); saslServerTransport.open(); @@ -177,8 +181,15 @@ public class TestTSaslTransports { try { TSocket clientSocket = new TSocket(HOST, ServerTestBase.PORT); - TTransport saslClientTransport = new TSaslClientTransport(mechanism, - PRINCIPAL, SERVICE, HOST, props, new TestSaslCallbackHandler(PASSWORD), clientSocket); + TTransport saslClientTransport = + new TSaslClientTransport( + mechanism, + PRINCIPAL, + SERVICE, + HOST, + props, + new TestSaslCallbackHandler(PASSWORD), + clientSocket); saslClientTransport.open(); LOGGER.debug("client writing: {}", testMessage1); saslClientTransport.write(testMessage1.getBytes()); @@ -228,8 +239,8 @@ public class TestTSaslTransports { } /** - * Test that we get the proper exceptions thrown back the server when - * the client provides invalid password. + * Test that we get the proper exceptions thrown back the server when the client provides invalid + * password. */ @Test public void testBadPassword() throws Exception { @@ -242,13 +253,23 @@ public class TestTSaslTransports { // Ah well. } - TTransportException tte = assertThrows(TTransportException.class, () -> { - TSocket clientSocket = new TSocket(HOST, ServerTestBase.PORT); - TTransport saslClientTransport = new TSaslClientTransport( - UNWRAPPED_MECHANISM, PRINCIPAL, SERVICE, HOST, UNWRAPPED_PROPS, - new TestSaslCallbackHandler("NOT THE PASSWORD"), clientSocket); - saslClientTransport.open(); - }, "Was able to open transport with bad password"); + TTransportException tte = + assertThrows( + TTransportException.class, + () -> { + TSocket clientSocket = new TSocket(HOST, ServerTestBase.PORT); + TTransport saslClientTransport = + new TSaslClientTransport( + UNWRAPPED_MECHANISM, + PRINCIPAL, + SERVICE, + HOST, + UNWRAPPED_PROPS, + new TestSaslCallbackHandler("NOT THE PASSWORD"), + clientSocket); + saslClientTransport.open(); + }, + "Was able to open transport with bad password"); LOGGER.error("Exception for bad password", tte); assertNotNull(tte.getMessage()); assertTrue(tte.getMessage().contains("Invalid response")); @@ -271,32 +292,52 @@ public class TestTSaslTransports { @Override public TTransport getClientTransport(TTransport underlyingTransport) throws Exception { return new TSaslClientTransport( - WRAPPED_MECHANISM, PRINCIPAL, SERVICE, HOST, WRAPPED_PROPS, - new TestSaslCallbackHandler(PASSWORD), underlyingTransport); + WRAPPED_MECHANISM, + PRINCIPAL, + SERVICE, + HOST, + WRAPPED_PROPS, + new TestSaslCallbackHandler(PASSWORD), + underlyingTransport); } @Override - public void startServer(final TProcessor processor, final TProtocolFactory protoFactory, final TTransportFactory factory) throws Exception { - serverThread = new Thread() { - public void run() { - try { - // Transport - TServerSocket socket = new TServerSocket(new TServerSocket.ServerSocketTransportArgs().port(PORT)); - - TTransportFactory factory = new TSaslServerTransport.Factory( - WRAPPED_MECHANISM, SERVICE, HOST, WRAPPED_PROPS, - new TestSaslCallbackHandler(PASSWORD)); - server = new TSimpleServer(new Args(socket).processor(processor).transportFactory(factory).protocolFactory(protoFactory)); - - // Run it - LOGGER.debug("Starting the server on port {}", PORT); - server.serve(); - } catch (Exception e) { - e.printStackTrace(); - fail(e); - } - } - }; + public void startServer( + final TProcessor processor, + final TProtocolFactory protoFactory, + final TTransportFactory factory) + throws Exception { + serverThread = + new Thread() { + public void run() { + try { + // Transport + TServerSocket socket = + new TServerSocket(new TServerSocket.ServerSocketTransportArgs().port(PORT)); + + TTransportFactory factory = + new TSaslServerTransport.Factory( + WRAPPED_MECHANISM, + SERVICE, + HOST, + WRAPPED_PROPS, + new TestSaslCallbackHandler(PASSWORD)); + server = + new TSimpleServer( + new Args(socket) + .processor(processor) + .transportFactory(factory) + .protocolFactory(protoFactory)); + + // Run it + LOGGER.debug("Starting the server on port {}", PORT); + server.serve(); + } catch (Exception e) { + e.printStackTrace(); + fail(e); + } + } + }; serverThread.start(); Thread.sleep(1000); } @@ -310,14 +351,9 @@ public class TestTSaslTransports { LOGGER.debug("interrupted during sleep", e); } } - } - - /** - * Implementation of SASL ANONYMOUS, used for testing client-side - * initial responses. - */ + /** Implementation of SASL ANONYMOUS, used for testing client-side initial responses. */ private static class AnonymousClient implements SaslClient { private final String username; private boolean hasProvidedInitialResponse; @@ -327,9 +363,15 @@ public class TestTSaslTransports { } @Override - public String getMechanismName() { return "ANONYMOUS"; } + public String getMechanismName() { + return "ANONYMOUS"; + } + @Override - public boolean hasInitialResponse() { return true; } + public boolean hasInitialResponse() { + return true; + } + @Override public byte[] evaluateChallenge(byte[] challenge) throws SaslException { if (hasProvidedInitialResponse) { @@ -339,58 +381,84 @@ public class TestTSaslTransports { hasProvidedInitialResponse = true; return username.getBytes(StandardCharsets.UTF_8); } + @Override - public boolean isComplete() { return hasProvidedInitialResponse; } + public boolean isComplete() { + return hasProvidedInitialResponse; + } + @Override public byte[] unwrap(byte[] incoming, int offset, int len) { throw new UnsupportedOperationException(); } + @Override public byte[] wrap(byte[] outgoing, int offset, int len) { throw new UnsupportedOperationException(); } + @Override - public Object getNegotiatedProperty(String propName) { return null; } + public Object getNegotiatedProperty(String propName) { + return null; + } + @Override public void dispose() {} } private static class AnonymousServer implements SaslServer { private String user; + @Override - public String getMechanismName() { return "ANONYMOUS"; } + public String getMechanismName() { + return "ANONYMOUS"; + } + @Override public byte[] evaluateResponse(byte[] response) throws SaslException { this.user = new String(response, StandardCharsets.UTF_8); return null; } + @Override - public boolean isComplete() { return user != null; } + public boolean isComplete() { + return user != null; + } + @Override - public String getAuthorizationID() { return user; } + public String getAuthorizationID() { + return user; + } + @Override public byte[] unwrap(byte[] incoming, int offset, int len) { throw new UnsupportedOperationException(); } + @Override public byte[] wrap(byte[] outgoing, int offset, int len) { throw new UnsupportedOperationException(); } + @Override - public Object getNegotiatedProperty(String propName) { return null; } + public Object getNegotiatedProperty(String propName) { + return null; + } + @Override public void dispose() {} - } - public static class SaslAnonymousFactory - implements SaslClientFactory, SaslServerFactory { + public static class SaslAnonymousFactory implements SaslClientFactory, SaslServerFactory { @Override public SaslClient createSaslClient( - String[] mechanisms, String authorizationId, String protocol, - String serverName, Map<String,?> props, CallbackHandler cbh) - { + String[] mechanisms, + String authorizationId, + String protocol, + String serverName, + Map<String, ?> props, + CallbackHandler cbh) { for (String mech : mechanisms) { if ("ANONYMOUS".equals(mech)) { return new AnonymousClient(authorizationId); @@ -401,22 +469,27 @@ public class TestTSaslTransports { @Override public SaslServer createSaslServer( - String mechanism, String protocol, String serverName, Map<String,?> props, CallbackHandler cbh) - { + String mechanism, + String protocol, + String serverName, + Map<String, ?> props, + CallbackHandler cbh) { if ("ANONYMOUS".equals(mechanism)) { return new AnonymousServer(); } return null; } + @Override public String[] getMechanismNames(Map<String, ?> props) { - return new String[] { "ANONYMOUS" }; + return new String[] {"ANONYMOUS"}; } } static { java.security.Security.addProvider(new SaslAnonymousProvider()); } + public static class SaslAnonymousProvider extends java.security.Provider { public SaslAnonymousProvider() { super("ThriftSaslAnonymous", 1.0, "Thrift Anonymous SASL provider"); @@ -432,15 +505,15 @@ public class TestTSaslTransports { public MockTTransport(int mode) throws TTransportException { readBuffer = new TMemoryInputTransport(); - if (mode==1) { + if (mode == 1) { // Invalid status byte - badHeader = new byte[] { (byte)0xFF, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05 }; + badHeader = new byte[] {(byte) 0xFF, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05}; } else if (mode == 2) { // Valid status byte, negative payload length - badHeader = new byte[] { (byte)0x01, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF }; + badHeader = new byte[] {(byte) 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}; } else if (mode == 3) { // Valid status byte, excessively large, bogus payload length - badHeader = new byte[] { (byte)0x01, (byte)0x64, (byte)0x00, (byte)0x00, (byte)0x00 }; + badHeader = new byte[] {(byte) 0x01, (byte) 0x64, (byte) 0x00, (byte) 0x00, (byte) 0x00}; } readBuffer.reset(badHeader); } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java index 926b78220..94c1f3296 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java @@ -18,41 +18,41 @@ */ package org.apache.thrift.transport; -import org.junit.jupiter.api.Test; - -import java.nio.file.Files; -import java.nio.file.Path; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -public class TestTSimpleFileTransport { +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; + +public class TestTSimpleFileTransport { @Test public void testFresh() throws Exception { - //Test write side + // Test write side Path tempFilePathName = Files.createTempFile("TSimpleFileTransportTest", null); Files.delete(tempFilePathName); - byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - TSimpleFileTransport trans_write = new TSimpleFileTransport(tempFilePathName.toString(),false, true, false); + byte[] input_buf = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + TSimpleFileTransport trans_write = + new TSimpleFileTransport(tempFilePathName.toString(), false, true, false); assert (!trans_write.isOpen()); trans_write.open(); - assert(trans_write.isOpen()); + assert (trans_write.isOpen()); trans_write.write(input_buf); - trans_write.write(input_buf,2,2); + trans_write.write(input_buf, 2, 2); trans_write.flush(); trans_write.close(); - //Test read side - TSimpleFileTransport trans = new TSimpleFileTransport(tempFilePathName.toString(),true, false); - assert(trans.isOpen()); + // Test read side + TSimpleFileTransport trans = new TSimpleFileTransport(tempFilePathName.toString(), true, false); + assert (trans.isOpen()); - //Simple file trans provides no buffer access + // Simple file trans provides no buffer access assertEquals(0, trans.getBufferPosition()); assertNull(trans.getBuffer()); assertEquals(-1, trans.getBytesRemainingInBuffer()); - //Test file pointer operations + // Test file pointer operations assertEquals(0, trans.getFilePointer()); assertEquals(12, trans.length()); @@ -60,10 +60,10 @@ public class TestTSimpleFileTransport { byte[] buf1 = new byte[BUFSIZ]; trans.readAll(buf1, 0, BUFSIZ); assertEquals(BUFSIZ, trans.getFilePointer()); - assertArrayEquals(new byte[]{1, 2, 3, 4}, buf1); + assertArrayEquals(new byte[] {1, 2, 3, 4}, buf1); int bytesRead = trans.read(buf1, 0, BUFSIZ); - assert(bytesRead > 0); + assert (bytesRead > 0); for (int i = 0; i < bytesRead; ++i) { assertEquals(buf1[i], i + 5); } @@ -71,7 +71,7 @@ public class TestTSimpleFileTransport { trans.seek(0); assertEquals(0, trans.getFilePointer()); trans.readAll(buf1, 0, BUFSIZ); - assertArrayEquals(new byte[]{1, 2, 3, 4}, buf1); + assertArrayEquals(new byte[] {1, 2, 3, 4}, buf1); assertEquals(BUFSIZ, trans.getFilePointer()); trans.close(); Files.delete(tempFilePathName); diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java index 75e917f6a..345a4d708 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java @@ -18,7 +18,8 @@ */ package org.apache.thrift.transport; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; @@ -29,20 +30,18 @@ import java.io.IOException; import java.util.zip.DataFormatException; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class TestTZlibTransport { +public class TestTZlibTransport { protected TTransport getTransport(TTransport underlying) throws TTransportException { return new TZlibTransport(underlying); } public static byte[] byteSequence(int start, int end) { - byte[] result = new byte[end-start+1]; - for (int i = 0; i <= (end-start); i++) { - result[i] = (byte)(start+i); + byte[] result = new byte[end - start + 1]; + for (int i = 0; i <= (end - start); i++) { + result[i] = (byte) (start + i); } return result; } @@ -50,8 +49,8 @@ public class TestTZlibTransport { @Test public void testClose() throws TTransportException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream - (baos))); + WriteCountingTransport countingTrans = + new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); TTransport trans = getTransport(countingTrans); trans.write(byteSequence(0, 245)); countingTrans.close(); @@ -68,7 +67,8 @@ public class TestTZlibTransport { final byte[] compressed = baos.toByteArray(); final byte[] buf = new byte[255]; - TTransport transRead = getTransport(new TIOStreamTransport(new ByteArrayInputStream(compressed))); + TTransport transRead = + getTransport(new TIOStreamTransport(new ByteArrayInputStream(compressed))); int readBytes = transRead.read(buf, 0, buf.length); assertEquals(uncompressed.length, readBytes); transRead.close(); @@ -111,7 +111,8 @@ public class TestTZlibTransport { @Test public void testWrite() throws TTransportException, IOException, DataFormatException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); + WriteCountingTransport countingTrans = + new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); TTransport trans = getTransport(countingTrans); trans.write(byteSequence(0, 100)); @@ -127,7 +128,8 @@ public class TestTZlibTransport { trans.flush(); assertEquals(3, countingTrans.writeCount); - DataInputStream din = new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(baos.toByteArray()))); + DataInputStream din = + new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(baos.toByteArray()))); byte[] buf = new byte[256]; int n = din.read(buf, 0, 256); assertEquals(n, 256); @@ -136,11 +138,10 @@ public class TestTZlibTransport { buf = new byte[246]; n = din.read(buf, 0, 246); assertEquals(n, 246); - for (int i = 0; i<buf.length; i++) { - assertEquals(byteSequence(0,245)[i], buf[i], "for "+i); + for (int i = 0; i < buf.length; i++) { + assertEquals(byteSequence(0, 245)[i], buf[i], "for " + i); } assertArrayEquals(byteSequence(0, 245), buf); } - } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/WriteCountingTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/WriteCountingTransport.java index 50b778b89..cb05a928b 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/WriteCountingTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/WriteCountingTransport.java @@ -18,7 +18,6 @@ */ package org.apache.thrift.transport; - import org.apache.thrift.TConfiguration; public class WriteCountingTransport extends TTransport { @@ -33,7 +32,9 @@ public class WriteCountingTransport extends TTransport { public void close() {} @Override - public boolean isOpen() {return true;} + public boolean isOpen() { + return true; + } @Override public void open() throws TTransportException {} @@ -45,7 +46,7 @@ public class WriteCountingTransport extends TTransport { @Override public void write(byte[] buf, int off, int len) throws TTransportException { - writeCount ++; + writeCount++; trans.write(buf, off, len); } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java index 4b90cceca..4288d4a65 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java @@ -19,23 +19,23 @@ package org.apache.thrift.transport.sasl; -import org.apache.thrift.transport.TMemoryInputTransport; -import org.apache.thrift.transport.TTransportException; -import org.junit.jupiter.api.Test; - -import java.nio.ByteBuffer; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.nio.ByteBuffer; +import org.apache.thrift.transport.TMemoryInputTransport; +import org.apache.thrift.transport.TTransportException; +import org.junit.jupiter.api.Test; + public class TestDataFrameReader { @Test public void testRead() throws TTransportException { // Prepare data int payloadSize = 23; - ByteBuffer buffer = ByteBuffer.allocate(DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES + payloadSize); + ByteBuffer buffer = + ByteBuffer.allocate(DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES + payloadSize); buffer.putInt(payloadSize); for (int i = 0; i < payloadSize; i++) { buffer.put((byte) i); @@ -53,12 +53,18 @@ public class TestDataFrameReader { dataFrameReader.read(transport); assertFalse(dataFrameReader.isComplete(), "Only header is complete"); assertTrue(dataFrameReader.getHeader().isComplete(), "Header should be complete"); - assertEquals(payloadSize, dataFrameReader.getHeader().payloadSize(), "Payload size should be " + payloadSize); + assertEquals( + payloadSize, + dataFrameReader.getHeader().payloadSize(), + "Payload size should be " + payloadSize); // Read the rest of payload. transport.reset(buffer.array(), 6, 21); dataFrameReader.read(transport); assertTrue(dataFrameReader.isComplete(), "Reader should be complete"); buffer.position(DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES); - assertEquals(buffer, ByteBuffer.wrap(dataFrameReader.getPayload()), "Payload should be the same as from the transport"); + assertEquals( + buffer, + ByteBuffer.wrap(dataFrameReader.getPayload()), + "Payload should be the same as from the transport"); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java index b6f4529e7..741a5f78f 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java @@ -19,6 +19,13 @@ package org.apache.thrift.transport.sasl; +import static org.apache.thrift.transport.sasl.DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.ByteBuffer; import org.apache.thrift.EncodingUtils; import org.apache.thrift.transport.TNonblockingTransport; import org.junit.jupiter.api.Test; @@ -26,80 +33,76 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.nio.ByteBuffer; - -import static org.apache.thrift.transport.sasl.DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class TestDataFrameWriter { - private static final byte[] BYTES = new byte[]{0x32, 0x2A, (byte) 0xE1, 0x18, (byte) 0x90, 0x75}; + private static final byte[] BYTES = new byte[] {0x32, 0x2A, (byte) 0xE1, 0x18, (byte) 0x90, 0x75}; - @Test - public void testProvideEntireByteArrayAsPayload() { - DataFrameWriter frameWriter = new DataFrameWriter(); - frameWriter.withOnlyPayload(BYTES); - byte[] expectedBytes = new byte[BYTES.length + PAYLOAD_LENGTH_BYTES]; - EncodingUtils.encodeBigEndian(BYTES.length, expectedBytes); - System.arraycopy(BYTES, 0, expectedBytes, PAYLOAD_LENGTH_BYTES, BYTES.length); - assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); - } + @Test + public void testProvideEntireByteArrayAsPayload() { + DataFrameWriter frameWriter = new DataFrameWriter(); + frameWriter.withOnlyPayload(BYTES); + byte[] expectedBytes = new byte[BYTES.length + PAYLOAD_LENGTH_BYTES]; + EncodingUtils.encodeBigEndian(BYTES.length, expectedBytes); + System.arraycopy(BYTES, 0, expectedBytes, PAYLOAD_LENGTH_BYTES, BYTES.length); + assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); + } - @Test - public void testProvideByteArrayPortionAsPayload() { - DataFrameWriter frameWriter = new DataFrameWriter(); - int portionOffset = 2; - int portionLength = 3; - frameWriter.withOnlyPayload(BYTES, portionOffset, portionLength); - byte[] expectedBytes = new byte[portionLength + PAYLOAD_LENGTH_BYTES]; - EncodingUtils.encodeBigEndian(portionLength, expectedBytes); - System.arraycopy(BYTES, portionOffset, expectedBytes, PAYLOAD_LENGTH_BYTES, portionLength); - assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); - } + @Test + public void testProvideByteArrayPortionAsPayload() { + DataFrameWriter frameWriter = new DataFrameWriter(); + int portionOffset = 2; + int portionLength = 3; + frameWriter.withOnlyPayload(BYTES, portionOffset, portionLength); + byte[] expectedBytes = new byte[portionLength + PAYLOAD_LENGTH_BYTES]; + EncodingUtils.encodeBigEndian(portionLength, expectedBytes); + System.arraycopy(BYTES, portionOffset, expectedBytes, PAYLOAD_LENGTH_BYTES, portionLength); + assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); + } - @Test - public void testProvideHeaderAndPayload() { - DataFrameWriter frameWriter = new DataFrameWriter(); - assertThrows(IllegalArgumentException.class, () -> frameWriter.withHeaderAndPayload(new byte[1], new byte[1])); - } + @Test + public void testProvideHeaderAndPayload() { + DataFrameWriter frameWriter = new DataFrameWriter(); + assertThrows( + IllegalArgumentException.class, + () -> frameWriter.withHeaderAndPayload(new byte[1], new byte[1])); + } - @Test - public void testProvidePayloadToIncompleteFrame() { - DataFrameWriter frameWriter = new DataFrameWriter(); - assertThrows(IllegalStateException.class, () -> { - frameWriter.withOnlyPayload(BYTES); - frameWriter.withOnlyPayload(new byte[1]); + @Test + public void testProvidePayloadToIncompleteFrame() { + DataFrameWriter frameWriter = new DataFrameWriter(); + assertThrows( + IllegalStateException.class, + () -> { + frameWriter.withOnlyPayload(BYTES); + frameWriter.withOnlyPayload(new byte[1]); }); - } + } - @Test - public void testWrite() throws Exception { - DataFrameWriter frameWriter = new DataFrameWriter(); - frameWriter.withOnlyPayload(BYTES); - // Slow socket which writes one byte per call. - TNonblockingTransport transport = Mockito.mock(TNonblockingTransport.class); - SlowWriting slowWriting = new SlowWriting(); - Mockito.when(transport.write(frameWriter.frameBytes)).thenAnswer(slowWriting); - frameWriter.write(transport); - while (slowWriting.written < frameWriter.frameBytes.limit()) { - assertFalse(frameWriter.isComplete(), "Frame writer should not be complete"); - frameWriter.write(transport); - } - assertTrue(frameWriter.isComplete(), "Frame writer should be complete"); + @Test + public void testWrite() throws Exception { + DataFrameWriter frameWriter = new DataFrameWriter(); + frameWriter.withOnlyPayload(BYTES); + // Slow socket which writes one byte per call. + TNonblockingTransport transport = Mockito.mock(TNonblockingTransport.class); + SlowWriting slowWriting = new SlowWriting(); + Mockito.when(transport.write(frameWriter.frameBytes)).thenAnswer(slowWriting); + frameWriter.write(transport); + while (slowWriting.written < frameWriter.frameBytes.limit()) { + assertFalse(frameWriter.isComplete(), "Frame writer should not be complete"); + frameWriter.write(transport); } + assertTrue(frameWriter.isComplete(), "Frame writer should be complete"); + } - private static class SlowWriting implements Answer<Integer> { - int written = 0; + private static class SlowWriting implements Answer<Integer> { + int written = 0; - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - ByteBuffer bytes = (ByteBuffer) invocation.getArguments()[0]; - bytes.get(); - written++; - return 1; - } + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer bytes = (ByteBuffer) invocation.getArguments()[0]; + bytes.get(); + written++; + return 1; } + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java index 7c4556a6c..fef88835e 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java @@ -19,52 +19,53 @@ package org.apache.thrift.transport.sasl; -import org.apache.thrift.transport.TMemoryInputTransport; -import org.apache.thrift.transport.TTransportException; -import org.junit.jupiter.api.Test; - -import java.nio.ByteBuffer; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.nio.ByteBuffer; +import org.apache.thrift.transport.TMemoryInputTransport; +import org.apache.thrift.transport.TTransportException; +import org.junit.jupiter.api.Test; + public class TestSaslNegotiationFrameReader { - @Test - public void testRead() throws TTransportException { - TMemoryInputTransport transport = new TMemoryInputTransport(); - SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); - // No bytes received - negotiationReader.read(transport); - assertFalse(negotiationReader.isComplete(), "No bytes received"); - assertFalse(negotiationReader.getHeader().isComplete(), "No bytes received"); - // Read header - ByteBuffer buffer = ByteBuffer.allocate(5); - buffer.put(0, NegotiationStatus.OK.getValue()); - buffer.putInt(1, 10); - transport.reset(buffer.array()); - negotiationReader.read(transport); - assertFalse(negotiationReader.isComplete(), "Only header is complete"); - assertTrue(negotiationReader.getHeader().isComplete(), "Header should be complete"); - assertEquals(10, negotiationReader.getHeader().payloadSize(), "Payload size should be 10"); - // Read payload - transport.reset(new byte[20]); - negotiationReader.read(transport); - assertTrue(negotiationReader.isComplete(), "Reader should be complete"); - assertEquals(10, negotiationReader.getPayload().length, "Payload length should be 10"); - } + @Test + public void testRead() throws TTransportException { + TMemoryInputTransport transport = new TMemoryInputTransport(); + SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); + // No bytes received + negotiationReader.read(transport); + assertFalse(negotiationReader.isComplete(), "No bytes received"); + assertFalse(negotiationReader.getHeader().isComplete(), "No bytes received"); + // Read header + ByteBuffer buffer = ByteBuffer.allocate(5); + buffer.put(0, NegotiationStatus.OK.getValue()); + buffer.putInt(1, 10); + transport.reset(buffer.array()); + negotiationReader.read(transport); + assertFalse(negotiationReader.isComplete(), "Only header is complete"); + assertTrue(negotiationReader.getHeader().isComplete(), "Header should be complete"); + assertEquals(10, negotiationReader.getHeader().payloadSize(), "Payload size should be 10"); + // Read payload + transport.reset(new byte[20]); + negotiationReader.read(transport); + assertTrue(negotiationReader.isComplete(), "Reader should be complete"); + assertEquals(10, negotiationReader.getPayload().length, "Payload length should be 10"); + } - @Test - public void testReadInvalidNegotiationStatus() throws TTransportException { - byte[] bytes = new byte[5]; - // Invalid status byte. - bytes[0] = -1; - TMemoryInputTransport transport = new TMemoryInputTransport(bytes); - SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); - assertThrows(TSaslNegotiationException.class, () -> { - negotiationReader.read(transport); + @Test + public void testReadInvalidNegotiationStatus() throws TTransportException { + byte[] bytes = new byte[5]; + // Invalid status byte. + bytes[0] = -1; + TMemoryInputTransport transport = new TMemoryInputTransport(bytes); + SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); + assertThrows( + TSaslNegotiationException.class, + () -> { + negotiationReader.read(transport); }); - } + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java index 49110e473..6e08a9fe6 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java @@ -19,39 +19,41 @@ package org.apache.thrift.transport.sasl; -import org.apache.thrift.EncodingUtils; -import org.junit.jupiter.api.Test; - -import java.nio.ByteBuffer; - import static org.apache.thrift.transport.sasl.SaslNegotiationFrameWriter.HEADER_BYTES; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.nio.ByteBuffer; +import org.apache.thrift.EncodingUtils; +import org.junit.jupiter.api.Test; + public class TestSaslNegotiationFrameWriter { - private static final byte[] PAYLOAD = {0x11, 0x08, 0x3F, 0x58, 0x73, 0x22, 0x00, (byte) 0xFF}; - - @Test - public void testWithHeaderAndPayload() { - SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); - frameWriter.withHeaderAndPayload(new byte[]{NegotiationStatus.OK.getValue()}, PAYLOAD); - byte[] expectedBytes = new byte[HEADER_BYTES + PAYLOAD.length]; - expectedBytes[0] = NegotiationStatus.OK.getValue(); - EncodingUtils.encodeBigEndian(PAYLOAD.length, expectedBytes, 1); - System.arraycopy(PAYLOAD, 0, expectedBytes, HEADER_BYTES, PAYLOAD.length); - assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); - } - - @Test - public void testWithInvalidHeaderLength() { - SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); - assertThrows(IllegalArgumentException.class, () -> frameWriter.withHeaderAndPayload(new byte[5], 0, 2, PAYLOAD, 0, 1)); - } - - @Test - public void testWithOnlyPayload() { - SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); - assertThrows(UnsupportedOperationException.class, () -> frameWriter.withOnlyPayload(new byte[0])); - } + private static final byte[] PAYLOAD = {0x11, 0x08, 0x3F, 0x58, 0x73, 0x22, 0x00, (byte) 0xFF}; + + @Test + public void testWithHeaderAndPayload() { + SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); + frameWriter.withHeaderAndPayload(new byte[] {NegotiationStatus.OK.getValue()}, PAYLOAD); + byte[] expectedBytes = new byte[HEADER_BYTES + PAYLOAD.length]; + expectedBytes[0] = NegotiationStatus.OK.getValue(); + EncodingUtils.encodeBigEndian(PAYLOAD.length, expectedBytes, 1); + System.arraycopy(PAYLOAD, 0, expectedBytes, HEADER_BYTES, PAYLOAD.length); + assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); + } + + @Test + public void testWithInvalidHeaderLength() { + SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); + assertThrows( + IllegalArgumentException.class, + () -> frameWriter.withHeaderAndPayload(new byte[5], 0, 2, PAYLOAD, 0, 1)); + } + + @Test + public void testWithOnlyPayload() { + SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); + assertThrows( + UnsupportedOperationException.class, () -> frameWriter.withOnlyPayload(new byte[0])); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java b/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java index 272815765..6fcea1e80 100644 --- a/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java +++ b/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java @@ -19,44 +19,42 @@ package org.apache.thrift.utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -public class TestStringUtils { - - @Test - public void testToHexString() { - byte[] bytes = {0x00, 0x1A, (byte) 0xEF, (byte) 0xAB, (byte) 0x92}; - assertEquals("001AEFAB92", StringUtils.bytesToHexString(bytes)); - assertEquals("EFAB92", StringUtils.bytesToHexString(bytes, 2, 3)); - assertNull(StringUtils.bytesToHexString(null)); - } - - - private byte[] bytes; - - @BeforeEach - public void setUp() throws Exception { - bytes = new byte[]{1, 2, 3, 4, 5}; - } - - @Test - public void testNegativeLength() { - assertThrows(IllegalArgumentException.class, () -> StringUtils.bytesToHexString(bytes, 0, -1)); - } - - @Test - public void testNegativeStartOffset() { - assertThrows(IndexOutOfBoundsException.class, () -> StringUtils.bytesToHexString(bytes, -1, 1)); - } +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; - @Test - public void testInvalidRange() { - assertThrows(IndexOutOfBoundsException.class, () -> StringUtils.bytesToHexString(bytes, 5, 1)); - } +public class TestStringUtils { + @Test + public void testToHexString() { + byte[] bytes = {0x00, 0x1A, (byte) 0xEF, (byte) 0xAB, (byte) 0x92}; + assertEquals("001AEFAB92", StringUtils.bytesToHexString(bytes)); + assertEquals("EFAB92", StringUtils.bytesToHexString(bytes, 2, 3)); + assertNull(StringUtils.bytesToHexString(null)); + } + + private byte[] bytes; + + @BeforeEach + public void setUp() throws Exception { + bytes = new byte[] {1, 2, 3, 4, 5}; + } + + @Test + public void testNegativeLength() { + assertThrows(IllegalArgumentException.class, () -> StringUtils.bytesToHexString(bytes, 0, -1)); + } + + @Test + public void testNegativeStartOffset() { + assertThrows(IndexOutOfBoundsException.class, () -> StringUtils.bytesToHexString(bytes, -1, 1)); + } + + @Test + public void testInvalidRange() { + assertThrows(IndexOutOfBoundsException.class, () -> StringUtils.bytesToHexString(bytes, 5, 1)); + } } |