diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
commit | 19fcec84d8d7d21e796c7624e521b60d28ee21ed (patch) | |
tree | 42d26aa27d1e3f7c0b8bd3fd14e7d7082f5008dc /src/jaegertracing/thrift/lib/java/test | |
parent | Initial commit. (diff) | |
download | ceph-upstream.tar.xz ceph-upstream.zip |
Adding upstream version 16.2.11+ds.upstream/16.2.11+dsupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/jaegertracing/thrift/lib/java/test')
59 files changed, 8187 insertions, 0 deletions
diff --git a/src/jaegertracing/thrift/lib/java/test/.keystore b/src/jaegertracing/thrift/lib/java/test/.keystore Binary files differnew file mode 100644 index 000000000..4dd66ac07 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/.keystore diff --git a/src/jaegertracing/thrift/lib/java/test/.truststore b/src/jaegertracing/thrift/lib/java/test/.truststore Binary files differnew file mode 100644 index 000000000..26fbd195f --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/.truststore diff --git a/src/jaegertracing/thrift/lib/java/test/log4j.properties b/src/jaegertracing/thrift/lib/java/test/log4j.properties new file mode 100644 index 000000000..ab9bebafe --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/log4j.properties @@ -0,0 +1,6 @@ +# log4j configuration used during build and unit tests +log4j.rootLogger=debug,stdout +log4j.threshold=ALL +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/Fixtures.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/Fixtures.java new file mode 100644 index 000000000..61f40a590 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/Fixtures.java @@ -0,0 +1,340 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +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; +import thrift.test.Nesting; +import thrift.test.OneOfEach; + +public class Fixtures { + public static final OneOfEach oneOfEach; + public static final Nesting nesting; + public static final HolyMoley holyMoley; + public static final CompactProtoTestStruct compactProtoTestStruct; + + // 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. + public 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 }; + public 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 }; + public 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 }; + + static { + try { + oneOfEach = new OneOfEach(); + oneOfEach.setIm_true(true); + oneOfEach.setIm_false(false); + oneOfEach.setA_bite((byte) 0xd6); + oneOfEach.setInteger16((short) 27000); + oneOfEach.setInteger32(1 << 24); + oneOfEach.setInteger64((long) 6000 * 1000 * 1000); + oneOfEach.setDouble_precision(Math.PI); + oneOfEach.setSome_characters("JSON THIS! \"\1"); + oneOfEach.setZomg_unicode(new String(kUnicodeBytes, StandardCharsets.UTF_8)); + oneOfEach.setBase64(ByteBuffer.wrap("base64".getBytes())); + // byte, i16, and i64 lists are populated by default constructor + + Bonk bonk = new Bonk(); + bonk.setType(31337); + bonk.setMessage("I am a bonk... xor!"); + nesting = new Nesting(bonk, oneOfEach); + + holyMoley = new HolyMoley(); + List<OneOfEach> big = new ArrayList<OneOfEach>(); + big.add(new OneOfEach(oneOfEach)); + big.add(nesting.my_ooe); + holyMoley.setBig(big); + holyMoley.getBig().get(0).setA_bite((byte) 0x22); + holyMoley.getBig().get(0).setA_bite((byte) 0x23); + + holyMoley.setContain(new HashSet<List<String>>()); + ArrayList<String> stage1 = new ArrayList<String>(2); + stage1.add("and a one"); + stage1.add("and a two"); + holyMoley.getContain().add(stage1); + stage1 = new ArrayList<String>(3); + stage1.add("then a one, two"); + stage1.add("three!"); + stage1.add("FOUR!!"); + holyMoley.getContain().add(stage1); + stage1 = new ArrayList<String>(0); + holyMoley.getContain().add(stage1); + + ArrayList<Bonk> stage2 = new ArrayList<Bonk>(); + holyMoley.setBonks(new HashMap<String, List<Bonk>>()); + // one empty + holyMoley.getBonks().put("zero", stage2); + + // one with two + stage2 = new ArrayList<Bonk>(); + Bonk b = new Bonk(); + b.setType(1); + b.setMessage("Wait."); + stage2.add(b); + b = new Bonk(); + b.setType(2); + b.setMessage("What?"); + stage2.add(b); + holyMoley.getBonks().put("two", stage2); + + // one with three + stage2 = new ArrayList<Bonk>(); + b = new Bonk(); + b.setType(3); + b.setMessage("quoth"); + b = new Bonk(); + b.setType(4); + b.setMessage("the raven"); + b = new Bonk(); + b.setType(5); + b.setMessage("nevermore"); + 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 })); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestDeepCopy.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestDeepCopy.java new file mode 100644 index 000000000..acafaef10 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestDeepCopy.java @@ -0,0 +1,34 @@ +package org.apache.thrift; + +import junit.framework.TestCase; +import thrift.test.DeepCopyBar; +import thrift.test.DeepCopyFoo; + +public class TestDeepCopy extends TestCase { + + public void testDeepCopy() throws Exception { + final DeepCopyFoo foo = new DeepCopyFoo(); + + foo.addToL(new DeepCopyBar()); + foo.addToS(new DeepCopyBar()); + foo.putToM("test 3", new DeepCopyBar()); + + foo.addToLi(new thrift.test.Object()); + foo.addToSi(new thrift.test.Object()); + foo.putToMi("test 3", new thrift.test.Object()); + + foo.setBar(new DeepCopyBar()); + + final DeepCopyFoo deepCopyFoo = foo.deepCopy(); + + 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")); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestEnumContainers.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestEnumContainers.java new file mode 100644 index 000000000..683246ba6 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestEnumContainers.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import junit.framework.TestCase; +import thrift.test.enumcontainers.EnumContainersTestConstants; +import thrift.test.enumcontainers.GodBean; +import thrift.test.enumcontainers.GreekGodGoddess; + +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; + +public class TestEnumContainers extends TestCase { + + 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 b3 = new GodBean(); + { + final TSerializer serializer = new TSerializer(); + final TDeserializer deserializer = new TDeserializer(); + + final byte[] bytes = serializer.serialize(b1); + deserializer.deserialize(b3, bytes); + } + + assertTrue(b1.getGoddess() != b2.getGoddess()); + assertTrue(b1.getPower() != b2.getPower()); + + assertTrue(b1.getGoddess() != b3.getGoddess()); + assertTrue(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); + + 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); + } + } + + 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); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestFullCamel.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestFullCamel.java new file mode 100644 index 000000000..fc9889890 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestFullCamel.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import java.util.HashSet; + +import junit.framework.TestCase; + +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TType; + +import thrift.test.fullcamel.OneOfEachZZ; +import thrift.test.fullcamel.UnderscoreSrv; + +// Sanity check for the code generated by 'fullcamel'. +// +public class TestFullCamel extends TestCase { + + public void testCamelCaseSyntax() throws Exception { + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); + + OneOfEachZZ obj = new OneOfEachZZ(); + obj.setABite((byte) 0xae); + obj.setImFalse(true); + byte[] serBytes = binarySerializer.serialize(obj); + binaryDeserializer.deserialize(obj, serBytes); + assertTrue( obj.getABite() == (byte) 0xae ); + assertTrue( obj.isImFalse() == true ); + } + + public void testCamelCaseRpcMethods() throws Exception { + final UnderscoreSrv.Iface srv = new UnderscoreSrv.Iface() { + @Override + public long someRpcCall(String message) { + return 1l; + } + }; + assertTrue(1l == srv.someRpcCall("test")); + } +} + diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestMultiplexedProcessor.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestMultiplexedProcessor.java new file mode 100644 index 000000000..85e7966bf --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestMultiplexedProcessor.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +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.Before; +import org.junit.Test; + +public class TestMultiplexedProcessor { + private TMultiplexedProcessor mp; + private TProtocol iprot; + private TProtocol oprot; + + @Before + public void setUp() throws Exception { + mp = new TMultiplexedProcessor(); + iprot = mock(TProtocol.class); + oprot = mock(TProtocol.class); + } + + @Test(expected = TException.class) + public void testWrongMessageType() throws TException { + when (iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.REPLY, 42)); + mp.process(iprot, oprot); + } + + @Test(expected = TException.class) + public void testNoSuchService() throws TException { + when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.CALL, 42)); + + 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) { + throw new TException("incorrect parameters"); + } + out.writeMessageBegin(new TMessage("func", TMessageType.REPLY, 42)); + } + } + + @Test + public void testExistingService() throws TException { + when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.CALL, 42)); + mp.registerProcessor("service", new StubProcessor()); + mp.process(iprot, oprot); + verify(oprot).writeMessageBegin(any(TMessage.class)); + } + + @Test + public void testDefaultService() throws TException { + when(iprot.readMessageBegin()).thenReturn(new TMessage("func", TMessageType.CALL, 42)); + mp.registerDefault(new StubProcessor()); + mp.process(iprot, oprot); + verify(oprot).writeMessageBegin(any(TMessage.class)); + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestOptionType.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestOptionType.java new file mode 100644 index 000000000..f70285ffa --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestOptionType.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import junit.framework.TestCase; +import org.apache.thrift.Option; + +// Tests and documents behavior for the "Option<T>" type +public class TestOptionType extends TestCase { + public void testSome() throws Exception { + 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"); + } + + 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 + try { + Object value = option.get(); + fail("Expected IllegalStateException, got no exception"); + } catch (IllegalStateException ex) { + + } catch(Exception ex) { + fail("Expected IllegalStateException, got some other exception: "+ex.toString()); + } + } + + public void testMakeSome() throws Exception { + Option<String> some = Option.some("wee"); + assertTrue(some instanceof Option.Some); + } + + public void testMakeNone() throws Exception { + Option<Integer> none = Option.none(); + assertTrue(none instanceof Option.None); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestOptionals.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestOptionals.java new file mode 100644 index 000000000..d1591ee2c --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestOptionals.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import junit.framework.TestCase; + +import thrift.test.Opt4; +import thrift.test.Opt30; +import thrift.test.Opt64; +import thrift.test.Opt80; + +// Exercises the isSet methods using structs from from ManyOptionals.thrift +public class TestOptionals extends TestCase { + public void testEncodingUtils() throws Exception { + assertEquals((short)0x8, EncodingUtils.setBit((short)0, 3, true)); + assertEquals((short)0, EncodingUtils.setBit((short)0x8, 3, false)); + assertEquals(true, EncodingUtils.testBit((short)0x8, 3)); + assertEquals(false, EncodingUtils.testBit((short)0x8, 4)); + + assertEquals((short)Short.MIN_VALUE, EncodingUtils.setBit((short)0, 15, true)); + assertEquals((short)0, EncodingUtils.setBit((short)Short.MIN_VALUE, 15, false)); + assertEquals(true, EncodingUtils.testBit(Short.MIN_VALUE, 15)); + assertEquals(false, EncodingUtils.testBit(Short.MIN_VALUE, 14)); + } + + public void testOpt4() throws Exception { + Opt4 x = new Opt4(); + assertEquals(false, x.isSetDef1()); + x.setDef1(3); + assertEquals(true, x.isSetDef1()); + assertEquals(false, x.isSetDef2()); + + Opt4 copy = new Opt4(x); + assertEquals(true, copy.isSetDef1()); + copy.unsetDef1(); + assertEquals(false, copy.isSetDef1()); + assertEquals(true, x.isSetDef1()); + } + + public void testOpt30() throws Exception { + Opt30 x = new Opt30(); + assertEquals(false, x.isSetDef1()); + x.setDef1(3); + assertEquals(true, x.isSetDef1()); + assertEquals(false, x.isSetDef2()); + } + + public void testOpt64() throws Exception { + Opt64 x = new Opt64(); + assertEquals(false, x.isSetDef1()); + x.setDef1(3); + assertEquals(true, x.isSetDef1()); + assertEquals(false, x.isSetDef2()); + x.setDef64(22); + assertEquals(true, x.isSetDef64()); + assertEquals(false, x.isSetDef63()); + } + + public void testOpt80() throws Exception { + Opt80 x = new Opt80(); + assertEquals(false, x.isSetDef1()); + x.setDef1(3); + assertEquals(true, x.isSetDef1()); + assertEquals(false, x.isSetDef2()); + + Opt80 copy = new Opt80(x); + copy.unsetDef1(); + assertEquals(false, copy.isSetDef1()); + assertEquals(true, x.isSetDef1()); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestRenderedDoubleConstants.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestRenderedDoubleConstants.java new file mode 100644 index 000000000..d691fe356 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestRenderedDoubleConstants.java @@ -0,0 +1,179 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import java.util.List; +import junit.framework.TestCase; +import static org.junit.Assert.*; +import org.junit.Test; +import thrift.test.DoubleConstantsTestConstants; + +public class TestRenderedDoubleConstants extends TestCase { + 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 + 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( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST, + EXPECTED_LIST[i], + DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i)), + EXPECTED_LIST[i], DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i), EPSILON); + } + } + + // to make sure the variables inside Thrift files are generated correctly + 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( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, EPSILON); + assertEquals( + 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), + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, EPSILON); + assertEquals( + 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), + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.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( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.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( + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestReuse.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestReuse.java new file mode 100644 index 000000000..b44abd0d2 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestReuse.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import java.util.HashSet; + +import org.apache.thrift.protocol.TBinaryProtocol; + +import thrift.test.Reuse; + +// Tests reusing objects for deserialization. +// +public class TestReuse extends TestStruct { + + public void testReuseObject() throws Exception { + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); + + Reuse ru1 = new Reuse(); + HashSet<String> hs1 = new HashSet<String>(); + byte[] serBytes; + String st1 = new String("string1"); + String st2 = new String("string2"); + + ru1.setVal1(11); + ru1.setVal2(hs1); + ru1.addToVal2(st1); + + serBytes = binarySerializer.serialize(ru1); + + // update hash set after serialization + hs1.add(st2); + + binaryDeserializer.deserialize(ru1, serBytes); + + assertTrue( ru1.getVal2() == hs1 ); + assertTrue( hs1.size() == 2 ); + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestStruct.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestStruct.java new file mode 100644 index 000000000..3379ed120 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestStruct.java @@ -0,0 +1,396 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift; + +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 junit.framework.TestCase; + +import org.apache.thrift.meta_data.FieldMetaData; +import org.apache.thrift.meta_data.ListMetaData; +import org.apache.thrift.meta_data.MapMetaData; +import org.apache.thrift.meta_data.SetMetaData; +import org.apache.thrift.meta_data.StructMetaData; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TType; + +import thrift.test.Bonk; +import thrift.test.CrazyNesting; +import thrift.test.HolyMoley; +import thrift.test.Insanity; +import thrift.test.JavaTestHelper; +import thrift.test.Nesting; +import thrift.test.Numberz; +import thrift.test.OneOfEach; +import thrift.test.StructA; +import thrift.test.StructB; +import thrift.test.Xtruct; + +public class TestStruct extends TestCase { + public void testIdentity() throws Exception { + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); + + OneOfEach ooe = Fixtures.oneOfEach; + + Nesting n = new Nesting(); + n.my_ooe = ooe; + 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_bonk = Fixtures.nesting.my_bonk; + + HolyMoley hm = Fixtures.holyMoley; + + OneOfEach ooe2 = new OneOfEach(); + binaryDeserializer.deserialize( + ooe2, + binarySerializer.serialize(ooe)); + + assertEquals(ooe, ooe2); + assertEquals(ooe.hashCode(), ooe2.hashCode()); + + + Nesting n2 = new Nesting(); + binaryDeserializer.deserialize( + n2, + binarySerializer.serialize(n)); + + assertEquals(n, n2); + assertEquals(n.hashCode(), n2.hashCode()); + + HolyMoley hm2 = new HolyMoley(); + binaryDeserializer.deserialize( + hm2, + binarySerializer.serialize(hm)); + + assertEquals(hm, hm2); + assertEquals(hm.hashCode(), hm2.hashCode()); + } + + public void testDeepCopy() throws Exception { + TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); + TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); + + HolyMoley hm = Fixtures.holyMoley; + + byte[] binaryCopy = binarySerializer.serialize(hm); + HolyMoley hmCopy = new HolyMoley(); + binaryDeserializer.deserialize(hmCopy, binaryCopy); + HolyMoley hmCopy2 = new HolyMoley(hm); + + assertEquals(hm, hmCopy); + assertEquals(hmCopy, hmCopy2); + + // change binary value in original object + hm.big.get(0).base64.array()[0]++; + // make sure the change didn't propagate to the copied object + assertFalse(hm.equals(hmCopy2)); + hm.big.get(0).base64.array()[0]--; // undo change + + hmCopy2.bonks.get("two").get(1).message = "What else?"; + + assertFalse(hm.equals(hmCopy2)); + } + + public void testCompareTo() throws Exception { + Bonk bonk1 = new Bonk(); + Bonk bonk2 = new Bonk(); + + // Compare empty thrift objects. + assertEquals(0, bonk1.compareTo(bonk2)); + + bonk1.setMessage("m"); + + // Compare one thrift object with a filled in field and another without it. + assertTrue(bonk1.compareTo(bonk2) > 0); + assertTrue(bonk2.compareTo(bonk1) < 0); + + // Compare both have filled-in fields. + bonk2.setMessage("z"); + assertTrue(bonk1.compareTo(bonk2) < 0); + assertTrue(bonk2.compareTo(bonk1) > 0); + + // Compare bonk1 has a field filled in that bonk2 doesn't. + bonk1.setType(123); + assertTrue(bonk1.compareTo(bonk2) > 0); + assertTrue(bonk2.compareTo(bonk1) < 0); + + // Compare bonk1 and bonk2 equal. + bonk2.setType(123); + bonk2.setMessage("m"); + assertEquals(0, bonk1.compareTo(bonk2)); + } + + public void testCompareToWithDataStructures() { + Insanity insanity1 = new Insanity(); + Insanity insanity2 = new Insanity(); + + // Both empty. + expectEquals(insanity1, insanity2); + + insanity1.setUserMap(new HashMap<Numberz, Long>()); + // insanity1.map = {}, insanity2.map = null + expectGreaterThan(insanity1, insanity2); + + // insanity1.map = {2:1}, insanity2.map = null + insanity1.getUserMap().put(Numberz.TWO, 1l); + expectGreaterThan(insanity1, insanity2); + + // insanity1.map = {2:1}, insanity2.map = {} + insanity2.setUserMap(new HashMap<Numberz, Long>()); + expectGreaterThan(insanity1, insanity2); + + // insanity1.map = {2:1}, insanity2.map = {2:2} + insanity2.getUserMap().put(Numberz.TWO, 2l); + expectLessThan(insanity1, insanity2); + + // insanity1.map = {2:1, 3:5}, insanity2.map = {2:2} + insanity1.getUserMap().put(Numberz.THREE, 5l); + expectGreaterThan(insanity1, insanity2); + + // insanity1.map = {2:1, 3:5}, insanity2.map = {2:1, 4:5} + insanity2.getUserMap().put(Numberz.TWO, 1l); + insanity2.getUserMap().put(Numberz.FIVE, 5l); + expectLessThan(insanity1, insanity2); + } + + private void expectLessThan(Insanity insanity1, Insanity insanity2) { + int compareTo = insanity1.compareTo(insanity2); + assertTrue(insanity1 + " should be less than " + insanity2 + ", but is: " + compareTo, compareTo < 0); + } + + private void expectGreaterThan(Insanity insanity1, Insanity insanity2) { + int compareTo = insanity1.compareTo(insanity2); + assertTrue(insanity1 + " should be greater than " + insanity2 + ", but is: " + compareTo, compareTo > 0); + } + + private void expectEquals(Insanity insanity1, Insanity insanity2) { + int compareTo = insanity1.compareTo(insanity2); + assertEquals(insanity1 + " should be equal to " + insanity2 + ", but is: " + compareTo, 0, compareTo); + } + + public void testMetaData() throws Exception { + Map<CrazyNesting._Fields, FieldMetaData> mdMap = CrazyNesting.metaDataMap; + + // Check for struct fields existence + assertEquals(4, mdMap.size()); + assertTrue(mdMap.containsKey(CrazyNesting._Fields.SET_FIELD)); + assertTrue(mdMap.containsKey(CrazyNesting._Fields.LIST_FIELD)); + assertTrue(mdMap.containsKey(CrazyNesting._Fields.STRING_FIELD)); + assertTrue(mdMap.containsKey(CrazyNesting._Fields.BINARY_FIELD)); + + // Check for struct fields contents + assertEquals("string_field", mdMap.get(CrazyNesting._Fields.STRING_FIELD).fieldName); + assertEquals("list_field", mdMap.get(CrazyNesting._Fields.LIST_FIELD).fieldName); + 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(TType.STRING, mdMap.get(CrazyNesting._Fields.STRING_FIELD).valueMetaData.type); + assertFalse(mdMap.get(CrazyNesting._Fields.STRING_FIELD).valueMetaData.isBinary()); + assertEquals(TType.LIST, mdMap.get(CrazyNesting._Fields.LIST_FIELD).valueMetaData.type); + assertEquals(TType.SET, mdMap.get(CrazyNesting._Fields.SET_FIELD).valueMetaData.type); + assertEquals(TType.STRING, mdMap.get(CrazyNesting._Fields.BINARY_FIELD).valueMetaData.type); + assertTrue(mdMap.get(CrazyNesting._Fields.BINARY_FIELD).valueMetaData.isBinary()); + + // Check nested structures + assertTrue(mdMap.get(CrazyNesting._Fields.LIST_FIELD).valueMetaData.isContainer()); + + 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); + + // Check that FieldMetaData contains a map with metadata for all generated struct classes + assertNotNull(FieldMetaData.getStructMetaDataMap(CrazyNesting.class)); + assertNotNull(FieldMetaData.getStructMetaDataMap(Insanity.class)); + assertNotNull(FieldMetaData.getStructMetaDataMap(Xtruct.class)); + + assertEquals(CrazyNesting.metaDataMap, FieldMetaData.getStructMetaDataMap(CrazyNesting.class)); + assertEquals(Insanity.metaDataMap, FieldMetaData.getStructMetaDataMap(Insanity.class)); + + for (Map.Entry<? extends TFieldIdEnum, FieldMetaData> mdEntry : mdMap.entrySet()) { + assertEquals(mdEntry.getKey(), CrazyNesting._Fields.findByName(mdEntry.getValue().fieldName)); + } + + MapMetaData vmd = (MapMetaData)Insanity.metaDataMap.get(Insanity._Fields.USER_MAP).valueMetaData; + assertTrue(vmd.valueMetaData.isTypedef()); + assertFalse(vmd.keyMetaData.isTypedef()); + } + + public void testToString() throws Exception { + JavaTestHelper object = new JavaTestHelper(); + 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.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.toString()); + + object.req_bin = ByteBuffer.wrap(new byte[] {}); + object.setOpt_binIsSet(true); + + assertEquals("JavaTestHelper(req_int:0, req_obj:, req_bin:)", + object.toString()); + } + + private static void assertArrayEquals(byte[] expected, byte[] actual) { + if (!java.util.Arrays.equals(expected, actual)) { + fail("Expected byte array did not match actual."); + } + } + + public void testBytesBufferFeatures() throws Exception { + + final String testString = "testBytesBufferFeatures"; + final JavaTestHelper o = new JavaTestHelper(); + + 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); + assertNull(o.getReq_bin()); + + o.setReq_bin(testString.getBytes()); + assertArrayEquals(testString.getBytes(), o.getReq_bin()); + + o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, null); + assertNull(o.getReq_bin()); + + o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, testString.getBytes()); + assertArrayEquals(testString.getBytes(), o.getReq_bin()); + + o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, null); + assertNull(o.getReq_bin()); + + o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, ByteBuffer.wrap(testString.getBytes())); + assertArrayEquals(testString.getBytes(), o.getReq_bin()); + } + + public void testJavaSerializable() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + + OneOfEach ooe = Fixtures.oneOfEach; + + // Serialize ooe the Java way... + oos.writeObject(ooe); + byte[] serialized = baos.toByteArray(); + + // Attempt to deserialize it + ByteArrayInputStream bais = new ByteArrayInputStream(serialized); + ObjectInputStream ois = new ObjectInputStream(bais); + OneOfEach ooe2 = (OneOfEach) ois.readObject(); + + assertEquals(ooe, ooe2); + } + + public void testSubStructValidation() throws Exception { + StructA valid = new StructA("valid"); + StructA invalid = new StructA(); + + StructB b = new StructB(); + try { + b.validate(); + fail(); + } catch (TException e) { + // expected + } + + b = new StructB().setAb(valid); + b.validate(); + + b = new StructB().setAb(invalid); + try { + b.validate(); + fail(); + } catch (TException e) { + // expected + } + + b = new StructB().setAb(valid).setAa(invalid); + try { + b.validate(); + fail(); + } catch (TException e) { + // expected + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTBaseHelper.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTBaseHelper.java new file mode 100644 index 000000000..8b0855525 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTBaseHelper.java @@ -0,0 +1,209 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift; + +import java.nio.ByteBuffer; +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 junit.framework.TestCase; + +public class TestTBaseHelper extends TestCase { + public void testByteArrayComparison() { + assertTrue(TBaseHelper.compareTo(new byte[]{'a','b'}, new byte[]{'a','c'}) < 0); + } + + public void testSets() { + Set<String> a = new HashSet<String>(); + Set<String> b = new HashSet<String>(); + + assertTrue(TBaseHelper.compareTo(a, b) == 0); + + a.add("test"); + + assertTrue(TBaseHelper.compareTo(a, b) > 0); + + b.add("test"); + + assertTrue(TBaseHelper.compareTo(a, b) == 0); + + b.add("aardvark"); + + assertTrue(TBaseHelper.compareTo(a, b) < 0); + + a.add("test2"); + + assertTrue(TBaseHelper.compareTo(a, b) > 0); + } + + public void testNestedStructures() { + Set<List<String>> a = new HashSet<List<String>>(); + Set<List<String>> b = new HashSet<List<String>>(); + + a.add(Arrays.asList(new String[] {"a","b"})); + b.add(Arrays.asList(new String[] {"a","b", "c"})); + a.add(Arrays.asList(new String[] {"a","b"})); + b.add(Arrays.asList(new String[] {"a","b", "c"})); + + assertTrue(TBaseHelper.compareTo(a, b) < 0); + } + + public void testMapsInSets() { + Set<Map<String, Long>> a = new HashSet<Map<String, Long>>(); + Set<Map<String, Long>> b = new HashSet<Map<String, Long>>(); + + assertTrue(TBaseHelper.compareTo(a, b) == 0); + + Map<String, Long> innerA = new HashMap<String, Long>(); + Map<String, Long> innerB = new HashMap<String, Long>(); + a.add(innerA); + b.add(innerB); + + innerA.put("a", 1l); + innerB.put("a", 2l); + + assertTrue(TBaseHelper.compareTo(a, b) < 0); + } + + public void testByteArraysInMaps() { + Map<byte[], Long> a = new HashMap<byte[], Long>(); + Map<byte[], Long> b = new HashMap<byte[], Long>(); + + assertTrue(TBaseHelper.compareTo(a, b) == 0); + + 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); + } + + public void testMapsWithNulls() { + Map<String, String> a = new HashMap<String, String>(); + Map<String, String> b = new HashMap<String, String>(); + a.put("a", null); + a.put("b", null); + b.put("a", null); + b.put("b", null); + + assertTrue(TBaseHelper.compareTo(a, b) == 0); + } + + public void testMapKeyComparison() { + Map<String, String> a = new HashMap<String, String>(); + Map<String, String> b = new HashMap<String, String>(); + a.put("a", "a"); + b.put("b", "a"); + + assertTrue(TBaseHelper.compareTo(a, b) < 0); + } + + public void testMapValueComparison() { + Map<String, String> a = new HashMap<String, String>(); + Map<String, String> b = new HashMap<String, String>(); + a.put("a", "b"); + b.put("a", "a"); + + assertTrue(TBaseHelper.compareTo(a, b) > 0); + } + + public void testByteArraysInSets() { + Set<byte[]> a = new HashSet<byte[]>(); + Set<byte[]> b = new HashSet<byte[]>(); + + 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'}); + assertTrue(TBaseHelper.compareTo(a, b) > 0); + } + + public void testByteBufferToByteArray() throws Exception { + byte[] b1 = {10,9,8,7,6,5,4,3,2,1,0}; + byte[] b2 = TBaseHelper.byteBufferToByteArray(ByteBuffer.wrap(b1)); + assertEquals("b1 and b2 should be the exact same array (identity) due to fast path", b1, b2); + + byte[] b3 = TBaseHelper.byteBufferToByteArray(ByteBuffer.wrap(b1, 1, 3)); + assertEquals(3, b3.length); + assertEquals(ByteBuffer.wrap(b1, 1, 3), ByteBuffer.wrap(b3)); + } + + public void testRightSize() throws Exception { + assertNull(TBaseHelper.rightSize(null)); + } + + public void testByteBufferToString() { + byte[] array = new byte[]{1, 2, 3}; + ByteBuffer bb = ByteBuffer.wrap(array, 1, 2); + StringBuilder sb = new StringBuilder(); + TBaseHelper.toString(bb, sb); + assertEquals("02 03", sb.toString()); + bb = ByteBuffer.wrap(array, 0, array.length); + bb.position(1); + bb = bb.slice(); + assertEquals(1, bb.arrayOffset()); + assertEquals(0, bb.position()); + assertEquals(2, bb.limit()); + sb = new StringBuilder(); + TBaseHelper.toString(bb, sb); + assertEquals("02 03", sb.toString()); + } + + public void testCopyBinaryWithByteBuffer() throws Exception { + byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5}; + ByteBuffer b = ByteBuffer.wrap(bytes); + ByteBuffer bCopy = TBaseHelper.copyBinary(b); + assertEquals(b, bCopy); + assertEquals(0, b.position()); + + b = ByteBuffer.allocateDirect(6); + b.put(bytes); + b.position(0); + bCopy = TBaseHelper.copyBinary(b); + assertEquals(6, b.remaining()); + assertEquals(0, b.position()); + assertEquals(b, bCopy); + + b.mark(); + b.get(); + bCopy = TBaseHelper.copyBinary(b); + assertEquals(ByteBuffer.wrap(bytes, 1, 5), bCopy); + assertEquals(1, b.position()); + b.reset(); + assertEquals(0, b.position()); + + assertNull(TBaseHelper.copyBinary((ByteBuffer)null)); + } + + public void testCopyBinaryWithByteArray() throws Exception { + 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)); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTDeserializer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTDeserializer.java new file mode 100644 index 000000000..a4a353d6c --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTDeserializer.java @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift; + +import java.nio.ByteBuffer; + +import junit.framework.TestCase; + +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TCompactProtocol; +import org.apache.thrift.protocol.TJSONProtocol; +import org.apache.thrift.protocol.TProtocolFactory; + +import thrift.test.Backwards; +import thrift.test.OneOfEach; +import thrift.test.PrimitiveThenStruct; +import thrift.test.StructWithAUnion; +import thrift.test.TestUnion; + +public class TestTDeserializer extends TestCase { + + private static final TProtocolFactory[] PROTOCOLS = new TProtocolFactory[] { + new TBinaryProtocol.Factory(), + new TCompactProtocol.Factory(), + new TJSONProtocol.Factory() + }; + + public void testPartialDeserialize() throws Exception { + //Root:StructWithAUnion + // 1:Union + // 1.3:OneOfEach + OneOfEach level3OneOfEach = Fixtures.oneOfEach; + TestUnion level2TestUnion = new TestUnion(TestUnion._Fields.STRUCT_FIELD, level3OneOfEach); + StructWithAUnion level1SWU = new StructWithAUnion(level2TestUnion); + + Backwards bw = new Backwards(2, 1); + PrimitiveThenStruct pts = new PrimitiveThenStruct(12345, 67890, bw); + + 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 + testPartialDeserialize(factory, pts, new Backwards(), bw, PrimitiveThenStruct._Fields.BW); + + //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); + 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); + 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); + 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); + 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); + 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); + 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); + 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()); + assertEquals(ByteBuffer.wrap(expectedBinary), resultBinary); + + // Test field id in Union + short id = deserializer.partialDeserializeSetFieldIdInUnion(serialize(level1SWU, factory), StructWithAUnion._Fields.TEST_UNION); + assertEquals(level2TestUnion.getSetField().getThriftFieldId(), id); + } + } + + public static 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("on attempt " + i + ", with " + protocolFactory.toString() + + ", expected " + expected + " but got " + outputCopy, + expected, outputCopy); + } + } + + private static byte[] serialize(TBase input, TProtocolFactory protocolFactory) throws TException{ + return new TSerializer(protocolFactory).serialize(input); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTEnumHelper.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTEnumHelper.java new file mode 100644 index 000000000..e2cca4039 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTEnumHelper.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift; + +import thrift.test.Numberz; + +import junit.framework.TestCase; + +public class TestTEnumHelper extends TestCase { + + public void testGetByValue_ValidValues() { + for (Numberz n: Numberz.values()) { + int value = n.getValue(); + assertEquals(n, TEnumHelper.getByValue(Numberz.class, value)); + } + } + + public void testGetByValue_InvalidValue() { + assertEquals(null, TEnumHelper.getByValue(Numberz.class, 0)); + } + + public void testGetByValue_InvalidClass() { + assertEquals(null, TEnumHelper.getByValue(TEnum.class, 0)); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTUnion.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTUnion.java new file mode 100644 index 000000000..f1e6f0e1f --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestTUnion.java @@ -0,0 +1,268 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import junit.framework.TestCase; + +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 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; + +public class TestTUnion extends TestCase { + + public void testBasic() throws Exception { + TestUnion union = new TestUnion(); + + assertFalse(union.isSet()); + assertFalse(union.isSetI32_field()); + assertNull(union.getFieldValue()); + + union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); + + assertEquals(Integer.valueOf(25), union.getFieldValue()); + + assertEquals(Integer.valueOf(25), union.getFieldValue(TestUnion._Fields.I32_FIELD)); + + assertTrue(union.isSetI32_field()); + + try { + union.getFieldValue(TestUnion._Fields.STRING_FIELD); + fail("should have thrown an exception"); + } catch (IllegalArgumentException e) { + // cool! + } + + union = new TestUnion(); + + // should not throw an exception here + union.hashCode(); + + union.setI32_field(1); + assertEquals(1, union.getI32_field()); + union.hashCode(); + + assertFalse(union.isSetString_field()); + + try { + union.getString_field(); + fail("should have thrown an exception"); + } catch (Exception e) { + // sweet + } + + union = TestUnion.i32_field(1); + + assertFalse(union.equals((TestUnion)null)); + + union = TestUnion.enum_field(SomeEnum.ONE); + union.hashCode(); + + union = new TestUnion(); + // should not throw an exception + union.toString(); + } + + public void testCompareTo() throws Exception { + ComparableUnion cu = ComparableUnion.string_field("a"); + ComparableUnion cu2 = ComparableUnion.string_field("b"); + + assertTrue(cu.compareTo(cu) == 0); + assertTrue(cu2.compareTo(cu2) == 0); + + assertTrue(cu.compareTo(cu2) < 0); + assertTrue(cu2.compareTo(cu) > 0); + + 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})); + + assertTrue(cu.compareTo(cu2) < 0); + assertTrue(cu2.compareTo(cu) > 0); + + TestUnion union1 = new TestUnion(TestUnion._Fields.STRUCT_LIST, new ArrayList<RandomStuff>()); + TestUnion union2 = new TestUnion(TestUnion._Fields.STRUCT_LIST, new ArrayList<RandomStuff>()); + assertTrue(union1.compareTo(union2) == 0); + + TestUnion union3 = new TestUnion(TestUnion._Fields.I32_SET, new HashSet<Integer>()); + Set<Integer> i32_set = new HashSet<Integer>(); + i32_set.add(1); + TestUnion union4 = new TestUnion(TestUnion._Fields.I32_SET, i32_set); + assertTrue(union3.compareTo(union4) < 0); + + Map<Integer, Integer> i32_map = new HashMap<Integer, Integer>(); + 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); + } + + public void testEquality() throws Exception { + TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); + + TestUnion otherUnion = new TestUnion(TestUnion._Fields.STRING_FIELD, "blah!!!"); + + assertFalse(union.equals(otherUnion)); + + otherUnion = new TestUnion(TestUnion._Fields.I32_FIELD, 400); + + assertFalse(union.equals(otherUnion)); + + otherUnion = new TestUnion(TestUnion._Fields.OTHER_I32_FIELD, 25); + + assertFalse(union.equals(otherUnion)); + } + + public void testSerialization() throws Exception { + TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); + union.setI32_set(Collections.singleton(42)); + + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = new TBinaryProtocol(buf); + + union.write(proto); + + TestUnion u2 = new TestUnion(); + + u2.read(proto); + + assertEquals(u2, union); + + StructWithAUnion swau = new StructWithAUnion(u2); + + buf = new TMemoryBuffer(0); + proto = new TBinaryProtocol(buf); + + swau.write(proto); + + StructWithAUnion swau2 = new StructWithAUnion(); + assertFalse(swau2.equals(swau)); + swau2.read(proto); + assertEquals(swau2, swau); + + // this should NOT throw an exception. + buf = new TMemoryBuffer(0); + proto = new TBinaryProtocol(buf); + + swau.write(proto); + new Empty().read(proto); + } + + public void testTupleProtocolSerialization () throws Exception { + TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); + union.setI32_set(Collections.singleton(42)); + + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = new TTupleProtocol(buf); + + union.write(proto); + + TestUnion u2 = new TestUnion(); + + u2.read(proto); + + assertEquals(u2, union); + + StructWithAUnion swau = new StructWithAUnion(u2); + + buf = new TMemoryBuffer(0); + proto = new TBinaryProtocol(buf); + + swau.write(proto); + + StructWithAUnion swau2 = new StructWithAUnion(); + assertFalse(swau2.equals(swau)); + swau2.read(proto); + assertEquals(swau2, swau); + + // this should NOT throw an exception. + buf = new TMemoryBuffer(0); + proto = new TTupleProtocol(buf); + + swau.write(proto); + new Empty().read(proto); + } + + public void testSkip() throws Exception { + TestUnion tu = TestUnion.string_field("string"); + byte[] tuSerialized = new TSerializer().serialize(tu); + TestUnionMinusStringField tums = new TestUnionMinusStringField(); + new TDeserializer().deserialize(tums, tuSerialized); + assertNull(tums.getSetField()); + assertNull(tums.getFieldValue()); + } + + public void testDeepCopy() throws Exception { + byte[] bytes = {1, 2, 3}; + ByteBuffer value = ByteBuffer.wrap(bytes); + ComparableUnion cu = ComparableUnion.binary_field(value); + ComparableUnion copy = cu.deepCopy(); + assertEquals(cu, copy); + assertNotSame(cu.bufferForBinary_field().array(), copy.bufferForBinary_field().array()); + } + + public void testToString() throws Exception { + byte[] bytes = {1, 2, 3}; + ByteBuffer value = ByteBuffer.wrap(bytes); + ComparableUnion cu = ComparableUnion.binary_field(value); + String expectedString = "<ComparableUnion binary_field:01 02 03>"; + assertEquals(expectedString, cu.toString()); + } + + public void testJavaSerializable() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + + TestUnion tu = TestUnion.string_field("string"); + + // Serialize tu the Java way... + oos.writeObject(tu); + byte[] serialized = baos.toByteArray(); + + // Attempt to deserialize it + ByteArrayInputStream bais = new ByteArrayInputStream(serialized); + ObjectInputStream ois = new ObjectInputStream(bais); + TestUnion tu2 = (TestUnion) ois.readObject(); + + assertEquals(tu, tu2); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestUnsafeBinaries.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestUnsafeBinaries.java new file mode 100644 index 000000000..d1fc21368 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/TestUnsafeBinaries.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +import thrift.test.SafeBytes; +import thrift.test.UnsafeBytes; + +// test generating types with un-copied byte[]/ByteBuffer input/output +// +public class TestUnsafeBinaries extends TestStruct { + + private static byte[] input() { + return new byte[]{1, 1}; + } + + // + // verify that the unsafe_binaries option modifies behavior + // + + // constructor doesn't copy + public void testUnsafeConstructor() throws Exception { + + byte[] input = input(); + UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input)); + + input[0] = 2; + + assertTrue(Arrays.equals( + 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 + // should be retained when using this flag + public void testUnsafeGetter(){ + UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); + + byte[] val = struct.getBytes(); + val[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{2, 1}, + struct.getBytes()) + ); + + } + + // setter doesn't copy + public void testUnsafeSetter(){ + UnsafeBytes struct = new UnsafeBytes(); + + byte[] val = input(); + struct.setBytes(val); + + val[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{2, 1}, + struct.getBytes()) + ); + + } + + // buffer doens't copy + public void testUnsafeBufferFor(){ + UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); + + ByteBuffer val = struct.bufferForBytes(); + val.array()[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{2, 1}, + struct.getBytes()) + ); + + } + + // + // verify that the default generator does not change behavior + // + + public void testSafeConstructor() { + + byte[] input = input(); + SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input)); + + input[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{1, 1}, + struct.getBytes()) + ); + + } + + public void testSafeSetter() { + + byte[] input = input(); + SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input)); + + input[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{1, 1}, + struct.getBytes()) + ); + + } + + public void testSafeBufferFor(){ + SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input())); + + ByteBuffer val = struct.bufferForBytes(); + val.array()[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{1, 1}, + struct.getBytes()) + ); + + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/async/TestTAsyncClient.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/async/TestTAsyncClient.java new file mode 100644 index 000000000..392ca22d4 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/async/TestTAsyncClient.java @@ -0,0 +1,28 @@ +package org.apache.thrift.async; + +import junit.framework.TestCase; + +import org.apache.thrift.TException; + +import thrift.test.Srv; +import thrift.test.Srv.AsyncClient; + +public class TestTAsyncClient extends TestCase { + public void testRaisesExceptionWhenUsedConcurrently() throws Exception { + 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); + try { + c.checkReady(); + fail("should have hit an exception"); + } catch (Exception e) { + // awesome + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/async/TestTAsyncClientManager.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/async/TestTAsyncClientManager.java new file mode 100644 index 000000000..c483cf24e --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/async/TestTAsyncClientManager.java @@ -0,0 +1,378 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.async; + +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 junit.framework.TestCase; + +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.server.ServerTestBase; +import org.apache.thrift.server.THsHaServer; +import org.apache.thrift.server.THsHaServer.Args; +import org.apache.thrift.transport.TNonblockingServerSocket; +import org.apache.thrift.transport.TNonblockingSocket; + +import thrift.test.CompactProtoTestStruct; +import thrift.test.ExceptionWithAMap; +import thrift.test.Srv; +import thrift.test.Srv.Iface; + +public class TestTAsyncClientManager extends TestCase { + + private THsHaServer server_; + private Thread serverThread_; + private TAsyncClientManager clientManager_; + + 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); + } + + public void tearDown() throws Exception { + server_.stop(); + clientManager_.stop(); + serverThread_.join(); + } + + public void testBasicCall() throws Exception { + Srv.AsyncClient client = getClient(); + basicCall(client); + } + + 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>() { + @Override + public void onComplete(R response) { + latch.countDown(); + } + + @Override + public void onError(Exception exception) { + 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); + } + + 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(); + } + + 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(); + } + + 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(); + } + + 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()); + } + + 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()); + } + + 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); + } + + private Srv.AsyncClient getClient() throws IOException { + 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)); + fail("unexpected onError with exception " + sink.toString()); + } finally { + latch.countDown(); + } + } + }); + latch.await(100, TimeUnit.SECONDS); + assertTrue(returned.get()); + } + + public 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; + } + + @Override + public void methodWithDefaultArgs(int something) throws TException { } + + @Override + public CompactProtoTestStruct structMethod() throws TException { + return null; + } + + @Override + public void voidMethod() 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!"); + } + } + } + + private static abstract 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)); + fail("unexpected error " + sink.toString()); + } + + private class JankyRunnable implements Runnable { + private int numCalls_; + private int numSuccesses_ = 0; + private Srv.AsyncClient client_; + + public JankyRunnable(int numCalls) throws Exception { + numCalls_ = numCalls; + client_ = getClient(); + client_.setTimeout(20000); + } + + public int getNumSuccesses() { + return numSuccesses_; + } + + 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)); + fail("unexpected onError on iteration " + iteration + ": " + sink.toString()); + } finally { + latch.countDown(); + } + } + }); + + boolean calledBack = latch.await(30, TimeUnit.SECONDS); + assertTrue("wasn't called back in time on iteration " + iteration, calledBack); + assertTrue("onComplete not called on iteration " + iteration, returned.get()); + this.numSuccesses_++; + } catch (Exception e) { + fail(e); + } + } + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/BenchmarkProtocols.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/BenchmarkProtocols.java new file mode 100644 index 000000000..e88160759 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/BenchmarkProtocols.java @@ -0,0 +1,88 @@ +package org.apache.thrift.protocol; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +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 int NUM_REPS = 100000; + private static final int NUM_TRIALS = 10; + + public static void main(String[] args) throws TException { + Map<TProtocolFactory, List<Long>> timesByFactory = new HashMap<TProtocolFactory, List<Long>>(); + + for (int trial = 0; trial < NUM_TRIALS; trial++) { + 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() { +// } +// }); + + + for (TProtocolFactory factory : FACTORIES) { + if (timesByFactory.get(factory) == null) { + timesByFactory.put(factory, new ArrayList<Long>()); + } + + long start = System.currentTimeMillis(); + for (int rep = 0; rep < NUM_REPS; rep++) { + TProtocol proto = factory.getProtocol(new TMemoryBuffer(128*1024)); + Fixtures.compactProtoTestStruct.write(proto); + Fixtures.nesting.write(proto); + } + long end = System.currentTimeMillis(); + timesByFactory.get(factory).add(end-start); + } + } + + for (TProtocolFactory factory : FACTORIES) { + List<Long> times = timesByFactory.get(factory); +// 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("raw times: " + times); + } + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/ProtocolTestBase.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/ProtocolTestBase.java new file mode 100644 index 000000000..0386d8393 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/ProtocolTestBase.java @@ -0,0 +1,427 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.protocol; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.thrift.Fixtures; +import org.apache.thrift.TBase; +import org.apache.thrift.TDeserializer; +import org.apache.thrift.TException; +import org.apache.thrift.TSerializer; +import org.apache.thrift.transport.TMemoryBuffer; + +import thrift.test.CompactProtoTestStruct; +import thrift.test.HolyMoley; +import thrift.test.Nesting; +import thrift.test.OneOfEach; +import thrift.test.Srv; + +public abstract class ProtocolTestBase extends TestCase { + + /** Does it make sense to call methods like writeI32 directly on your protocol? */ + protected abstract boolean canBeUsedNaked(); + + /** The protocol factory for the protocol being tested. */ + protected abstract TProtocolFactory getFactory(); + + public void testDouble() throws Exception { + if (canBeUsedNaked()) { + TMemoryBuffer buf = new TMemoryBuffer(1000); + TProtocol proto = getFactory().getProtocol(buf); + proto.writeDouble(123.456); + 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); + } + }); + } + + public void testSerialization() throws Exception { + internalTestSerialization(OneOfEach.class, Fixtures.oneOfEach); + internalTestSerialization(Nesting.class, Fixtures.nesting); + internalTestSerialization(HolyMoley.class, Fixtures.holyMoley); + internalTestSerialization(CompactProtoTestStruct.class, Fixtures.compactProtoTestStruct); + } + + 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])) { + if (canBeUsedNaked()) { + internalTestNakedBinary(b); + } + internalTestBinaryField(b); + } + + if (canBeUsedNaked()) { + byte[] data = {1, 2, 3, 4, 5, 6}; + + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + ByteBuffer bb = ByteBuffer.wrap(data); + bb.get(); + proto.writeBinary(bb.slice()); + assertEquals(ByteBuffer.wrap(data, 1, 5), proto.readBinary()); + } + } + + public void testString() throws Exception { + for (String s : Arrays.asList("", "short", "borderlinetiny", "a bit longer than the smallest possible")) { + if (canBeUsedNaked()) { + internalTestNakedString(s); + } + internalTestStringField(s); + } + } + + public void testLong() throws Exception { + if (canBeUsedNaked()) { + internalTestNakedI64(0); + } + internalTestI64Field(0); + for (int i = 0; i < 62; i++) { + if (canBeUsedNaked()) { + internalTestNakedI64(1L << i); + internalTestNakedI64(-(1L << i)); + } + internalTestI64Field(1L << i); + internalTestI64Field(-(1L << i)); + } + } + + public void testInt() throws Exception { + for (int i : Arrays.asList(0, 1, 7, 150, 15000, 31337, 0xffff, 0xffffff, -1, -7, -150, -15000, -0xffff, -0xffffff)) { + if (canBeUsedNaked()) { + internalTestNakedI32(i); + } + internalTestI32Field(i); + } + } + + 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); + } + internalTestI16Field((short)s); + } + } + + public void testByte() throws Exception { + if (canBeUsedNaked()) { + internalTestNakedByte(); + } + for (int i = 0; i < 128; 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); + 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); + } + + public void readMethod(TProtocol proto) throws TException { + assertEquals((byte)b, proto.readByte()); + } + }); + } + + private void internalTestNakedI16(short n) throws Exception { + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + proto.writeI16(n); + assertEquals(n, proto.readI16()); + } + + 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); + } + + public void readMethod(TProtocol proto) throws TException { + assertEquals(n, proto.readI16()); + } + }); + } + + private void internalTestNakedI32(int n) throws Exception { + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + proto.writeI32(n); + assertEquals(n, proto.readI32()); + } + + 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); + } + + public void readMethod(TProtocol proto) throws TException { + assertEquals(n, proto.readI32()); + } + }); + } + + private void internalTestNakedI64(long n) throws Exception { + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + proto.writeI64(n); + assertEquals(n, proto.readI64()); + } + + 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); + } + + public void readMethod(TProtocol proto) throws TException { + assertEquals(n, proto.readI64()); + } + }); + } + + private void internalTestNakedString(String str) throws Exception { + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + proto.writeString(str); + assertEquals(str, proto.readString()); + } + + 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); + } + + public void readMethod(TProtocol proto) throws TException { + assertEquals(str, proto.readString()); + } + }); + } + + private void internalTestNakedBinary(byte[] data) throws Exception { + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + proto.writeBinary(ByteBuffer.wrap(data)); + assertEquals(ByteBuffer.wrap(data), proto.readBinary()); + } + + 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)); + } + + 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 { + TMemoryBuffer buf = new TMemoryBuffer(0); + TBinaryProtocol binproto = new TBinaryProtocol(buf); + + expected.write(binproto); + + buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + + expected.write(proto); + System.out.println("Size in " + proto.getClass().getSimpleName() + ": " + buf.length()); + + T actual = klass.newInstance(); + actual.read(proto); + assertEquals(expected, actual); + } + + 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), + }); + + for (TMessage msg : msgs) { + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + TMessage output = null; + + proto.writeMessageBegin(msg); + proto.writeMessageEnd(); + + output = proto.readMessageBegin(); + + assertEquals(msg, output); + } + } + + public void testServerRequest() throws Exception { + Srv.Iface handler = new Srv.Iface() { + public int Janky(int i32arg) throws TException { + return i32arg * 2; + } + + public int primitiveMethod() throws TException { + return 0; + } + + public CompactProtoTestStruct structMethod() throws TException { + return null; + } + + public void voidMethod() throws TException { + } + + public void methodWithDefaultArgs(int something) throws TException { + } + + @Override + public void onewayMethod() throws TException { + } + + @Override + public boolean declaredExceptionMethod(boolean shouldThrow) throws TException { + return shouldThrow; + } + }; + + Srv.Processor testProcessor = new Srv.Processor(handler); + + TMemoryBuffer clientOutTrans = new TMemoryBuffer(0); + TProtocol clientOutProto = getFactory().getProtocol(clientOutTrans); + TMemoryBuffer clientInTrans = new TMemoryBuffer(0); + TProtocol clientInProto = getFactory().getProtocol(clientInTrans); + + Srv.Client testClient = new Srv.Client(clientInProto, clientOutProto); + + testClient.send_Janky(1); + // System.out.println(clientOutTrans.inspect()); + testProcessor.process(clientOutProto, clientInProto); + // System.out.println(clientInTrans.inspect()); + assertEquals(2, testClient.recv_Janky()); + } + + public void testTDeserializer() throws TException { + TSerializer ser = new TSerializer(getFactory()); + byte[] bytes = ser.serialize(Fixtures.compactProtoTestStruct); + + TDeserializer deser = new TDeserializer(getFactory()); + CompactProtoTestStruct cpts = new CompactProtoTestStruct(); + deser.deserialize(cpts, bytes); + + assertEquals(Fixtures.compactProtoTestStruct, cpts); + } + + // + // Helper methods + // + + private void internalTestStructField(StructFieldTestCase testCase) throws Exception { + TMemoryBuffer buf = new TMemoryBuffer(0); + TProtocol proto = getFactory().getProtocol(buf); + + TField field = new TField("test_field", testCase.type_, testCase.id_); + proto.writeStructBegin(new TStruct("test_struct")); + proto.writeFieldBegin(field); + testCase.writeMethod(proto); + proto.writeFieldEnd(); + proto.writeStructEnd(); + + proto.readStructBegin(); + TField readField = proto.readFieldBegin(); + assertEquals(testCase.id_, readField.id); + assertEquals(testCase.type_, readField.type); + testCase.readMethod(proto); + proto.readStructEnd(); + } + + private static abstract 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; + } + + private static final int NUM_TRIALS = 5; + private static final int NUM_REPS = 10000; + + protected void benchmark() throws Exception { + for (int trial = 0; trial < NUM_TRIALS; trial++) { + TSerializer ser = new TSerializer(getFactory()); + byte[] serialized = null; + long serStart = System.currentTimeMillis(); + for (int rep = 0; rep < NUM_REPS; rep++) { + serialized = ser.serialize(Fixtures.holyMoley); + } + long serEnd = System.currentTimeMillis(); + long serElapsed = serEnd - serStart; + System.out.println("Ser:\t" + serElapsed + "ms\t" + + ((double)serElapsed / NUM_REPS) + "ms per serialization"); + + HolyMoley cpts = new HolyMoley(); + TDeserializer deser = new TDeserializer(getFactory()); + long deserStart = System.currentTimeMillis(); + for (int rep = 0; rep < NUM_REPS; rep++) { + deser.deserialize(cpts, serialized); + } + long deserEnd = System.currentTimeMillis(); + long deserElapsed = deserEnd - deserStart; + System.out.println("Des:\t" + deserElapsed + "ms\t" + + ((double)deserElapsed / NUM_REPS) + "ms per deserialization"); + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestShortStack.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestShortStack.java new file mode 100644 index 000000000..c8e78eee6 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestShortStack.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.protocol; + +import junit.framework.TestCase; + +public class TestShortStack extends TestCase { + + 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()); + try { + s.pop(); + fail("should have thrown an exception!"); + } catch (Exception e) { + // yay + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTCompactProtocol.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTCompactProtocol.java new file mode 100644 index 000000000..b4c0888a4 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTCompactProtocol.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.apache.thrift.protocol; + +import org.apache.thrift.TDeserializer; +import org.apache.thrift.TException; + +import thrift.test.Bonk; + +public class TestTCompactProtocol extends ProtocolTestBase { + @Override + protected TProtocolFactory getFactory() { + return new TCompactProtocol.Factory(); + } + + @Override + protected boolean canBeUsedNaked() { + return true; + } + + 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)); + Bonk bonk = new Bonk(); + try { + deser.deserialize(bonk, bytes); + } catch (TException e) { + // Ignore as we are only checking for OOM in the failure case + } + } + + public static void main(String args[]) throws Exception { + new TestTCompactProtocol().benchmark(); + } +}
\ No newline at end of file diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTField.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTField.java new file mode 100644 index 000000000..f72c25972 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTField.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.protocol; + +import junit.framework.TestCase; +import static org.junit.Assert.assertNotEquals; + +public abstract class TestTField extends TestCase { + + public void testConstructor() { + TField uut = new TField(); + assertEquals("", uut.name); + assertEquals(TType.STOP, uut.type); + assertEquals(0, uut.id); + + uut = new TField("foo", TType.VOID, (short)42); + assertEquals("foo", uut.name); + assertEquals(TType.VOID, uut.type); + assertEquals(42, uut.id); + } + + public void testEquality() { + TField uut1 = new TField(); + TField uut2 = new TField(); + assertEquals(uut1, uut2); + assertEquals(uut1.hashCode(), uut2.hashCode()); + + 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); + assertNotEquals(uut1, uut2); + assertNotEquals(uut1.hashCode(), uut2.hashCode()); + + 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/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTJSONProtocol.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTJSONProtocol.java new file mode 100644 index 000000000..c2ca1fa7a --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTJSONProtocol.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.protocol; + +import java.nio.charset.StandardCharsets; + +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TJSONProtocol; +import org.apache.thrift.transport.TMemoryBuffer; + +public class TestTJSONProtocol extends ProtocolTestBase { + @Override + protected TProtocolFactory getFactory() { + return new TJSONProtocol.Factory(); + } + + @Override + protected boolean canBeUsedNaked() { + return false; + } + + public void testEscapedUnicode() throws TException { + String jsonString = "\"hello unicode \\u0e01\\ud834\\udd1e world\""; + String expectedString = "hello unicode \u0e01\ud834\udd1e world"; + + TMemoryBuffer buffer = new TMemoryBuffer(1000); + TJSONProtocol protocol = new TJSONProtocol(buffer); + buffer.write(jsonString.getBytes(StandardCharsets.UTF_8)); + + assertEquals(expectedString, protocol.readString()); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTProtocolUtil.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTProtocolUtil.java new file mode 100644 index 000000000..89cf5366e --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTProtocolUtil.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.protocol; + +import junit.framework.TestCase; + +import org.apache.thrift.TSerializer; + +import thrift.test.GuessProtocolStruct; + +public class TestTProtocolUtil extends TestCase { + + public void testGuessProtocolFactory_JSON() throws Exception { + + byte[] data = "{foo}".getBytes(); + 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("}","}"); + byte[] ser = new TSerializer(new TCompactProtocol.Factory()).serialize(s); + factory = TProtocolUtil.guessProtocolFactory(ser, new TCompactProtocol.Factory()); + assertFalse(factory instanceof TJSONProtocol.Factory); + } + + public void testGuessProtocolFactory_Binary() throws Exception { + // Check that a last byte != 0 is correctly reported as Binary + + byte[] buf = new byte[1]; + for (int i = 1; i < 256; i++) { + buf[0] = (byte) i; + 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()); + assertTrue(factory instanceof TBinaryProtocol.Factory); + } + + public void testGuessProtocolFactory_Compact() throws Exception { + // 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()); + assertTrue(factory instanceof TCompactProtocol.Factory); + + // Check that second byte >= 0x80 is reported as Compact + buf[0] = 0; + for (int i = 0x80; i < 0x100; i++) { + buf[1] = (byte) i; + factory = TProtocolUtil.guessProtocolFactory(buf, new TBinaryProtocol.Factory()); + assertTrue(factory instanceof TCompactProtocol.Factory); + } + } + + public void testGuessProtocolFactory_Undecided() throws Exception { + byte[] buf = new byte[3]; + buf[1] = 0x7e; + TProtocolFactory factory = TProtocolUtil.guessProtocolFactory(buf, new TSimpleJSONProtocol.Factory()); + assertTrue(factory instanceof TSimpleJSONProtocol.Factory); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java new file mode 100644 index 000000000..171a487ea --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.protocol; + +import java.nio.charset.StandardCharsets; + +import junit.framework.TestCase; + +import org.apache.thrift.Fixtures; +import org.apache.thrift.TException; +import org.apache.thrift.transport.TMemoryBuffer; + +import thrift.test.CompactProtoTestStruct; +import thrift.test.HolyMoley; + +public class TestTSimpleJSONProtocol extends TestCase { + private TMemoryBuffer buf; + private TSimpleJSONProtocol proto; + + @Override + protected void setUp() throws Exception { + buf = new TMemoryBuffer(1000); + proto = new TSimpleJSONProtocol(buf); + } + + private String bufToString() { + return buf.toString(StandardCharsets.UTF_8); + } + + public void testHolyMoley() throws TException { + final HolyMoley holyMoley = Fixtures.holyMoley.deepCopy(); + // unset sets that produce inconsistent ordering between JDK7/8 + 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()); + } + + public void testNesting() throws TException { + Fixtures.nesting.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()); + } + + public void testOneOfEach() throws TException { + Fixtures.oneOfEach.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()); + } + + public void testSanePartsOfCompactProtoTestStruct() throws TException { + // unset all the maps with container keys + CompactProtoTestStruct struct = Fixtures.compactProtoTestStruct.deepCopy(); + struct.unsetList_byte_map(); + struct.unsetSet_byte_map(); + struct.unsetMap_byte_map(); + // unset sets and maps that produce inconsistent ordering between JDK7/8 + struct.unsetByte_set(); + struct.unsetI16_set(); + struct.unsetI64_set(); + struct.unsetDouble_set(); + struct.unsetString_set(); + struct.unsetI16_byte_map(); + struct.unsetI32_byte_map(); + struct.unsetI64_byte_map(); + 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()); + } + + public void testThrowsOnCollectionKeys() throws TException { + try { + Fixtures.compactProtoTestStruct.write(proto); + fail("this should throw a CollectionMapKeyException"); + } catch (TSimpleJSONProtocol.CollectionMapKeyException e) { + // + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTTupleProtocol.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTTupleProtocol.java new file mode 100644 index 000000000..b654db3f8 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/protocol/TestTTupleProtocol.java @@ -0,0 +1,27 @@ +package org.apache.thrift.protocol; + +import org.apache.thrift.TDeserializer; +import org.apache.thrift.TSerializer; + +import thrift.test.TupleProtocolTestStruct; + + +public class TestTTupleProtocol extends ProtocolTestBase { + + @Override + protected boolean canBeUsedNaked() { + return false; + } + + @Override + protected TProtocolFactory getFactory() { + return new TTupleProtocol.Factory(); + } + + public void testBitsetLengthIssue() throws Exception { + 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)); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/scheme/TestStandardScheme.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/scheme/TestStandardScheme.java new file mode 100644 index 000000000..33f229e88 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/scheme/TestStandardScheme.java @@ -0,0 +1,40 @@ +package org.apache.thrift.scheme; + +import junit.framework.TestCase; + +import org.apache.thrift.Fixtures; +import org.apache.thrift.TBase; +import org.apache.thrift.TDeserializer; +import org.apache.thrift.TException; +import org.apache.thrift.TSerializer; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TMemoryBuffer; +import org.apache.thrift.transport.TTransport; + +import thrift.test.HolyMoley; +import thrift.test.Nesting; +import thrift.test.OneOfEach; + +public class TestStandardScheme extends TestCase { + TSerializer serializer = new TSerializer(); + TDeserializer deserializer = new TDeserializer(); + + /** + * This tests whether the Standard Scheme properly reads structs serialized + * using an older version of thrift. + */ + public void testPersistentStructs() throws TException { + readAndCompare(new OneOfEach(), Fixtures.oneOfEach, Fixtures.persistentBytesOneOfEach); + readAndCompare(new HolyMoley(), Fixtures.holyMoley, Fixtures.persistentBytesHolyMoley); + readAndCompare(new Nesting(), Fixtures.nesting, Fixtures.persistentBytesNesting); + } + + public void readAndCompare(TBase struct, TBase fixture, byte[] inputBytes) throws TException { + TTransport trans = new TMemoryBuffer(0); + trans.write(inputBytes, 0, inputBytes.length); + TProtocol iprot = new TBinaryProtocol(trans); + struct.read(iprot); + assertEquals(fixture, struct); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/ServerTestBase.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/ServerTestBase.java new file mode 100644 index 000000000..8348cbc3d --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/ServerTestBase.java @@ -0,0 +1,715 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.server; + +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 java.nio.ByteBuffer; + +import junit.framework.TestCase; + +import org.apache.thrift.TException; +import org.apache.thrift.TProcessor; +import org.apache.thrift.async.AsyncMethodCallback; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TCompactProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.protocol.TProtocolFactory; +import org.apache.thrift.transport.TFramedTransport; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportFactory; +import org.apache.thrift.transport.TFramedTransport.Factory; + +import thrift.test.Insanity; +import thrift.test.Numberz; +import thrift.test.ThriftTest; +import thrift.test.Xception; +import thrift.test.Xception2; +import thrift.test.Xtruct; +import thrift.test.Xtruct2; + +public abstract class ServerTestBase extends TestCase { + + public static class TestHandler implements ThriftTest.Iface { + + public TestHandler() {} + + public void testVoid() { + System.out.print("testVoid()\n"); + } + + public String testString(String thing) { + System.out.print("testString(\"" + thing + "\")\n"); + return thing; + } + + public boolean testBool(boolean thing) { + System.out.print("testBool(" + thing + ")\n"); + return thing; + } + + public byte testByte(byte thing) { + System.out.print("testByte(" + thing + ")\n"); + return thing; + } + + public int testI32(int thing) { + System.out.print("testI32(" + thing + ")\n"); + return thing; + } + + public long testI64(long thing) { + System.out.print("testI64(" + thing + ")\n"); + return thing; + } + + public double testDouble(double thing) { + System.out.print("testDouble(" + thing + ")\n"); + return thing; + } + + 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 + while ((thing.remaining() > 0) && (++limit < 1024)) { + sb.append(String.format("%02X ", thing.get())); + } + if(thing.remaining() > 0) { + sb.append("..."); // indicate we have more date + } + System.out.print("testBinary(" + sb.toString() + ")\n"); + thing.reset(); + return thing; + } + + public Xtruct testStruct(Xtruct thing) { + System.out.print("testStruct({" + + "\"" + thing.string_thing + "\", " + + thing.byte_thing + ", " + + thing.i32_thing + ", " + + thing.i64_thing + "})\n"); + return thing; + } + + 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"); + return nest; + } + + public Map<Integer,Integer> testMap(Map<Integer,Integer> thing) { + System.out.print("testMap({"); + System.out.print(thing); + System.out.print("})\n"); + return thing; + } + + public Map<String,String> testStringMap(Map<String,String> thing) { + System.out.print("testStringMap({"); + System.out.print(thing); + System.out.print("})\n"); + return thing; + } + + public Set<Integer> testSet(Set<Integer> thing) { + System.out.print("testSet({"); + boolean first = true; + for (int elem : thing) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(elem); + } + System.out.print("})\n"); + return thing; + } + + public List<Integer> testList(List<Integer> thing) { + System.out.print("testList({"); + boolean first = true; + for (int elem : thing) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(elem); + } + System.out.print("})\n"); + return thing; + } + + public Numberz testEnum(Numberz thing) { + System.out.print("testEnum(" + thing + ")\n"); + return thing; + } + + public long testTypedef(long thing) { + System.out.print("testTypedef(" + thing + ")\n"); + return thing; + } + + public Map<Integer,Map<Integer,Integer>> testMapMap(int hello) { + System.out.print("testMapMap(" + hello + ")\n"); + Map<Integer,Map<Integer,Integer>> mapmap = + new HashMap<Integer,Map<Integer,Integer>>(); + + HashMap<Integer,Integer> pos = new HashMap<Integer,Integer>(); + HashMap<Integer,Integer> neg = new HashMap<Integer,Integer>(); + for (int i = 1; i < 5; i++) { + pos.put(i, i); + neg.put(-i, -i); + } + + mapmap.put(4, pos); + mapmap.put(-4, neg); + + return mapmap; + } + + public Map<Long, Map<Numberz,Insanity>> testInsanity(Insanity argument) { + System.out.print("testInsanity()\n"); + + HashMap<Numberz,Insanity> first_map = new HashMap<Numberz, Insanity>(); + HashMap<Numberz,Insanity> second_map = new HashMap<Numberz, Insanity>();; + + first_map.put(Numberz.TWO, argument); + first_map.put(Numberz.THREE, argument); + + Insanity looney = new Insanity(); + second_map.put(Numberz.SIX, looney); + + Map<Long,Map<Numberz,Insanity>> insane = + new HashMap<Long, Map<Numberz,Insanity>>(); + insane.put((long)1, first_map); + insane.put((long)2, second_map); + + return insane; + } + + 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();; + hello.string_thing = "Hello2"; + hello.byte_thing = arg0; + hello.i32_thing = arg1; + hello.i64_thing = arg2; + return hello; + } + + public void testException(String arg) throws Xception, TException { + System.out.print("testException("+arg+")\n"); + if ("Xception".equals(arg)) { + Xception x = new Xception(); + x.errorCode = 1001; + x.message = arg; + throw x; + } else if ("TException".equals(arg)) { + // Unspecified exception should yield a TApplicationException on client side + throw new RuntimeException(arg); + } else { + Xtruct result = new Xtruct(); + result.string_thing = arg; + } + return; + } + + public Xtruct testMultiException(String arg0, String arg1) throws Xception, Xception2 { + System.out.print("testMultiException(" + arg0 + ", " + arg1 + ")\n"); + if (arg0.equals("Xception")) { + Xception x = new Xception(); + x.errorCode = 1001; + x.message = "This is an Xception"; + throw x; + } else if (arg0.equals("Xception2")) { + Xception2 x = new Xception2(); + x.errorCode = 2002; + x.struct_thing = new Xtruct(); + x.struct_thing.string_thing = "This is an Xception2"; + throw x; + } + + Xtruct result = new Xtruct(); + result.string_thing = arg1; + return result; + } + + public void testOneway(int sleepFor) { + System.out.println("testOneway(" + Integer.toString(sleepFor) + + ") => sleeping..."); + try { + Thread.sleep(sleepFor * SLEEP_DELAY); + System.out.println("Done sleeping!"); + } catch (InterruptedException ie) { + throw new RuntimeException(ie); + } + } + } // class TestHandler + + 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.valueOf( + System.getProperty("test.port", "9090")); + protected static final int 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); + + 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 stopServer() throws Exception; + + public abstract TTransport getClientTransport(TTransport underlyingTransport) throws Exception; + + private void testBool(ThriftTest.Client testClient) throws TException { + boolean t = testClient.testBool(true); + assertEquals(true, t); + boolean f = testClient.testBool(false); + assertEquals(false, f); + } + + private void testByte(ThriftTest.Client testClient) throws TException { + byte i8 = testClient.testByte((byte)1); + assertEquals(1, i8); + } + + private void testDouble(ThriftTest.Client testClient) throws TException { + double dub = testClient.testDouble(5.325098235); + assertEquals(5.325098235, dub); + } + + private void testEnum(ThriftTest.Client testClient) throws TException { + assertEquals(Numberz.ONE, testClient.testEnum(Numberz.ONE)); + assertEquals(Numberz.TWO, testClient.testEnum(Numberz.TWO)); + assertEquals(Numberz.THREE, testClient.testEnum(Numberz.THREE)); + assertEquals(Numberz.FIVE, testClient.testEnum(Numberz.FIVE)); + assertEquals(Numberz.EIGHT, testClient.testEnum(Numberz.EIGHT)); + } + + private void testI32(ThriftTest.Client testClient) throws TException { + int i32 = testClient.testI32(-1); + assertEquals(i32, -1); + } + + private void testI64(ThriftTest.Client testClient) throws TException { + long i64 = testClient.testI64(-34359738368L); + assertEquals(i64, -34359738368L); + } + + // todo: add assertions + private void testInsanity(ThriftTest.Client testClient) throws TException { + Insanity insane; + + insane = new Insanity(); + insane.userMap = new HashMap<Numberz, Long>(); + insane.userMap.put(Numberz.FIVE, (long)5000); + Xtruct truck = new Xtruct(); + truck.string_thing = "Truck"; + truck.byte_thing = (byte)8; + truck.i32_thing = 8; + truck.i64_thing = 8; + insane.xtructs = new ArrayList<Xtruct>(); + insane.xtructs.add(truck); + System.out.print("testInsanity()"); + Map<Long,Map<Numberz,Insanity>> whoa = + testClient.testInsanity(insane); + System.out.print(" = {"); + for (long key : whoa.keySet()) { + Map<Numberz,Insanity> val = whoa.get(key); + System.out.print(key + " => {"); + + for (Numberz k2 : val.keySet()) { + Insanity v2 = val.get(k2); + System.out.print(k2 + " => {"); + Map<Numberz, Long> userMap = v2.userMap; + System.out.print("{"); + if (userMap != null) { + for (Numberz k3 : userMap.keySet()) { + System.out.print(k3 + " => " + userMap.get(k3) + ", "); + } + } + System.out.print("}, "); + + List<Xtruct> xtructs = v2.xtructs; + 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("}"); + + System.out.print("}, "); + } + System.out.print("}, "); + } + System.out.print("}\n"); + } + + public boolean useAsyncProcessor() { + return false; + } + + public void testIt() throws Exception { + + for (TProtocolFactory protoFactory : getProtocols()) { + TProcessor processor = useAsyncProcessor() ? new ThriftTest.AsyncProcessor<AsyncTestHandler>(new AsyncTestHandler()) : new ThriftTest.Processor<TestHandler>(new TestHandler()); + + startServer(processor, protoFactory); + + TSocket socket = new TSocket(HOST, PORT); + socket.setTimeout(SOCKET_TIMEOUT); + TTransport transport = getClientTransport(socket); + + TProtocol protocol = protoFactory.getProtocol(transport); + ThriftTest.Client testClient = new ThriftTest.Client(protocol); + + open(transport); + testVoid(testClient); + testString(testClient); + testBool(testClient); + testByte(testClient); + testI32(testClient); + testI64(testClient); + testDouble(testClient); + testStruct(testClient); + testNestedStruct(testClient); + testMap(testClient); + testStringMap(testClient); + testSet(testClient); + testList(testClient); + testEnum(testClient); + testTypedef(testClient); + testNestedMap(testClient); + testInsanity(testClient); + testException(testClient); + testOneway(testClient); + testI32(testClient); + transport.close(); + socket.close(); + + stopServer(); + } + } + + public void open(TTransport transport) throws Exception { + transport.open(); + } + + public List<TProtocolFactory> getProtocols() { + return PROTOCOLS; + } + + private void testList(ThriftTest.Client testClient) throws TException { + List<Integer> listout = new ArrayList<Integer>(); + for (int i = -2; i < 3; ++i) { + listout.add(i); + } + List<Integer> listin = testClient.testList(listout); + assertEquals(listout, listin); + } + + private void testMap(ThriftTest.Client testClient) throws TException { + Map<Integer,Integer> mapout = new HashMap<Integer,Integer>(); + for (int i = 0; i < 5; ++i) { + mapout.put(i, i-10); + } + Map<Integer,Integer> mapin = testClient.testMap(mapout); + assertEquals(mapout, mapin); + } + + private void testStringMap(ThriftTest.Client testClient) throws TException { + Map<String,String> mapout = new HashMap<String,String>(); + 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); + 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<Integer,Map<Integer,Integer>>(); + + HashMap<Integer,Integer> pos = new HashMap<Integer,Integer>(); + HashMap<Integer,Integer> neg = new HashMap<Integer,Integer>(); + for (int i = 1; i < 5; i++) { + pos.put(i, i); + neg.put(-i, -i); + } + + mapmap.put(4, pos); + mapmap.put(-4, neg); + assertEquals(mapmap, mm); + } + + private void testNestedStruct(ThriftTest.Client testClient) throws TException { + Xtruct2 in2 = testClient.testNest(XSTRUCT2); + assertEquals(XSTRUCT2, in2); + } + + private void testOneway(ThriftTest.Client testClient) throws Exception { + long begin = System.currentTimeMillis(); + testClient.testOneway(1); + long elapsed = System.currentTimeMillis() - begin; + assertTrue(elapsed < 500); + } + + private void testSet(ThriftTest.Client testClient) throws TException { + Set<Integer> setout = new HashSet<Integer>(); + for (int i = -2; i < 3; ++i) { + setout.add(i); + } + Set<Integer> setin = testClient.testSet(setout); + assertEquals(setout, setin); + } + + private void testString(ThriftTest.Client testClient) throws TException { + String s = testClient.testString("Test"); + assertEquals("Test", s); + } + + private void testStruct(ThriftTest.Client testClient) throws TException { + assertEquals(XSTRUCT, testClient.testStruct(XSTRUCT)); + } + + private void testTypedef(ThriftTest.Client testClient) throws TException { + assertEquals(309858235082523L, testClient.testTypedef(309858235082523L)); + } + + private void testVoid(ThriftTest.Client testClient) throws TException { + testClient.testVoid(); + } + + private static class CallCountingTransportFactory extends TTransportFactory { + public int count = 0; + private final Factory factory; + + public CallCountingTransportFactory(Factory factory) { + this.factory = factory; + } + + @Override + public TTransport getTransport(TTransport trans) { + count++; + return factory.getTransport(trans); + } + } + + public void testTransportFactory() throws Exception { + for (TProtocolFactory protoFactory : getProtocols()) { + TestHandler handler = new TestHandler(); + ThriftTest.Processor<TestHandler> processor = new ThriftTest.Processor<TestHandler>(handler); + + final CallCountingTransportFactory factory = new CallCountingTransportFactory(new TFramedTransport.Factory()); + + startServer(processor, protoFactory, factory); + assertEquals(0, factory.count); + + TSocket socket = new TSocket(HOST, PORT); + socket.setTimeout(SOCKET_TIMEOUT); + TTransport transport = getClientTransport(socket); + open(transport); + + TProtocol protocol = protoFactory.getProtocol(transport); + ThriftTest.Client testClient = new ThriftTest.Client(protocol); + assertEquals(0, testClient.testByte((byte) 0)); + assertEquals(2, factory.count); + socket.close(); + stopServer(); + } + } + + private void testException(ThriftTest.Client testClient) throws TException, Xception { + try { + testClient.testException("Xception"); + assert false; + } catch(Xception e) { + assertEquals(e.message, "Xception"); + assertEquals(e.errorCode, 1001); + } + try { + testClient.testException("TException"); + assert false; + } catch(TException e) { + } + testClient.testException("no Exception"); + } + + + public static class AsyncTestHandler implements ThriftTest.AsyncIface { + + TestHandler handler = new TestHandler(); + + @Override + public void testVoid(AsyncMethodCallback<Void> resultHandler) throws TException { + resultHandler.onComplete(null); + } + + @Override + 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 { + resultHandler.onComplete(handler.testBool(thing)); + } + + @Override + public void testByte(byte thing, AsyncMethodCallback<Byte> resultHandler) throws TException { + resultHandler.onComplete(handler.testByte(thing)); + } + + @Override + public void testI32(int thing, AsyncMethodCallback<Integer> resultHandler) throws TException { + resultHandler.onComplete(handler.testI32(thing)); + } + + @Override + public void testI64(long thing, AsyncMethodCallback<Long> resultHandler) throws TException { + resultHandler.onComplete(handler.testI64(thing)); + } + + @Override + 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 { + resultHandler.onComplete(handler.testBinary(thing)); + } + + @Override + 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 { + resultHandler.onComplete(handler.testNest(thing)); + } + + @Override + 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 { + resultHandler.onComplete(handler.testStringMap(thing)); + } + + @Override + 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 { + resultHandler.onComplete(handler.testList(thing)); + } + + @Override + public void testEnum(Numberz thing, AsyncMethodCallback<Numberz> resultHandler) throws TException { + resultHandler.onComplete(handler.testEnum(thing)); + } + + @Override + public void testTypedef(long thing, AsyncMethodCallback<Long> resultHandler) throws TException { + resultHandler.onComplete(handler.testTypedef(thing)); + } + + @Override + 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 { + 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)); + } + + @Override + 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; + x.message = arg; + // throw and onError yield the same result. + // throw x; + resultHandler.onError(x); + return; + } else if ("TException".equals(arg)) { + // throw and onError yield the same result. + // resultHandler.onError(new TException(arg)); + // return; + // Unspecified exception should yield a TApplicationException on client side + throw new RuntimeException(arg); + } + resultHandler.onComplete(null); + } + + @Override + 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 { + handler.testOneway(secondsToSleep); + resultHandler.onComplete(null); + } + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestAsyncServer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestAsyncServer.java new file mode 100644 index 000000000..29c54cbbc --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestAsyncServer.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.server; + +public class TestAsyncServer extends TestNonblockingServer { + + @Override + public boolean useAsyncProcessor(){ + return true; + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestHsHaServer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestHsHaServer.java new file mode 100644 index 000000000..6638a333f --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestHsHaServer.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.server; + +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TProtocolFactory; +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) { + return new THsHaServer(new Args(socket).processor(processor).protocolFactory(protoFactory)); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestNonblockingServer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestNonblockingServer.java new file mode 100644 index 000000000..3df3bd827 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestNonblockingServer.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.server; + + +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.protocol.TProtocolFactory; +import org.apache.thrift.server.TNonblockingServer.Args; +import org.apache.thrift.transport.TFramedTransport; +import org.apache.thrift.transport.TNonblockingServerSocket; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportException; +import org.apache.thrift.transport.TTransportFactory; + +import thrift.test.ThriftTest; + +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) { + final Args args = new Args(socket).processor(processor).protocolFactory(protoFactory); + if (factory != null) { + args.transportFactory(factory); + } + return new TNonblockingServer(args); + } + + @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(); + } + } + }; + serverThread.start(); + Thread.sleep(1000); + } + + @Override + public void stopServer() throws Exception { + server.stop(); + try { + serverThread.join(); + } catch (InterruptedException e) {} + } + + @Override + public TTransport getClientTransport(TTransport underlyingTransport) throws Exception { + return new TFramedTransport(underlyingTransport); + } + + + public void testCleanupAllSelectionKeys() throws Exception { + for (TProtocolFactory protoFactory : getProtocols()) { + TestHandler handler = new TestHandler(); + ThriftTest.Processor processor = new ThriftTest.Processor(handler); + + startServer(processor, protoFactory); + + TSocket socket = new TSocket(HOST, PORT); + socket.setTimeout(SOCKET_TIMEOUT); + TTransport transport = getClientTransport(socket); + + TProtocol protocol = protoFactory.getProtocol(transport); + ThriftTest.Client testClient = new ThriftTest.Client(protocol); + + open(transport); + + for (int i = 0; i < NUM_QUERIES; ++i) { + testClient.testI32(1); + } + server.stop(); + for (int i = 0; i < NUM_QUERIES; ++i) { + try { + testClient.testI32(1); + } catch(TTransportException e) { + System.err.println(e); + e.printStackTrace(); + if (e.getCause() instanceof java.net.SocketTimeoutException) { + fail("timed out when it should have thrown another kind of error!"); + } + } + } + + transport.close(); + stopServer(); + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestThreadedSelectorServer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestThreadedSelectorServer.java new file mode 100644 index 000000000..ed729a296 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/server/TestThreadedSelectorServer.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.server; + +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TProtocolFactory; +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)); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/EqualityTest.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/EqualityTest.java new file mode 100644 index 000000000..94ba543a8 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/EqualityTest.java @@ -0,0 +1,663 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* +This program was generated by the following Python script: + +#!/usr/bin/python2.5 + +# Remove this when Python 2.6 hits the streets. +from __future__ import with_statement + +import sys +import os.path + + +# Quines the easy way. +with open(sys.argv[0], 'r') as handle: + source = handle.read() + +with open(os.path.join(os.path.dirname(sys.argv[0]), 'EqualityTest.java'), 'w') as out: + print >> out, ("/""*" r""" + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + """ "*""/") + print >> out + print >> out, "/""*" + print >> out, "This program was generated by the following Python script:" + print >> out + out.write(source) + print >> out, "*""/" + + print >> out, r''' +package org.apache.thrift.test; + +// Generated code +import thrift.test.*; + +/'''r'''** + *'''r'''/ +public class EqualityTest { + public static void main(String[] args) throws Exception { + JavaTestHelper lhs, rhs; +''' + + vals = { + 'int': ("1", "2"), + 'obj': ("\"foo\"", "\"bar\""), + 'bin': ("new byte[]{1,2}", "new byte[]{3,4}"), + } + matrix = ( + (False,False), + (False,True ), + (True ,False), + (True ,True ), + ) + + for type in ('int', 'obj', 'bin'): + for option in ('req', 'opt'): + nulls = matrix[0:1] if type == 'int' else matrix[-1::-1] + issets = matrix + for is_null in nulls: + for is_set in issets: + # isset is implied for non-primitives, so only consider the case + # where isset and non-null match. + if type != 'int' and list(is_set) != [ not null for null in is_null ]: + continue + for equal in (True, False): + print >> out + print >> out, " lhs = new JavaTestHelper();" + print >> out, " rhs = new JavaTestHelper();" + print >> out, " lhs." + option + "_" + type, "=", vals[type][0] + ";" + print >> out, " rhs." + option + "_" + type, "=", vals[type][0 if equal else 1] + ";" + isset_setter = "set" + option[0].upper() + option[1:] + "_" + type + "IsSet" + if (type == 'int' and is_set[0]): print >> out, " lhs." + isset_setter + "(true);" + if (type == 'int' and is_set[1]): print >> out, " rhs." + isset_setter + "(true);" + if (is_null[0]): print >> out, " lhs." + option + "_" + type, "= null;" + if (is_null[1]): print >> out, " rhs." + option + "_" + type, "= null;" + this_present = not is_null[0] and (option == 'req' or is_set[0]) + that_present = not is_null[1] and (option == 'req' or is_set[1]) + print >> out, " // this_present = " + repr(this_present) + print >> out, " // that_present = " + repr(that_present) + is_equal = \ + (not this_present and not that_present) or \ + (this_present and that_present and equal) + eq_str = 'true' if is_equal else 'false' + + print >> out, " if (lhs.equals(rhs) != "+eq_str+")" + print >> out, " throw new RuntimeException(\"Failure\");" + if is_equal: + print >> out, " if (lhs.hashCode() != rhs.hashCode())" + print >> out, " throw new RuntimeException(\"Failure\");" + + print >> out, r''' + } +} +''' +*/ + +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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_int = 1; + rhs.req_int = 2; + // this_present = True + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_int = 1; + rhs.req_int = 1; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_int = 1; + rhs.req_int = 2; + rhs.setReq_intIsSet(true); + // this_present = True + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_int = 1; + rhs.req_int = 1; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_int = 1; + rhs.req_int = 2; + lhs.setReq_intIsSet(true); + // this_present = True + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_int = 1; + rhs.req_int = 1; + lhs.setReq_intIsSet(true); + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_int = 1; + rhs.req_int = 2; + lhs.setReq_intIsSet(true); + rhs.setReq_intIsSet(true); + // this_present = True + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + rhs.opt_int = 1; + rhs.setOpt_intIsSet(true); + // this_present = False + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + rhs.opt_int = 2; + rhs.setOpt_intIsSet(true); + // this_present = False + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + rhs.opt_int = 1; + lhs.setOpt_intIsSet(true); + // this_present = True + // that_present = False + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + rhs.opt_int = 2; + lhs.setOpt_intIsSet(true); + // this_present = True + // that_present = False + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + rhs.opt_int = 1; + lhs.setOpt_intIsSet(true); + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_int = 1; + rhs.opt_int = 2; + lhs.setOpt_intIsSet(true); + rhs.setOpt_intIsSet(true); + // this_present = True + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + rhs.req_obj = "foo"; + lhs.req_obj = null; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + rhs.req_obj = "bar"; + lhs.req_obj = null; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + rhs.req_obj = "foo"; + lhs.req_obj = null; + // this_present = False + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + rhs.req_obj = "bar"; + lhs.req_obj = null; + // this_present = False + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + rhs.req_obj = "foo"; + rhs.req_obj = null; + // this_present = True + // that_present = False + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + rhs.req_obj = "bar"; + rhs.req_obj = null; + // this_present = True + // that_present = False + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.req_obj = "foo"; + rhs.req_obj = "bar"; + // this_present = True + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + rhs.opt_obj = "foo"; + lhs.opt_obj = null; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + rhs.opt_obj = "bar"; + lhs.opt_obj = null; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + rhs.opt_obj = "foo"; + lhs.opt_obj = null; + // this_present = False + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + rhs.opt_obj = "bar"; + lhs.opt_obj = null; + // this_present = False + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + rhs.opt_obj = "foo"; + rhs.opt_obj = null; + // this_present = True + // that_present = False + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + rhs.opt_obj = "bar"; + rhs.opt_obj = null; + // this_present = True + // that_present = False + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + 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"); + + lhs = new JavaTestHelper(); + rhs = new JavaTestHelper(); + lhs.opt_obj = "foo"; + rhs.opt_obj = "bar"; + // this_present = True + // that_present = True + 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 = 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"); + + 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 = 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"); + + 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 = null; + // this_present = False + // that_present = True + 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 = null; + // this_present = False + // that_present = True + 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}); + rhs.req_bin = null; + // this_present = True + // that_present = False + 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}); + rhs.req_bin = null; + // this_present = True + // that_present = False + 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}); + // this_present = True + // that_present = True + 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}); + // this_present = True + // that_present = True + 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 = 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"); + + 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 = 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"); + + 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 = null; + // this_present = False + // that_present = True + 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 = null; + // this_present = False + // that_present = True + 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}); + rhs.opt_bin = null; + // this_present = True + // that_present = False + 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}); + rhs.opt_bin = null; + // this_present = True + // that_present = False + 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}); + // this_present = True + // that_present = True + 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}); + // this_present = True + // that_present = True + if (lhs.equals(rhs) != false) + throw new RuntimeException("Failure"); + + } +} + diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/JavaBeansTest.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/JavaBeansTest.java new file mode 100644 index 000000000..6a2a0ed0c --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/JavaBeansTest.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.test; + +import java.nio.ByteBuffer; +import java.util.LinkedList; + +import thrift.test.OneOfEachBeans; + +public class JavaBeansTest { + public static void main(String[] args) throws Exception { + // Test isSet methods + OneOfEachBeans ooe = new OneOfEachBeans(); + + // Nothing should be set + if (ooe.is_set_a_bite()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_base64()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_byte_list()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_double_precision()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_i16_list()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_i64_list()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_boolean_field()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_integer16()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_integer32()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_integer64()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + if (ooe.is_set_some_characters()) + throw new RuntimeException("isSet method error: unset field returned as set!"); + + 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!"); + } + + // Everything is set + ooe.set_a_bite((byte) 1); + ooe.set_base64(ByteBuffer.wrap("bytes".getBytes())); + ooe.set_byte_list(new LinkedList<Byte>()); + ooe.set_double_precision(1); + ooe.set_i16_list(new LinkedList<Short>()); + ooe.set_i64_list(new LinkedList<Long>()); + ooe.set_boolean_field(true); + ooe.set_integer16((short) 1); + ooe.set_integer32(1); + ooe.set_integer64(1); + ooe.set_some_characters("string"); + + if (!ooe.is_set_a_bite()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_base64()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_byte_list()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_double_precision()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_i16_list()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_i64_list()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_boolean_field()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_integer16()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_integer32()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_integer64()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + if (!ooe.is_set_some_characters()) + throw new RuntimeException("isSet method error: set field returned as unset!"); + + 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{ + if (ooe.isSet(ooe.fieldForId(100))); + } catch (IllegalArgumentException e){ + exceptionThrown = true; + } + if (!exceptionThrown) + throw new RuntimeException("isSet method error: non-existent field provided as agument but no exception thrown!"); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/ReadStruct.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/ReadStruct.java new file mode 100644 index 000000000..7e3b091d4 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/ReadStruct.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.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'."); + } + + TTransport trans = new TIOStreamTransport(new BufferedInputStream(new FileInputStream(args[0]))); + + TProtocolFactory factory = (TProtocolFactory)Class.forName(args[1]).newInstance(); + + TProtocol proto = factory.getProtocol(trans); + + CompactProtoTestStruct cpts = new CompactProtoTestStruct(); + + for (CompactProtoTestStruct._Fields fid : CompactProtoTestStruct.metaDataMap.keySet()) { + cpts.setFieldValue(fid, null); + } + + cpts.read(proto); + + if (cpts.equals(Fixtures.compactProtoTestStruct)) { + System.out.println("Object verified successfully!"); + } else { + System.out.println("Object failed verification!"); + System.out.println("Expected: " + Fixtures.compactProtoTestStruct + " but got " + cpts); + } + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/SerializationBenchmark.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/SerializationBenchmark.java new file mode 100644 index 000000000..2b0db3132 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/SerializationBenchmark.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.apache.thrift.test; + +import org.apache.thrift.Fixtures; +import org.apache.thrift.TBase; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.protocol.TProtocolFactory; +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; + + public static void main(String[] args) throws Exception { + TProtocolFactory factory = new TBinaryProtocol.Factory(); + + testSerialization(factory, Fixtures.oneOfEach); + testDeserialization(factory, Fixtures.oneOfEach, OneOfEach.class); + } + + 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 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); + + long startTime = System.currentTimeMillis(); + for (int i = 0; i < HOW_MANY; i++) { + object.write(proto); + } + long endTime = System.currentTimeMillis(); + + 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 { + TMemoryBuffer buf = new TMemoryBuffer(0); + object.write(factory.getProtocol(buf)); + byte[] serialized = new byte[100*1024]; + buf.read(serialized, 0, 100*1024); + + long startTime = System.currentTimeMillis(); + for (int i = 0; i < HOW_MANY; i++) { + T o2 = klass.newInstance(); + o2.read(factory.getProtocol(new TMemoryInputTransport(serialized))); + } + long endTime = System.currentTimeMillis(); + + System.out.println("Deserialization test time: " + (endTime - startTime) + " ms"); + } +}
\ No newline at end of file diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestClient.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestClient.java new file mode 100644 index 000000000..84410cea0 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestClient.java @@ -0,0 +1,811 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.test; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.thrift.TApplicationException; +import org.apache.thrift.TException; +import org.apache.thrift.TSerializer; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TCompactProtocol; +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.TFastFramedTransport; +import org.apache.thrift.transport.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; + +// Generated code +import thrift.test.Insanity; +import thrift.test.Numberz; +import thrift.test.SecondService; +import thrift.test.ThriftTest; +import thrift.test.Xception; +import thrift.test.Xception2; +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. + * + */ +public class TestClient { + + private static int ERR_BASETYPES = 1; + private static int ERR_STRUCTS = 2; + private static int ERR_CONTAINERS = 4; + private static int ERR_EXCEPTIONS = 8; + private static int ERR_PROTOCOLS = 16; + private static int ERR_UNKNOWN = 64; + + public static void main(String [] args) { + String host = "localhost"; + int port = 9090; + int numTests = 1; + String protocol_type = "binary"; + String transport_type = "buffered"; + boolean ssl = false; + + int socketTimeout = 1000; + + try { + for (int i = 0; i < args.length; ++i) { + if (args[i].startsWith("--host")) { + host = args[i].split("=")[1]; + 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")){ + numTests = Integer.valueOf(args[i].split("=")[1]); + } else if (args[i].equals("--timeout")) { + socketTimeout = Integer.valueOf(args[i].split("=")[1]); + } else if (args[i].startsWith("--protocol")) { + protocol_type = args[i].split("=")[1]; + protocol_type.trim(); + } else if (args[i].startsWith("--transport")) { + transport_type = args[i].split("=")[1]; + transport_type.trim(); + } else if (args[i].equals("--ssl")) { + ssl = true; + } else if (args[i].equals("--help")) { + System.out.println("Allowed options:"); + 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"); + 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(" --testloops[--n]=arg (=" + numTests + ")\tNumber of Tests"); + System.exit(0); + } + } + } catch (Exception x) { + System.err.println("Can not parse arguments! See --help"); + System.exit(ERR_UNKNOWN); + } + + try { + if (protocol_type.equals("binary")) { + } else if (protocol_type.equals("compact")) { + } else if (protocol_type.equals("json")) { + } else if (protocol_type.equals("multi")) { + } else if (protocol_type.equals("multic")) { + } else if (protocol_type.equals("multij")) { + } else { + throw new Exception("Unknown protocol type! " + protocol_type); + } + if (transport_type.equals("buffered")) { + } else if (transport_type.equals("framed")) { + } else if (transport_type.equals("fastframed")) { + } else if (transport_type.equals("http")) { + } else { + throw new Exception("Unknown transport type! " + transport_type); + } + if (transport_type.equals("http") && ssl == true) { + throw new Exception("SSL is not supported over http."); + } + } catch (Exception e) { + System.err.println("Error: " + e.getMessage()); + System.exit(ERR_UNKNOWN); + } + + TTransport transport = null; + + try { + if (transport_type.equals("http")) { + String url = "http://" + host + ":" + port + "/service"; + transport = new THttpClient(url); + } else { + TSocket socket = null; + if (ssl == true) { + socket = TSSLTransportFactory.getClientSocket(host, port, 0); + } else { + socket = new TSocket(host, port); + } + socket.setTimeout(socketTimeout); + transport = socket; + if (transport_type.equals("buffered")) { + } else if (transport_type.equals("framed")) { + transport = new TFramedTransport(transport); + } else if (transport_type.equals("fastframed")) { + transport = new TFastFramedTransport(transport); + } + } + } catch (Exception x) { + x.printStackTrace(); + System.exit(ERR_UNKNOWN); + } + + TProtocol tProtocol = null; + TProtocol tProtocol2 = null; + if (protocol_type.equals("json") || protocol_type.equals("multij")) { + tProtocol = new TJSONProtocol(transport); + } else if (protocol_type.equals("compact") || protocol_type.equals("multic")) { + tProtocol = new TCompactProtocol(transport); + } else { + tProtocol = new TBinaryProtocol(transport); + } + + if (protocol_type.startsWith("multi")) { + tProtocol2 = new TMultiplexedProtocol(tProtocol, "SecondService"); + tProtocol = new TMultiplexedProtocol(tProtocol, "ThriftTest"); + } + + ThriftTest.Client testClient = new ThriftTest.Client(tProtocol); + Insanity insane = new Insanity(); + + long timeMin = 0; + long timeMax = 0; + long timeTot = 0; + + int returnCode = 0; + for (int test = 0; test < numTests; ++test) { + try { + /** + * CONNECT TEST + */ + System.out.println("Test #" + (test+1) + ", " + "connect " + host + ":" + port); + + if (transport.isOpen() == false) { + try { + transport.open(); + } catch (TTransportException ttx) { + ttx.printStackTrace(); + System.out.println("Connect failed: " + ttx.getMessage()); + System.exit(ERR_UNKNOWN); + } + } + + long start = System.nanoTime(); + + /** + * VOID TEST + */ + try { + System.out.print("testVoid()"); + testClient.testVoid(); + System.out.print(" = void\n"); + } catch (TApplicationException tax) { + tax.printStackTrace(); + returnCode |= ERR_BASETYPES; + } + + /** + * STRING TEST + */ + System.out.print("testString(\"Test\")"); + String s = testClient.testString("Test"); + System.out.print(" = \"" + s + "\"\n"); + if (!s.equals("Test")) { + returnCode |= ERR_BASETYPES; + System.out.println("*** FAILURE ***\n"); + } + + /** + * Multiplexed test + */ + if (protocol_type.startsWith("multi")) { + SecondService.Client secondClient = new SecondService.Client(tProtocol2); + System.out.print("secondtestString(\"Test2\")"); + s = secondClient.secondtestString("Test2"); + System.out.print(" = \"" + s + "\"\n"); + if (!s.equals("testString(\"Test2\")")) { + returnCode |= ERR_PROTOCOLS; + System.out.println("*** FAILURE ***\n"); + } + } + /** + * BYTE TEST + */ + System.out.print("testByte(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 + */ + System.out.print("testI32(-1)"); + int i32 = testClient.testI32(-1); + System.out.print(" = " + i32 + "\n"); + if (i32 != -1) { + returnCode |= ERR_BASETYPES; + System.out.println("*** FAILURE ***\n"); + } + + /** + * I64 TEST + */ + System.out.print("testI64(-34359738368)"); + long i64 = testClient.testI64(-34359738368L); + System.out.print(" = " + i64 + "\n"); + if (i64 != -34359738368L) { + returnCode |= ERR_BASETYPES; + System.out.println("*** FAILURE ***\n"); + } + + /** + * DOUBLE TEST + */ + System.out.print("testDouble(-5.325098235)"); + double dub = testClient.testDouble(-5.325098235); + System.out.print(" = " + dub + "\n"); + if (Math.abs(dub - (-5.325098235)) > 0.001) { + returnCode |= ERR_BASETYPES; + System.out.println("*** FAILURE ***\n"); + } + + /** + * 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}; + ByteBuffer bin = testClient.testBinary(ByteBuffer.wrap(data)); + bin.mark(); + byte[] bytes = new byte[bin.limit() - bin.position()]; + bin.get(bytes); + bin.reset(); + System.out.print("{"); + boolean first = true; + for (int i = 0; i < bytes.length; ++i) { + if (first) + first = false; + else + System.out.print(", "); + System.out.print(bytes[i]); + } + System.out.println("}"); + if (!ByteBuffer.wrap(data).equals(bin)) { + returnCode |= ERR_BASETYPES; + System.out.println("*** FAILURE ***\n"); + } + } catch (Exception ex) { + returnCode |= ERR_BASETYPES; + System.out.println("\n*** FAILURE ***\n"); + ex.printStackTrace(System.out); + } + + /** + * STRUCT TEST + */ + System.out.print("testStruct({\"Zero\", 1, -3, -5})"); + Xtruct out = new Xtruct(); + out.string_thing = "Zero"; + out.byte_thing = (byte) 1; + 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"); + if (!in.equals(out)) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + /** + * NESTED STRUCT TEST + */ + System.out.print("testNest({1, {\"Zero\", 1, -3, -5}), 5}"); + Xtruct2 out2 = new Xtruct2(); + 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"); + if (!in2.equals(out2)) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + /** + * MAP TEST + */ + Map<Integer,Integer> mapout = new HashMap<Integer,Integer>(); + for (int i = 0; i < 5; ++i) { + mapout.put(i, i-10); + } + System.out.print("testMap({"); + boolean first = true; + for (int key : mapout.keySet()) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(key + " => " + mapout.get(key)); + } + System.out.print("})"); + Map<Integer,Integer> mapin = testClient.testMap(mapout); + System.out.print(" = {"); + first = true; + for (int key : mapin.keySet()) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(key + " => " + mapout.get(key)); + } + System.out.print("}\n"); + if (!mapout.equals(mapin)) { + returnCode |= ERR_CONTAINERS; + System.out.println("*** FAILURE ***\n"); + } + + /** + * STRING MAP TEST + */ + try { + Map<String, String> smapout = new HashMap<String, String>(); + smapout.put("a", "2"); + smapout.put("b", "blah"); + smapout.put("some", "thing"); + for (String key : smapout.keySet()) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(key + " => " + smapout.get(key)); + } + System.out.print("})"); + Map<String, String> smapin = testClient.testStringMap(smapout); + System.out.print(" = {"); + first = true; + for (String key : smapin.keySet()) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(key + " => " + smapout.get(key)); + } + System.out.print("}\n"); + if (!smapout.equals(smapin)) { + returnCode |= ERR_CONTAINERS; + System.out.println("*** FAILURE ***\n"); + } + } catch (Exception ex) { + returnCode |= ERR_CONTAINERS; + System.out.println("*** FAILURE ***\n"); + ex.printStackTrace(System.out); + } + + /** + * SET TEST + */ + Set<Integer> setout = new HashSet<Integer>(); + for (int i = -2; i < 3; ++i) { + setout.add(i); + } + System.out.print("testSet({"); + first = true; + for (int elem : setout) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(elem); + } + System.out.print("})"); + Set<Integer> setin = testClient.testSet(setout); + System.out.print(" = {"); + first = true; + for (int elem : setin) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(elem); + } + System.out.print("}\n"); + if (!setout.equals(setin)) { + returnCode |= ERR_CONTAINERS; + System.out.println("*** FAILURE ***\n"); + } + + /** + * LIST TEST + */ + List<Integer> listout = new ArrayList<Integer>(); + for (int i = -2; i < 3; ++i) { + listout.add(i); + } + System.out.print("testList({"); + first = true; + for (int elem : listout) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(elem); + } + System.out.print("})"); + List<Integer> listin = testClient.testList(listout); + System.out.print(" = {"); + first = true; + for (int elem : listin) { + if (first) { + first = false; + } else { + System.out.print(", "); + } + System.out.print(elem); + } + System.out.print("}\n"); + if (!listout.equals(listin)) { + returnCode |= ERR_CONTAINERS; + System.out.println("*** FAILURE ***\n"); + } + + /** + * ENUM TEST + */ + System.out.print("testEnum(ONE)"); + Numberz ret = testClient.testEnum(Numberz.ONE); + System.out.print(" = " + ret + "\n"); + if (ret != Numberz.ONE) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + System.out.print("testEnum(TWO)"); + ret = testClient.testEnum(Numberz.TWO); + System.out.print(" = " + ret + "\n"); + if (ret != Numberz.TWO) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + System.out.print("testEnum(THREE)"); + ret = testClient.testEnum(Numberz.THREE); + System.out.print(" = " + ret + "\n"); + if (ret != Numberz.THREE) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + System.out.print("testEnum(FIVE)"); + ret = testClient.testEnum(Numberz.FIVE); + System.out.print(" = " + ret + "\n"); + if (ret != Numberz.FIVE) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + System.out.print("testEnum(EIGHT)"); + ret = testClient.testEnum(Numberz.EIGHT); + System.out.print(" = " + ret + "\n"); + if (ret != Numberz.EIGHT) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + /** + * TYPEDEF TEST + */ + System.out.print("testTypedef(309858235082523)"); + long uid = testClient.testTypedef(309858235082523L); + System.out.print(" = " + uid + "\n"); + if (uid != 309858235082523L) { + returnCode |= ERR_BASETYPES; + System.out.println("*** FAILURE ***\n"); + } + + /** + * NESTED MAP TEST + */ + System.out.print("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); + for (int k2 : m2.keySet()) { + System.out.print(k2 + " => " + m2.get(k2) + ", "); + } + System.out.print("}, "); + } + System.out.print("}\n"); + if (mm.size() != 2 || !mm.containsKey(4) || !mm.containsKey(-4)) { + returnCode |= ERR_CONTAINERS; + System.out.println("*** FAILURE ***\n"); + } 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) { + returnCode |= ERR_CONTAINERS; + System.out.println("*** FAILURE ***\n"); + } + } + + /** + * INSANITY TEST + */ + + boolean insanityFailed = true; + try { + Xtruct hello = new Xtruct(); + hello.string_thing = "Hello2"; + hello.byte_thing = 2; + hello.i32_thing = 2; + hello.i64_thing = 2; + + Xtruct goodbye = new Xtruct(); + goodbye.string_thing = "Goodbye4"; + goodbye.byte_thing = (byte)4; + goodbye.i32_thing = 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.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); + System.out.print(" = {"); + for (long key : whoa.keySet()) { + Map<Numberz,Insanity> val = whoa.get(key); + System.out.print(key + " => {"); + + for (Numberz k2 : val.keySet()) { + Insanity v2 = val.get(k2); + System.out.print(k2 + " => {"); + Map<Numberz, Long> userMap = v2.userMap; + System.out.print("{"); + if (userMap != null) { + for (Numberz k3 : userMap.keySet()) { + System.out.print(k3 + " => " + userMap.get(k3) + ", "); + } + } + System.out.print("}, "); + + List<Xtruct> xtructs = v2.xtructs; + 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("}"); + + System.out.print("}, "); + } + System.out.print("}, "); + } + System.out.print("}\n"); + 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); + // 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 . + if (six.getUserMapSize() == 0 && six.getXtructsSize() == 0) { + // OK + insanityFailed = false; + } + } + } + } catch (Exception ex) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + ex.printStackTrace(System.out); + insanityFailed = false; + } + if (insanityFailed) { + returnCode |= ERR_STRUCTS; + System.out.println("*** FAILURE ***\n"); + } + + /** + * 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) { + System.out.printf(" {%d, \"%s\"}\n", e.errorCode, e.message); + } + + try { + System.out.print("testClient.testException(\"TException\") =>"); + testClient.testException("TException"); + System.out.print(" void\n*** FAILURE ***\n"); + returnCode |= ERR_EXCEPTIONS; + } catch(TException e) { + System.out.printf(" {\"%s\"}\n", e.getMessage()); + } + + try { + System.out.print("testClient.testException(\"success\") =>"); + testClient.testException("success"); + System.out.print(" void\n"); + }catch(Exception e) { + System.out.printf(" exception\n*** FAILURE ***\n"); + returnCode |= ERR_EXCEPTIONS; + } + + + /** + * 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) { + System.out.printf(" {%d, \"%s\"}\n", e.errorCode, e.message); + } + + try { + System.out.printf("testClient.testMultiException(\"Xception2\", \"test 2\") =>"); + testClient.testMultiException("Xception2", "test 2"); + System.out.print(" result\n*** FAILURE ***\n"); + returnCode |= ERR_EXCEPTIONS; + } catch(Xception2 e) { + System.out.printf(" {%d, {\"%s\"}}\n", e.errorCode, e.struct_thing.string_thing); + } + + try { + System.out.print("testClient.testMultiException(\"success\", \"test 3\") =>"); + Xtruct result; + result = testClient.testMultiException("success", "test 3"); + System.out.printf(" {{\"%s\"}}\n", result.string_thing); + } catch(Exception e) { + System.out.printf(" exception\n*** FAILURE ***\n"); + returnCode |= ERR_EXCEPTIONS; + } + + + + /** + * 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 " + + Long.toString(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("before executing the RPC."); + System.out.println("*** FAILURE ***"); + returnCode |= ERR_BASETYPES; + } else { + System.out.println("Success - fire and forget only took " + + Long.toString(onewayElapsedMillis) + + "ms"); + } + + + long stop = System.nanoTime(); + long tot = stop-start; + + System.out.println("Total time: " + tot/1000 + "us"); + + if (timeMin == 0 || tot < timeMin) { + timeMin = tot; + } + if (tot > timeMax) { + timeMax = tot; + } + timeTot += tot; + + transport.close(); + } catch (Exception x) { + System.out.printf("*** FAILURE ***\n"); + x.printStackTrace(); + returnCode |= ERR_UNKNOWN; + } + } + + 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"); + + try { + String json = (new TSerializer(new TSimpleJSONProtocol.Factory())).toString(insane); + System.out.println("\nSample TSimpleJSONProtocol output:\n" + json); + } catch (TException x) { + System.out.println("*** FAILURE ***"); + x.printStackTrace(); + returnCode |= ERR_BASETYPES; + } + + + System.exit(returnCode); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestNonblockingServer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestNonblockingServer.java new file mode 100644 index 000000000..41c4b6500 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestNonblockingServer.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.test; + +import org.apache.thrift.server.THsHaServer; +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) { + try { + int port = 9090; + boolean hsha = false; + + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-p")) { + port = Integer.valueOf(args[i++]); + } else if (args[i].equals("-hsha")) { + hsha = true; + } + } + //@TODO add other protocol and transport types + + // Processor + TestHandler testHandler = + new TestHandler(); + ThriftTest.Processor testProcessor = + new ThriftTest.Processor(testHandler); + + // Transport + TNonblockingServerSocket tServerSocket = + new TNonblockingServerSocket(new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(port)); + + TServer serverEngine; + + if (hsha) { + // HsHa Server + serverEngine = new THsHaServer(new Args(tServerSocket).processor(testProcessor)); + } else { + // Nonblocking Server + serverEngine = new TNonblockingServer(new Args(tServerSocket).processor(testProcessor)); + } + + // Run it + System.out.println("Starting the server on port " + port + "..."); + serverEngine.serve(); + + } catch (Exception x) { + x.printStackTrace(); + } + System.out.println("done."); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestServer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestServer.java new file mode 100644 index 000000000..1f3e555d9 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/TestServer.java @@ -0,0 +1,310 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +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.protocol.TMultiplexedProtocol; +import org.apache.thrift.server.ServerContext; +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TServer.Args; +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.TFramedTransport; +import org.apache.thrift.transport.TFastFramedTransport; +import org.apache.thrift.transport.TServerSocket; +import org.apache.thrift.transport.TSSLTransportFactory; +import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportFactory; +import org.apache.thrift.transport.TNonblockingServerSocket; +import org.apache.thrift.TMultiplexedProcessor; + +import thrift.test.Insanity; +import thrift.test.Numberz; +import thrift.test.SecondService; +import thrift.test.ThriftTest; +import thrift.test.Xception; +import thrift.test.Xception2; +import thrift.test.Xtruct; +import thrift.test.Xtruct2; + +public class TestServer { + + // Multiplexed Protocol Support Details: + // + // For multiplexed testing we always use binary protocol underneath. + // + // "ThriftTest" named service implements "ThriftTest" from ThriftTest.thrift + // "SecondService" named service implements "SecondService" from ThriftTest.thrift + // In addition, to support older non-multiplexed clients using the same concrete protocol + // the multiplexed processor is taught to use "ThriftTest" if the incoming request has no + // multiplexed call name decoration. + + 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 + "\")"; } + + } + + static class TestServerContext implements ServerContext { + + int connectionId; + + public TestServerContext(int connectionId) { + this.connectionId = connectionId; + } + + public int getConnectionId() { + return connectionId; + } + + public void setConnectionId(int connectionId) { + this.connectionId = connectionId; + } + + } + + static class TestServerEventHandler implements TServerEventHandler { + + 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 deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) { + TestServerContext ctx = (TestServerContext)serverContext; + System.out.println("TServerEventHandler.deleteContext - connection #"+ctx.getConnectionId()+" terminated"); + } + + public void processContext(ServerContext serverContext, TTransport inputTransport, TTransport outputTransport) { + TestServerContext ctx = (TestServerContext)serverContext; + System.out.println("TServerEventHandler.processContext - connection #"+ctx.getConnectionId()+" is ready to process next request"); + } + + } + + public static void main(String [] args) { + try { + int port = 9090; + boolean ssl = false; + String transport_type = "buffered"; + String protocol_type = "binary"; + String server_type = "thread-pool"; + String domain_socket = ""; + int string_limit = -1; + int container_limit = -1; + try { + for (int i = 0; i < args.length; i++) { + if (args[i].startsWith("--port")) { + port = Integer.valueOf(args[i].split("=")[1]); + } else if (args[i].startsWith("--server-type")) { + server_type = args[i].split("=")[1]; + server_type.trim(); + } else if (args[i].startsWith("--port")) { + port=Integer.parseInt(args[i].split("=")[1]); + } else if (args[i].startsWith("--protocol")) { + protocol_type = args[i].split("=")[1]; + protocol_type.trim(); + } else if (args[i].startsWith("--transport")) { + transport_type = args[i].split("=")[1]; + transport_type.trim(); + } else if (args[i].equals("--ssl")) { + ssl = true; + } else if (args[i].startsWith("--string-limit")) { + string_limit = Integer.valueOf(args[i].split("=")[1]); + } else if (args[i].startsWith("--container-limit")) { + container_limit = Integer.valueOf(args[i].split("=")[1]); + } else if (args[i].equals("--help")) { + 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"); + 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(" --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); + } + } + } catch (Exception e) { + System.err.println("Can not parse arguments! See --help"); + System.exit(1); + } + + try { + if (server_type.equals("simple")) { + } else if (server_type.equals("thread-pool")) { + } else if (server_type.equals("nonblocking")) { + if (ssl == true) { + throw new Exception("SSL is not supported over nonblocking servers!"); + } + } else if (server_type.equals("threaded-selector")) { + if (ssl == true) { + throw new Exception("SSL is not supported over nonblocking servers!"); + } + } else { + throw new Exception("Unknown server type! " + server_type); + } + if (protocol_type.equals("binary")) { + } else if (protocol_type.equals("compact")) { + } else if (protocol_type.equals("json")) { + } else if (protocol_type.equals("multi")) { + } else if (protocol_type.equals("multic")) { + } else if (protocol_type.equals("multij")) { + } else { + throw new Exception("Unknown protocol type! " + protocol_type); + } + if (transport_type.equals("buffered")) { + } else if (transport_type.equals("framed")) { + } else if (transport_type.equals("fastframed")) { + } else { + throw new Exception("Unknown transport type! " + transport_type); + } + } catch (Exception e) { + System.err.println("Error: " + e.getMessage()); + System.exit(1); + } + + // Processors + TestHandler testHandler = new TestHandler(); + ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); + + SecondHandler secondHandler = new SecondHandler(); + SecondService.Processor secondProcessor = new SecondService.Processor(secondHandler); + + // Protocol factory + TProtocolFactory tProtocolFactory = null; + if (protocol_type.equals("json") || protocol_type.equals("multij")) { + tProtocolFactory = new TJSONProtocol.Factory(); + } else if (protocol_type.equals("compact") || protocol_type.equals("multic")) { + tProtocolFactory = new TCompactProtocol.Factory(string_limit, container_limit); + } else { // also covers multi + tProtocolFactory = new TBinaryProtocol.Factory(string_limit, container_limit); + } + + TTransportFactory tTransportFactory = null; + + if (transport_type.equals("framed")) { + tTransportFactory = new TFramedTransport.Factory(); + } else if (transport_type.equals("fastframed")) { + tTransportFactory = new TFastFramedTransport.Factory(); + } else { // .equals("buffered") => default value + tTransportFactory = new TTransportFactory(); + } + + TServer serverEngine = null; + + // If we are multiplexing services in one server... + TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor(); + multiplexedProcessor.registerDefault (testProcessor); + multiplexedProcessor.registerProcessor("ThriftTest", testProcessor); + multiplexedProcessor.registerProcessor("SecondService", secondProcessor); + + if (server_type.equals("nonblocking") || + server_type.equals("threaded-selector")) { + // Nonblocking servers + TNonblockingServerSocket tNonblockingServerSocket = + 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); + 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); + tThreadedSelectorServerArgs.protocolFactory(tProtocolFactory); + tThreadedSelectorServerArgs.transportFactory(tTransportFactory); + serverEngine = new TThreadedSelectorServer(tThreadedSelectorServerArgs); + } + } else { + // Blocking servers + + // SSL socket + TServerSocket tServerSocket = null; + if (ssl) { + tServerSocket = TSSLTransportFactory.getServerSocket(port, 0); + } else { + 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.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); + tThreadPoolServerArgs.protocolFactory(tProtocolFactory); + tThreadPoolServerArgs.transportFactory(tTransportFactory); + serverEngine = new TThreadPoolServer(tThreadPoolServerArgs); + } + } + + // Set server event handler + 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))); + serverEngine.serve(); + + } catch (Exception x) { + x.printStackTrace(); + } + System.out.println("done."); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/WriteStruct.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/WriteStruct.java new file mode 100644 index 000000000..a0013a93a --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/test/WriteStruct.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.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; +import org.apache.thrift.transport.TIOStreamTransport; +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'."); + } + + TTransport trans = new TIOStreamTransport(new BufferedOutputStream(new FileOutputStream(args[0]))); + + TProtocolFactory factory = (TProtocolFactory)Class.forName(args[1]).newInstance(); + + TProtocol proto = factory.getProtocol(trans); + + Fixtures.compactProtoTestStruct.write(proto); + trans.flush(); + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/ReadCountingTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/ReadCountingTransport.java new file mode 100644 index 000000000..3c749f9fb --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/ReadCountingTransport.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + + +public class ReadCountingTransport extends TTransport { + public int readCount = 0; + private TTransport trans; + private boolean open = true; + + public ReadCountingTransport(TTransport underlying) { + trans = underlying; + } + + @Override + public void close() { + open = false; + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void open() throws TTransportException { + open = true; + } + + @Override + public int read(byte[] buf, int off, int len) throws TTransportException { + if (!isOpen()) { + throw new TTransportException(TTransportException.NOT_OPEN, "Transport is closed"); + } + readCount++; + return trans.read(buf, off, len); + } + + @Override + public void write(byte[] buf, int off, int len) throws TTransportException { + if (!isOpen()) { + throw new TTransportException(TTransportException.NOT_OPEN, "Transport is closed"); + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBuffer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBuffer.java new file mode 100644 index 000000000..c35348953 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBuffer.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +import junit.framework.TestCase; + +public class TestAutoExpandingBuffer extends TestCase { + public void testExpands() throws Exception { + // has expected initial capacity + AutoExpandingBuffer b = new AutoExpandingBuffer(10); + assertEquals(10, b.array().length); + + // doesn't shrink + b.resizeIfNecessary(8); + assertEquals(10, b.array().length); + + // grows when more capacity is needed + b.resizeIfNecessary(100); + assertTrue(b.array().length >= 100); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java new file mode 100644 index 000000000..83ebc2d4c --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +import java.nio.ByteBuffer; + +import junit.framework.TestCase; + +public class TestAutoExpandingBufferReadTransport extends TestCase { + private static final byte[] HUNDRED_BYTES = new byte[100]; + + static { + for (byte i = 0; i < 100; i++) { + HUNDRED_BYTES[i] = i; + } + } + + public void testIt() throws Exception { + AutoExpandingBufferReadTransport t = new AutoExpandingBufferReadTransport(150); + + TMemoryInputTransport membuf = new TMemoryInputTransport(HUNDRED_BYTES); + + t.fill(membuf, 100); + assertEquals(100, t.getBytesRemainingInBuffer()); + assertEquals(0, t.getBufferPosition()); + + byte[] target = new byte[10]; + assertEquals(10, t.read(target, 0, 10)); + assertEquals(ByteBuffer.wrap(HUNDRED_BYTES, 0, 10), ByteBuffer.wrap(target)); + + assertEquals(90, t.getBytesRemainingInBuffer()); + assertEquals(10, t.getBufferPosition()); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java new file mode 100644 index 000000000..86b5b0d0f --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +import java.nio.ByteBuffer; +import org.junit.Test; +import static org.junit.Assert.*; + +public class TestAutoExpandingBufferWriteTransport { + + @Test + public void testIt() throws Exception { + AutoExpandingBufferWriteTransport t = new AutoExpandingBufferWriteTransport(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)); + + AutoExpandingBufferWriteTransport uut = new AutoExpandingBufferWriteTransport(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(expected = IllegalArgumentException.class) + public void testBadInitialSize() throws IllegalArgumentException { + new AutoExpandingBufferWriteTransport(0, 0); + } + + @Test(expected = IllegalArgumentException.class) + public void testBadFrontReserveSize() throws IllegalArgumentException { + new AutoExpandingBufferWriteTransport(4, -1); + } + + @Test(expected = IllegalArgumentException.class) + public void testTooSmallFrontReserveSize() throws IllegalArgumentException { + new AutoExpandingBufferWriteTransport(4, 5); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTByteBuffer.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTByteBuffer.java new file mode 100644 index 000000000..bdc0a848a --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTByteBuffer.java @@ -0,0 +1,36 @@ +package org.apache.thrift.transport; + +import junit.framework.TestCase; +import java.nio.charset.StandardCharsets; +import org.apache.thrift.TException; + +import java.nio.ByteBuffer; + +public class TestTByteBuffer extends TestCase { + 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)); + } + + 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)); + + byteBuffer.clear(); + + byteBuffer.write("Goodbye Horses".getBytes(StandardCharsets.UTF_8)); + assertEquals("Goodbye Horses", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); + } + + public void testOverflow() throws Exception { + final TByteBuffer byteBuffer = new TByteBuffer(ByteBuffer.allocate(4)); + try { + byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8)); + fail("Expected write operation to fail with TTransportException"); + } catch (TTransportException e) { + assertEquals("Not enough room in output buffer", e.getMessage()); + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTFastFramedTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTFastFramedTransport.java new file mode 100644 index 000000000..06ee20666 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTFastFramedTransport.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +public class TestTFastFramedTransport extends TestTFramedTransport { + protected final static int INITIAL_CAPACITY = 50; + + @Override + protected TTransport getTransport(TTransport underlying) { + return new TFastFramedTransport(underlying, INITIAL_CAPACITY, 10 * 1024 * 1024); + } + + @Override + protected TTransport getTransport(TTransport underlying, int maxLength) { + return new TFastFramedTransport(underlying, INITIAL_CAPACITY, maxLength); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTFramedTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTFramedTransport.java new file mode 100644 index 000000000..e30d74b07 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTFramedTransport.java @@ -0,0 +1,214 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Arrays; + +import junit.framework.TestCase; + +public class TestTFramedTransport extends TestCase { + + protected TTransport getTransport(TTransport underlying) { + return new TFramedTransport(underlying); + } + + protected TTransport getTransport(TTransport underlying, int maxLength) { + 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); + } + return result; + } + + public void testRead() throws IOException, TTransportException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(50); + dos.write(byteSequence(0, 49)); + + dos.writeInt(220); + dos.write(byteSequence(0, 219)); + + TMemoryBuffer membuf = new TMemoryBuffer(0); + membuf.write(baos.toByteArray()); + + ReadCountingTransport countTrans = new ReadCountingTransport(membuf); + TTransport trans = getTransport(countTrans); + + byte[] readBuf = new byte[10]; + trans.read(readBuf, 0, 10); + assertTrue(Arrays.equals(readBuf, byteSequence(0,9))); + assertEquals(2, countTrans.readCount); + + trans.read(readBuf, 0, 10); + assertTrue(Arrays.equals(readBuf, byteSequence(10,19))); + assertEquals(2, countTrans.readCount); + + assertEquals(30, trans.read(new byte[30], 0, 30)); + assertEquals(2, countTrans.readCount); + + readBuf = new byte[220]; + assertEquals(220, trans.read(readBuf, 0, 220)); + assertTrue(Arrays.equals(readBuf, byteSequence(0, 219))); + assertEquals(4, countTrans.readCount); + } + + public void testInvalidFrameSize() throws IOException, TTransportException { + int maxLength = 128; + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(130); + dos.write(byteSequence(0, 129)); + + TMemoryBuffer membuf = new TMemoryBuffer(0); + membuf.write(baos.toByteArray()); + + ReadCountingTransport countTrans = new ReadCountingTransport(membuf); + TTransport trans = getTransport(countTrans, maxLength); + + byte[] readBuf = new byte[10]; + try { + trans.read(readBuf, 0, 4); + fail("Expected a TTransportException"); + } catch (TTransportException e) { + // 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()); + + try { + trans.read(readBuf, 0, 4); + fail("Expected a TTransportException"); + } catch (TTransportException e) { + // This time we get an exception indicating the connection was closed + assertEquals(TTransportException.NOT_OPEN, e.getType()); + } + } + + public void testWrite() throws TTransportException, IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); + TTransport trans = getTransport(countingTrans); + + trans.write(byteSequence(0,100)); + assertEquals(0, countingTrans.writeCount); + trans.write(byteSequence(101,200)); + trans.write(byteSequence(201,255)); + assertEquals(0, countingTrans.writeCount); + + trans.flush(); + assertEquals(1, countingTrans.writeCount); + + trans.write(byteSequence(0, 245)); + trans.flush(); + assertEquals(2, countingTrans.writeCount); + + DataInputStream din = new DataInputStream(new ByteArrayInputStream(baos.toByteArray())); + assertEquals(256, din.readInt()); + + byte[] buf = new byte[256]; + din.read(buf, 0, 256); + assertTrue(Arrays.equals(byteSequence(0,255), buf)); + + assertEquals(246, din.readInt()); + buf = new byte[246]; + din.read(buf, 0, 246); + assertTrue(Arrays.equals(byteSequence(0,245), buf)); + } + + public void testDirectRead() throws IOException, TTransportException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(50); + dos.write(byteSequence(0, 49)); + dos.writeInt(75); + dos.write(byteSequence(125, 200)); + + TMemoryBuffer membuf = new TMemoryBuffer(0); + membuf.write(baos.toByteArray()); + + ReadCountingTransport countTrans = new ReadCountingTransport(membuf); + TTransport trans = getTransport(countTrans); + + assertEquals(0, trans.getBytesRemainingInBuffer()); + + byte[] readBuf = new byte[10]; + trans.read(readBuf, 0, 10); + assertTrue(Arrays.equals(readBuf, byteSequence(0,9))); + + assertEquals(40, trans.getBytesRemainingInBuffer()); + assertEquals(10, trans.getBufferPosition()); + + trans.consumeBuffer(5); + assertEquals(35, trans.getBytesRemainingInBuffer()); + assertEquals(15, trans.getBufferPosition()); + + assertEquals(2, countTrans.readCount); + + assertEquals(35, trans.read(new byte[35], 0, 35)); + assertEquals(0, trans.getBytesRemainingInBuffer()); + assertEquals(50, trans.getBufferPosition()); + + trans.read(readBuf, 0, 10); + assertEquals(4, countTrans.readCount); + assertTrue(Arrays.equals(readBuf, byteSequence(125,134))); + assertEquals(65, trans.getBytesRemainingInBuffer()); + assertEquals(10, trans.getBufferPosition()); + } + + public void testClear() throws IOException, TTransportException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(220); + dos.write(byteSequence(0, 219)); + + TMemoryBuffer membuf = new TMemoryBuffer(0); + membuf.write(baos.toByteArray()); + + ReadCountingTransport countTrans = new ReadCountingTransport(membuf); + TTransport trans = getTransport(countTrans); + + byte[] readBuf = new byte[220]; + trans.read(readBuf, 0, 220); + assertTrue(Arrays.equals(readBuf, byteSequence(0,219))); + + assertTrue(trans instanceof TFramedTransport || trans instanceof TFastFramedTransport); + if (trans instanceof TFramedTransport) { + assertTrue(trans.getBuffer() != null && trans.getBuffer().length > 0); + ((TFramedTransport) trans).clear(); + assertTrue(trans.getBuffer() == null); + } else if (trans instanceof TFastFramedTransport) { + assertTrue(trans.getBuffer().length > TestTFastFramedTransport.INITIAL_CAPACITY); + ((TFastFramedTransport) trans).clear(); + assertTrue(trans.getBuffer().length == TestTFastFramedTransport.INITIAL_CAPACITY); + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTMemoryInputTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTMemoryInputTransport.java new file mode 100644 index 000000000..273145bd2 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTMemoryInputTransport.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +import java.util.Arrays; + +import junit.framework.TestCase; + +public class TestTMemoryInputTransport extends TestCase { + public void testFresh() throws Exception { + 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[] buf1 = new byte[4]; + trans.readAll(buf1, 0, 4); + assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); + assertEquals(4, trans.getBufferPosition()); + assertEquals(6, trans.getBytesRemainingInBuffer()); + + trans.consumeBuffer(2); + + assertEquals(6, trans.getBufferPosition()); + assertEquals(4, trans.getBytesRemainingInBuffer()); + + trans.readAll(buf1, 0, 4); + assertTrue(Arrays.equals(new byte[]{7, 8, 9, 10}, buf1)); + assertEquals(10, trans.getBufferPosition()); + assertEquals(0, trans.getBytesRemainingInBuffer()); + } + + public void testReused() throws Exception { + 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}; + trans.reset(new_buf); + assertEquals(0, trans.getBufferPosition()); + assertEquals(new_buf, trans.getBuffer()); + assertEquals(3, trans.getBytesRemainingInBuffer()); + } + + public void testWithOffsetAndLength() throws Exception { + 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()); + byte[] readBuffer = new byte[3]; + trans.readAll(readBuffer, 0, 3); + assertTrue(Arrays.equals(new byte[]{2, 3, 4}, readBuffer)); + + try { + assertEquals(0, trans.readAll(readBuffer, 0, 3)); + fail("should have thrown an exception"); + } catch (Exception e) { + // yay + } + + trans.reset(input_buf, 3, 4); + readBuffer = new byte[4]; + trans.readAll(readBuffer, 0, 4); + assertTrue(Arrays.equals(new byte[]{4, 5, 6, 7}, readBuffer)); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactory.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactory.java new file mode 100644 index 000000000..032c2eb71 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactory.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.transport; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocolFactory; +import org.apache.thrift.server.ServerTestBase; +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TSimpleServer; +import org.apache.thrift.server.TServer.Args; + +public class TestTSSLTransportFactory extends ServerTestBase { + private Thread serverThread; + private TServer server; + + private static final List<TProtocolFactory> protocols = new ArrayList<TProtocolFactory>(); + static { + // TODO: Only supported on TBinaryProtocol. Doesn't work for TCompactProtocol + protocols.add(new TBinaryProtocol.Factory()); + } + + @Override + public TTransport getClientTransport(TTransport underlyingTransport) + throws Exception { + return TSSLTransportFactory.getClientSocket(HOST, PORT); + } + + protected TServerSocket getServerTransport() throws Exception { + return TSSLTransportFactory.getServerSocket(PORT); + } + + @Override + public void startServer(final TProcessor processor, final TProtocolFactory protoFactory, final TTransportFactory factory) + throws Exception { + serverThread = new Thread() { + public void run() { + 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); + } + + @Override + public void stopServer() throws Exception { + server.stop(); + serverThread.join(); + } + + @Override + public void open(TTransport transport) throws Exception {} + + @Override + public List<TProtocolFactory> getProtocols() { + return protocols; + } + + @Override + public void testTransportFactory() throws Exception { + // this test doesn't really apply to this suite, so let's skip it. + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java new file mode 100644 index 000000000..da1659f9d --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.transport; + +public class TestTSSLTransportFactoryCustomClient1 extends TestTSSLTransportFactory { + + @Override + public TTransport getClientTransport(TTransport underlyingTransport) + throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = new + TSSLTransportFactory.TSSLTransportParameters(); + + params.setTrustStore(System.getProperty("javax.net.ssl.trustStore"), + System.getProperty("javax.net.ssl.trustStorePassword")); + + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java new file mode 100644 index 000000000..eaed46057 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.transport; + +public class TestTSSLTransportFactoryCustomClient2 extends TestTSSLTransportFactory { + + @Override + public TTransport getClientTransport(TTransport underlyingTransport) + throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = new + TSSLTransportFactory.TSSLTransportParameters(); + + params.setTrustStore(System.getProperty("javax.net.ssl.trustStore"), null); + + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java new file mode 100644 index 000000000..25bf5cebb --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.transport; + +import java.io.FileInputStream; +import java.net.InetAddress; + +public class TestTSSLTransportFactoryStreamedStore extends TestTSSLTransportFactory { + private static String keyStoreLocation = System.getProperty("javax.net.ssl.keyStore"); + private static String trustStoreLocation = System.getProperty("javax.net.ssl.trustStore"); + + public TestTSSLTransportFactoryStreamedStore() { + super(); + + /** + * Override system properties to be able to test passing + * the trustStore and keyStore as input stream + */ + System.setProperty("javax.net.ssl.trustStore", ""); + System.setProperty("javax.net.ssl.keyStore", ""); + } + + @Override + public TTransport getClientTransport(TTransport underlyingTransport) + throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = new + TSSLTransportFactory.TSSLTransportParameters(); + + params.setTrustStore(new FileInputStream(trustStoreLocation), + System.getProperty("javax.net.ssl.trustStorePassword")); + + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); + } + + @Override + protected TServerSocket getServerTransport() throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = new + TSSLTransportFactory.TSSLTransportParameters(); + + params.setKeyStore(new FileInputStream(keyStoreLocation), + System.getProperty("javax.net.ssl.keyStorePassword")); + + return TSSLTransportFactory.getServerSocket(PORT, 0/*timeout*/, InetAddress.getByName(HOST), params); + } +}
\ No newline at end of file diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSaslTransports.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSaslTransports.java new file mode 100644 index 000000000..36a06e9e5 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSaslTransports.java @@ -0,0 +1,471 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.thrift.transport; + +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; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.AuthorizeCallback; +import javax.security.sasl.RealmCallback; +import javax.security.sasl.Sasl; +import javax.security.sasl.SaslClient; +import javax.security.sasl.SaslClientFactory; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import javax.security.sasl.SaslServerFactory; + +import junit.framework.TestCase; + +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.TSimpleServer; +import org.apache.thrift.server.TServer.Args; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestTSaslTransports extends TestCase { + + private static final Logger LOGGER = LoggerFactory.getLogger(TestTSaslTransports.class); + + private static final String HOST = "localhost"; + private static final String SERVICE = "thrift-test"; + private static final String PRINCIPAL = "thrift-test-principal"; + private static final String PASSWORD = "super secret password"; + private static final String REALM = "thrift-test-realm"; + + private static final String UNWRAPPED_MECHANISM = "CRAM-MD5"; + private static final Map<String, String> UNWRAPPED_PROPS = null; + + private static final String WRAPPED_MECHANISM = "DIGEST-MD5"; + private static final Map<String, String> WRAPPED_PROPS = new HashMap<String, String>(); + + static { + WRAPPED_PROPS.put(Sasl.QOP, "auth-int"); + 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 class TestSaslCallbackHandler implements CallbackHandler { + private final String password; + + public TestSaslCallbackHandler(String password) { + this.password = password; + } + + @Override + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + for (Callback c : callbacks) { + if (c instanceof NameCallback) { + ((NameCallback) c).setName(PRINCIPAL); + } else if (c instanceof PasswordCallback) { + ((PasswordCallback) c).setPassword(password.toCharArray()); + } else if (c instanceof AuthorizeCallback) { + ((AuthorizeCallback) c).setAuthorized(true); + } else if (c instanceof RealmCallback) { + ((RealmCallback) c).setText(REALM); + } else { + throw new UnsupportedCallbackException(c); + } + } + } + } + + private class ServerThread extends Thread { + final String mechanism; + final Map<String, String> props; + volatile Throwable thrown; + + public ServerThread(String mechanism, Map<String, String> props) { + this.mechanism = mechanism; + this.props = props; + } + + public void run() { + try { + internalRun(); + } catch (Throwable t) { + thrown = t; + } + } + + private void internalRun() throws Exception { + TServerSocket serverSocket = new TServerSocket( + new TServerSocket.ServerSocketTransportArgs(). + port(ServerTestBase.PORT)); + try { + acceptAndWrite(serverSocket); + } finally { + serverSocket.close(); + } + } + + private void acceptAndWrite(TServerSocket serverSocket) + throws Exception { + TTransport serverTransport = serverSocket.accept(); + TTransport saslServerTransport = new TSaslServerTransport( + mechanism, SERVICE, HOST, + props, new TestSaslCallbackHandler(PASSWORD), serverTransport); + + saslServerTransport.open(); + + byte[] inBuf = new byte[testMessage1.getBytes().length]; + // Deliberately read less than the full buffer to ensure + // that TSaslTransport is correctly buffering reads. This + // will fail for the WRAPPED test, if it doesn't work. + saslServerTransport.readAll(inBuf, 0, 5); + saslServerTransport.readAll(inBuf, 5, 10); + saslServerTransport.readAll(inBuf, 15, inBuf.length - 15); + LOGGER.debug("server got: {}", new String(inBuf)); + assertEquals(new String(inBuf), testMessage1); + + LOGGER.debug("server writing: {}", testMessage2); + saslServerTransport.write(testMessage2.getBytes()); + saslServerTransport.flush(); + + saslServerTransport.close(); + } + } + + private void testSaslOpen(final String mechanism, final Map<String, String> props) + throws Exception { + ServerThread serverThread = new ServerThread(mechanism, props); + serverThread.start(); + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // Ah well. + } + + try { + TSocket clientSocket = new TSocket(HOST, ServerTestBase.PORT); + TTransport saslClientTransport = new TSaslClientTransport(mechanism, + PRINCIPAL, SERVICE, HOST, props, new TestSaslCallbackHandler(PASSWORD), clientSocket); + saslClientTransport.open(); + LOGGER.debug("client writing: {}", testMessage1); + saslClientTransport.write(testMessage1.getBytes()); + saslClientTransport.flush(); + + byte[] inBuf = new byte[testMessage2.getBytes().length]; + saslClientTransport.readAll(inBuf, 0, inBuf.length); + LOGGER.debug("client got: {}", new String(inBuf)); + assertEquals(new String(inBuf), testMessage2); + + TTransportException expectedException = null; + try { + saslClientTransport.open(); + } catch (TTransportException e) { + expectedException = e; + } + assertNotNull(expectedException); + + saslClientTransport.close(); + } catch (Exception e) { + LOGGER.warn("Exception caught", e); + throw e; + } finally { + serverThread.interrupt(); + try { + serverThread.join(); + } catch (InterruptedException e) { + // Ah well. + } + assertNull(serverThread.thrown); + } + } + + public void testUnwrappedOpen() throws Exception { + testSaslOpen(UNWRAPPED_MECHANISM, UNWRAPPED_PROPS); + } + + public void testWrappedOpen() throws Exception { + testSaslOpen(WRAPPED_MECHANISM, WRAPPED_PROPS); + } + + public void testAnonymousOpen() throws Exception { + testSaslOpen("ANONYMOUS", null); + } + + /** + * Test that we get the proper exceptions thrown back the server when + * the client provides invalid password. + */ + public void testBadPassword() throws Exception { + ServerThread serverThread = new ServerThread(UNWRAPPED_MECHANISM, UNWRAPPED_PROPS); + serverThread.start(); + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // Ah well. + } + + boolean clientSidePassed = true; + + try { + 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(); + clientSidePassed = false; + fail("Was able to open transport with bad password"); + } catch (TTransportException tte) { + LOGGER.error("Exception for bad password", tte); + assertNotNull(tte.getMessage()); + assertTrue(tte.getMessage().contains("Invalid response")); + + } finally { + serverThread.interrupt(); + serverThread.join(); + + if (clientSidePassed) { + assertNotNull(serverThread.thrown); + assertTrue(serverThread.thrown.getMessage().contains("Invalid response")); + } + } + } + + public void testWithServer() throws Exception { + new TestTSaslTransportsWithServer().testIt(); + } + + private static class TestTSaslTransportsWithServer extends ServerTestBase { + + private Thread serverThread; + private TServer server; + + @Override + public TTransport getClientTransport(TTransport underlyingTransport) throws Exception { + return new TSaslClientTransport( + 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(); + } + } + }; + serverThread.start(); + Thread.sleep(1000); + } + + @Override + public void stopServer() throws Exception { + server.stop(); + try { + serverThread.join(); + } catch (InterruptedException e) {} + } + + } + + + /** + * Implementation of SASL ANONYMOUS, used for testing client-side + * initial responses. + */ + private static class AnonymousClient implements SaslClient { + private final String username; + private boolean hasProvidedInitialResponse; + + public AnonymousClient(String username) { + this.username = username; + } + + public String getMechanismName() { return "ANONYMOUS"; } + public boolean hasInitialResponse() { return true; } + public byte[] evaluateChallenge(byte[] challenge) throws SaslException { + if (hasProvidedInitialResponse) { + throw new SaslException("Already complete!"); + } + + hasProvidedInitialResponse = true; + return username.getBytes(StandardCharsets.UTF_8); + } + public boolean isComplete() { return hasProvidedInitialResponse; } + public byte[] unwrap(byte[] incoming, int offset, int len) { + throw new UnsupportedOperationException(); + } + public byte[] wrap(byte[] outgoing, int offset, int len) { + throw new UnsupportedOperationException(); + } + public Object getNegotiatedProperty(String propName) { return null; } + public void dispose() {} + } + + private static class AnonymousServer implements SaslServer { + private String user; + public String getMechanismName() { return "ANONYMOUS"; } + public byte[] evaluateResponse(byte[] response) throws SaslException { + this.user = new String(response, StandardCharsets.UTF_8); + return null; + } + public boolean isComplete() { return user != null; } + public String getAuthorizationID() { return user; } + public byte[] unwrap(byte[] incoming, int offset, int len) { + throw new UnsupportedOperationException(); + } + public byte[] wrap(byte[] outgoing, int offset, int len) { + throw new UnsupportedOperationException(); + } + public Object getNegotiatedProperty(String propName) { return null; } + public void dispose() {} + + } + + public static class SaslAnonymousFactory + implements SaslClientFactory, SaslServerFactory { + + public SaslClient createSaslClient( + 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); + } + } + return null; + } + + public SaslServer createSaslServer( + String mechanism, String protocol, String serverName, Map<String,?> props, CallbackHandler cbh) + { + if ("ANONYMOUS".equals(mechanism)) { + return new AnonymousServer(); + } + return null; + } + public String[] getMechanismNames(Map<String, ?> props) { + 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"); + put("SaslClientFactory.ANONYMOUS", SaslAnonymousFactory.class.getName()); + put("SaslServerFactory.ANONYMOUS", SaslAnonymousFactory.class.getName()); + } + } + + private static class MockTTransport extends TTransport { + + byte[] badHeader = null; + private TMemoryInputTransport readBuffer = new TMemoryInputTransport(); + + public MockTTransport(int mode) { + if (mode==1) { + // Invalid status byte + 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 }; + } 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 }; + } + readBuffer.reset(badHeader); + } + + @Override + public boolean isOpen() { + return true; + } + + @Override + public void open() throws TTransportException {} + + @Override + public void close() {} + + @Override + public int read(byte[] buf, int off, int len) throws TTransportException { + return readBuffer.read(buf, off, len); + } + + @Override + public void write(byte[] buf, int off, int len) throws TTransportException {} + } + + public void testBadHeader() { + TSaslTransport saslTransport = new TSaslServerTransport(new MockTTransport(1)); + try { + saslTransport.receiveSaslMessage(); + fail("Should have gotten an error due to incorrect status byte value."); + } catch (TTransportException e) { + assertEquals(e.getMessage(), "Invalid status -1"); + } + saslTransport = new TSaslServerTransport(new MockTTransport(2)); + try { + saslTransport.receiveSaslMessage(); + fail("Should have gotten an error due to negative payload length."); + } catch (TTransportException e) { + assertEquals(e.getMessage(), "Invalid payload header length: -1"); + } + saslTransport = new TSaslServerTransport(new MockTTransport(3)); + try { + saslTransport.receiveSaslMessage(); + fail("Should have gotten an error due to bogus (large) payload length."); + } catch (TTransportException e) { + assertEquals(e.getMessage(), "Invalid payload header length: 1677721600"); + } + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSimpleFileTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSimpleFileTransport.java new file mode 100644 index 000000000..7b880f499 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTSimpleFileTransport.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import junit.framework.TestCase; + +public class TestTSimpleFileTransport extends TestCase { + public void testFresh() throws Exception { + //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); + assert (!trans_write.isOpen()); + trans_write.open(); + assert(trans_write.isOpen()); + trans_write.write(input_buf); + 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()); + + //Simple file trans provides no buffer access + assert(0 == trans.getBufferPosition()); + assert(null == trans.getBuffer()); + assert(-1 == trans.getBytesRemainingInBuffer()); + + //Test file pointer operations + assert(0 == trans.getFilePointer()); + assert(12 == trans.length()); + + final int BUFSIZ = 4; + byte[] buf1 = new byte[BUFSIZ]; + trans.readAll(buf1, 0, BUFSIZ); + assert(BUFSIZ == trans.getFilePointer()); + assert(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); + + int bytesRead = trans.read(buf1, 0, BUFSIZ); + assert(bytesRead > 0); + for (int i = 0; i < bytesRead; ++i) { + assert(buf1[i] == i+5); + } + + trans.seek(0); + assert(0 == trans.getFilePointer()); + trans.readAll(buf1, 0, BUFSIZ); + assert(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); + assert(BUFSIZ == trans.getFilePointer()); + trans.close(); + Files.delete(tempFilePathName); + } +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTZlibTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTZlibTransport.java new file mode 100644 index 000000000..3d7f9c1c9 --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/TestTZlibTransport.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.zip.DataFormatException; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.InflaterInputStream; + +import junit.framework.TestCase; + +public class TestTZlibTransport extends TestCase { + + protected TTransport getTransport(TTransport underlying) { + 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); + } + return result; + } + + public void testClose() throws TTransportException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream + (baos))); + TTransport trans = getTransport(countingTrans); + trans.write(byteSequence(0, 245)); + countingTrans.close(); + trans.close(); + } + + public void testCloseOpen() throws TTransportException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + TTransport trans = getTransport(new TIOStreamTransport(baos)); + byte[] uncompressed = byteSequence(0, 245); + trans.write(uncompressed); + trans.close(); + final byte[] compressed = baos.toByteArray(); + + final byte[] buf = new byte[255]; + TTransport transRead = getTransport(new TIOStreamTransport(new ByteArrayInputStream(compressed))); + int readBytes = transRead.read(buf, 0, buf.length); + assertEquals(uncompressed.length, readBytes); + transRead.close(); + } + + public void testRead() throws IOException, TTransportException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(baos); + DataOutputStream dos = new DataOutputStream(deflaterOutputStream); + dos.write(byteSequence(0, 49)); + dos.write(byteSequence(0, 219)); + + deflaterOutputStream.finish(); + + TMemoryBuffer membuf = new TMemoryBuffer(0); + membuf.write(baos.toByteArray()); + + ReadCountingTransport countTrans = new ReadCountingTransport(membuf); + TTransport trans = getTransport(countTrans); + + byte[] readBuf = new byte[10]; + trans.read(readBuf, 0, 10); + assertTrue(Arrays.equals(readBuf, byteSequence(0,9))); + assertEquals(1, countTrans.readCount); + + trans.read(readBuf, 0, 10); + assertTrue(Arrays.equals(readBuf, byteSequence(10,19))); + assertEquals(1, countTrans.readCount); + + assertEquals(30, trans.read(new byte[30], 0, 30)); + assertEquals(1, countTrans.readCount); + + readBuf = new byte[220]; + assertEquals(220, trans.read(readBuf, 0, 220)); + assertTrue(Arrays.equals(readBuf, byteSequence(0, 219))); + assertEquals(1, countTrans.readCount); + } + + public void testWrite() throws TTransportException, IOException, DataFormatException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); + TTransport trans = getTransport(countingTrans); + + trans.write(byteSequence(0, 100)); + assertEquals(1, countingTrans.writeCount); + trans.write(byteSequence(101, 200)); + trans.write(byteSequence(201, 255)); + assertEquals(1, countingTrans.writeCount); + + trans.flush(); + assertEquals(2, countingTrans.writeCount); + + trans.write(byteSequence(0, 245)); + trans.flush(); + assertEquals(3, countingTrans.writeCount); + + 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); + assertTrue(Arrays.equals(byteSequence(0, 255), buf)); + + buf = new byte[246]; + n = din.read(buf, 0, 246); + assertEquals(n, 246); + for (int i = 0; i<buf.length; i++) { + assertEquals("for "+i, byteSequence(0,245)[i], buf[i]); + } + + assertTrue(Arrays.equals(byteSequence(0,245), buf)); + } + +} diff --git a/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/WriteCountingTransport.java b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/WriteCountingTransport.java new file mode 100644 index 000000000..358f5c6eb --- /dev/null +++ b/src/jaegertracing/thrift/lib/java/test/org/apache/thrift/transport/WriteCountingTransport.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.thrift.transport; + + +public class WriteCountingTransport extends TTransport { + public int writeCount = 0; + private final TTransport trans; + + public WriteCountingTransport(TTransport underlying) { + trans = underlying; + } + + @Override + public void close() {} + + @Override + public boolean isOpen() {return true;} + + @Override + public void open() throws TTransportException {} + + @Override + public int read(byte[] buf, int off, int len) throws TTransportException { + return 0; + } + + @Override + public void write(byte[] buf, int off, int len) throws TTransportException { + writeCount ++; + trans.write(buf, off, len); + } + + @Override + public void flush() throws TTransportException { + trans.flush(); + } +}
\ No newline at end of file |