THRIFT-317. java: Issues with Java struct validation
authorBryan Duxbury <bryanduxbury@apache.org>
Tue, 27 Dec 2011 22:26:59 +0000 (22:26 +0000)
committerBryan Duxbury <bryanduxbury@apache.org>
Tue, 27 Dec 2011 22:26:59 +0000 (22:26 +0000)
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

compiler/cpp/src/generate/t_java_generator.cc
lib/java/test/org/apache/thrift/TestStruct.java
test/ThriftTest.thrift

index 9f2bbd3..34bcf32 100644 (file)
@@ -1656,6 +1656,16 @@ void t_java_generator::generate_java_validator(ofstream& out,
     }
   }
 
+  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;
 }
index 61162d9..b0dffc8 100644 (file)
@@ -22,7 +22,6 @@ 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;
@@ -45,6 +44,8 @@ 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 {
@@ -332,4 +333,36 @@ public class TestStruct extends TestCase {
 
     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
+    }
+  }
 }
index 633be1f..b9b7fda 100644 (file)
@@ -233,3 +233,12 @@ struct BoolTest {
   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