THRIFT-317. java: Issues with Java struct validation
Nested structs will now be validated before serialization starts.
git-svn-id: https://svn.apache.org/repos/asf/thrift/trunk@1225035 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/compiler/cpp/src/generate/t_java_generator.cc b/compiler/cpp/src/generate/t_java_generator.cc
index 9f2bbd3..34bcf32 100644
--- a/compiler/cpp/src/generate/t_java_generator.cc
+++ b/compiler/cpp/src/generate/t_java_generator.cc
@@ -1656,6 +1656,16 @@
}
}
+ out << indent() << "// check for sub-struct validity" << endl;
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+ t_type* type = (*f_iter)->get_type();
+ if (type->is_struct() && ! ((t_struct*)type)->is_union()) {
+ out << indent() << "if (" << (*f_iter)->get_name() << " != null) {" << endl;
+ out << indent() << " " << (*f_iter)->get_name() << ".validate();" << endl;
+ out << indent() << "}" << endl;
+ }
+ }
+
indent_down();
indent(out) << "}" << endl << endl;
}
diff --git a/lib/java/test/org/apache/thrift/TestStruct.java b/lib/java/test/org/apache/thrift/TestStruct.java
index 61162d9..b0dffc8 100644
--- a/lib/java/test/org/apache/thrift/TestStruct.java
+++ b/lib/java/test/org/apache/thrift/TestStruct.java
@@ -22,7 +22,6 @@
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
@@ -45,6 +44,8 @@
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 {
@@ -332,4 +333,36 @@
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/test/ThriftTest.thrift b/test/ThriftTest.thrift
index 633be1f..b9b7fda 100644
--- a/test/ThriftTest.thrift
+++ b/test/ThriftTest.thrift
@@ -233,3 +233,12 @@
1: optional bool b = true;
2: optional string s = "true";
}
+
+struct StructA {
+ 1: required string s;
+}
+
+struct StructB {
+ 1: optional StructA aa;
+ 2: required StructA ab;
+}
\ No newline at end of file