r1274@dev030 (orig r62880): mcslee | 2007-10-09 13:55:10 -0700
[amiethrift.git] / compiler / cpp / src / generate / t_java_generator.cc
blobea27854d652d33414eb1f902210929595078a7d9
1 // Copyright (c) 2006- Facebook
2 // Distributed under the Thrift Software License
3 //
4 // See accompanying file LICENSE or visit the Thrift site at:
5 // http://developers.facebook.com/thrift/
7 #include <stdlib.h>
8 #include <sys/stat.h>
9 #include <sstream>
10 #include "t_java_generator.h"
11 using namespace std;
13 /**
14 * Prepares for file generation by opening up the necessary file output
15 * streams.
17 * @param tprogram The program to generate
19 void t_java_generator::init_generator() {
20 // Make output directory
21 const char* java_dir = bean_style_ ? T_JAVABEAN_DIR : T_JAVA_DIR;
22 mkdir(java_dir, S_IREAD | S_IWRITE | S_IEXEC);
23 package_name_ = program_->get_java_package();
25 string dir = package_name_;
26 string subdir = java_dir;
27 string::size_type loc;
28 while ((loc = dir.find(".")) != string::npos) {
29 subdir = subdir + "/" + dir.substr(0, loc);
30 mkdir(subdir.c_str(), S_IREAD | S_IWRITE | S_IEXEC);
31 dir = dir.substr(loc+1);
33 if (dir.size() > 0) {
34 subdir = subdir + "/" + dir;
35 mkdir(subdir.c_str(), S_IREAD | S_IWRITE | S_IEXEC);
38 package_dir_ = subdir;
41 /**
42 * Packages the generated file
44 * @return String of the package, i.e. "package com.facebook.thriftdemo;"
46 string t_java_generator::java_package() {
47 if (!package_name_.empty()) {
48 return string("package ") + package_name_ + ";\n\n";
50 return "";
53 /**
54 * Prints standard java imports
56 * @return List of imports for Java types that are used in here
58 string t_java_generator::java_type_imports() {
59 return
60 string() +
61 "import java.util.ArrayList;\n" +
62 "import java.util.AbstractMap;\n" +
63 "import java.util.HashMap;\n" +
64 "import java.util.HashSet;\n" +
65 "import com.facebook.thrift.*;\n\n";
68 /**
69 * Prints standard java imports
71 * @return List of imports necessary for thrift
73 string t_java_generator::java_thrift_imports() {
74 return
75 string() +
76 "import com.facebook.thrift.protocol.*;\n" +
77 "import com.facebook.thrift.transport.*;\n\n";
80 /**
81 * Nothing in Java
83 void t_java_generator::close_generator() {}
85 /**
86 * Generates a typedef. This is not done in Java, since it does
87 * not support arbitrary name replacements, and it'd be a wacky waste
88 * of overhead to make wrapper classes.
90 * @param ttypedef The type definition
92 void t_java_generator::generate_typedef(t_typedef* ttypedef) {}
94 /**
95 * Enums are a class with a set of static constants.
97 * @param tenum The enumeration
99 void t_java_generator::generate_enum(t_enum* tenum) {
100 // Make output file
101 string f_enum_name = package_dir_+"/"+(tenum->get_name())+".java";
102 ofstream f_enum;
103 f_enum.open(f_enum_name.c_str());
105 // Comment and package it
106 f_enum <<
107 autogen_comment() <<
108 java_package() << endl;
110 f_enum <<
111 "public class " << tenum->get_name() << " ";
112 scope_up(f_enum);
114 vector<t_enum_value*> constants = tenum->get_constants();
115 vector<t_enum_value*>::iterator c_iter;
116 int value = -1;
117 for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
118 if ((*c_iter)->has_value()) {
119 value = (*c_iter)->get_value();
120 } else {
121 ++value;
124 indent(f_enum) <<
125 "public static final int " << (*c_iter)->get_name() <<
126 " = " << value << ";" << endl;
129 scope_down(f_enum);
130 f_enum.close();
134 * Generates a class that holds all the constants.
136 void t_java_generator::generate_consts(std::vector<t_const*> consts) {
137 string f_consts_name = package_dir_+"/Constants.java";
138 ofstream f_consts;
139 f_consts.open(f_consts_name.c_str());
141 // Print header
142 f_consts <<
143 autogen_comment() <<
144 java_package() <<
145 java_type_imports();
147 f_consts <<
148 "public class Constants {" << endl <<
149 endl;
150 indent_up();
151 vector<t_const*>::iterator c_iter;
152 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
153 print_const_value(f_consts,
154 (*c_iter)->get_name(),
155 (*c_iter)->get_type(),
156 (*c_iter)->get_value(),
157 false);
159 indent_down();
160 indent(f_consts) <<
161 "}" << endl;
162 f_consts.close();
167 * Prints the value of a constant with the given type. Note that type checking
168 * is NOT performed in this function as it is always run beforehand using the
169 * validate_types method in main.cc
171 void t_java_generator::print_const_value(std::ofstream& out, string name, t_type* type, t_const_value* value, bool in_static, bool defval) {
173 indent(out);
174 if (!defval) {
175 out <<
176 (in_static ? "" : "public static final ") <<
177 type_name(type) << " ";
179 if (type->is_base_type()) {
180 string v2 = render_const_value(out, name, type, value);
181 out << name << " = " << v2 << ";" << endl << endl;
182 } else if (type->is_enum()) {
183 out << name << " = " << value->get_integer() << ";" << endl << endl;
184 } else if (type->is_struct() || type->is_xception()) {
185 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
186 vector<t_field*>::const_iterator f_iter;
187 const map<t_const_value*, t_const_value*>& val = value->get_map();
188 map<t_const_value*, t_const_value*>::const_iterator v_iter;
189 out << name << " = new " << type_name(type) << "();" << endl;
190 if (!in_static) {
191 indent(out) << "static {" << endl;
192 indent_up();
194 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
195 t_type* field_type = NULL;
196 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
197 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
198 field_type = (*f_iter)->get_type();
201 if (field_type == NULL) {
202 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
204 string val = render_const_value(out, name, field_type, v_iter->second);
205 indent(out) << name << "." << v_iter->first->get_string() << " = " << val << ";" << endl;
206 indent(out) << name << ".__isset." << v_iter->first->get_string() << " = true;" << endl;
208 if (!in_static) {
209 indent_down();
210 indent(out) << "}" << endl;
212 out << endl;
213 } else if (type->is_map()) {
214 out << name << " = new " << type_name(type, true, true) << "();" << endl;
215 if (!in_static) {
216 indent(out) << "static {" << endl;
217 indent_up();
219 t_type* ktype = ((t_map*)type)->get_key_type();
220 t_type* vtype = ((t_map*)type)->get_val_type();
221 const map<t_const_value*, t_const_value*>& val = value->get_map();
222 map<t_const_value*, t_const_value*>::const_iterator v_iter;
223 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
224 string key = render_const_value(out, name, ktype, v_iter->first);
225 string val = render_const_value(out, name, vtype, v_iter->second);
226 indent(out) << name << ".put(" << key << ", " << val << ");" << endl;
228 if (!in_static) {
229 indent_down();
230 indent(out) << "}" << endl;
232 out << endl;
233 } else if (type->is_list() || type->is_set()) {
234 out << name << " = new " << type_name(type) << "();" << endl;
235 if (!in_static) {
236 indent(out) << "static {" << endl;
237 indent_up();
239 t_type* etype;
240 if (type->is_list()) {
241 etype = ((t_list*)type)->get_elem_type();
242 } else {
243 etype = ((t_set*)type)->get_elem_type();
245 const vector<t_const_value*>& val = value->get_list();
246 vector<t_const_value*>::const_iterator v_iter;
247 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
248 string val = render_const_value(out, name, etype, *v_iter);
249 indent(out) << name << ".add(" << val << ");" << endl;
251 if (!in_static) {
252 indent_down();
253 indent(out) << "}" << endl;
255 out << endl;
259 string t_java_generator::render_const_value(ofstream& out, string name, t_type* type, t_const_value* value) {
260 std::ostringstream render;
262 if (type->is_base_type()) {
263 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
264 switch (tbase) {
265 case t_base_type::TYPE_STRING:
266 render << "\"" + value->get_string() + "\"";
267 break;
268 case t_base_type::TYPE_BOOL:
269 render << ((value->get_integer() > 0) ? "true" : "false");
270 break;
271 case t_base_type::TYPE_BYTE:
272 case t_base_type::TYPE_I16:
273 case t_base_type::TYPE_I32:
274 case t_base_type::TYPE_I64:
275 render << value->get_integer();
276 break;
277 case t_base_type::TYPE_DOUBLE:
278 if (value->get_type() == t_const_value::CV_INTEGER) {
279 render << value->get_integer();
280 } else {
281 render << value->get_double();
283 break;
284 default:
285 throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
287 } else if (type->is_enum()) {
288 render << value->get_integer();
289 } else {
290 string t = tmp("tmp");
291 print_const_value(out, t, type, value, true);
292 render << t;
295 return render.str();
299 * Generates a struct definition for a thrift data type. This is a class
300 * with data members, read(), write(), and an inner Isset class.
302 * @param tstruct The struct definition
304 void t_java_generator::generate_struct(t_struct* tstruct) {
305 generate_java_struct(tstruct, false);
309 * Exceptions are structs, but they inherit from Exception
311 * @param tstruct The struct definition
313 void t_java_generator::generate_xception(t_struct* txception) {
314 generate_java_struct(txception, true);
319 * Java struct definition.
321 * @param tstruct The struct definition
323 void t_java_generator::generate_java_struct(t_struct* tstruct,
324 bool is_exception) {
325 // Make output file
326 string f_struct_name = package_dir_+"/"+(tstruct->get_name())+".java";
327 ofstream f_struct;
328 f_struct.open(f_struct_name.c_str());
330 f_struct <<
331 autogen_comment() <<
332 java_package() <<
333 java_type_imports() <<
334 java_thrift_imports();
336 generate_java_struct_definition(f_struct,
337 tstruct,
338 is_exception);
339 f_struct.close();
343 * Java struct definition. This has various parameters, as it could be
344 * generated standalone or inside another class as a helper. If it
345 * is a helper than it is a static class.
347 * @param tstruct The struct definition
348 * @param is_exception Is this an exception?
349 * @param in_class If inside a class, needs to be static class
350 * @param is_result If this is a result it needs a different writer
352 void t_java_generator::generate_java_struct_definition(ofstream &out,
353 t_struct* tstruct,
354 bool is_exception,
355 bool in_class,
356 bool is_result) {
357 generate_java_doc(out, tstruct);
359 indent(out) <<
360 "public " << (in_class ? "static " : "") << "class " << tstruct->get_name() << " ";
362 if (is_exception) {
363 out << "extends Exception ";
365 out << "implements TBase, java.io.Serializable ";
367 scope_up(out);
369 // Members are public for -java, private for -javabean
370 const vector<t_field*>& members = tstruct->get_members();
371 vector<t_field*>::const_iterator m_iter;
372 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
373 if (bean_style_) {
374 indent(out) << "private ";
375 } else {
376 indent(out) << "public ";
378 out << declare_field(*m_iter, false) << endl;
381 // Inner Isset class
382 if (members.size() > 0) {
383 out <<
384 endl <<
385 indent() << "public final Isset __isset = new Isset();" << endl <<
386 indent() << "public static final class Isset {" << endl;
387 indent_up();
388 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
389 indent(out) <<
390 "public boolean " << (*m_iter)->get_name() << " = false;" << endl;
392 indent_down();
393 out <<
394 indent() << "}" << endl <<
395 endl;
398 // Default constructor
399 indent(out) <<
400 "public " << tstruct->get_name() << "() {" << endl;
401 indent_up();
402 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
403 t_type* t = get_true_type((*m_iter)->get_type());
404 if (!t->is_base_type() && (*m_iter)->get_value() != NULL) {
405 print_const_value(out, "this." + (*m_iter)->get_name(), t, (*m_iter)->get_value(), true, true);
408 indent_down();
409 indent(out) << "}" << endl << endl;
412 // Full constructor for all fields
413 if (!members.empty()) {
414 indent(out) <<
415 "public " << tstruct->get_name() << "(" << endl;
416 indent_up();
417 for (m_iter = members.begin(); m_iter != members.end(); ) {
418 indent(out) << type_name((*m_iter)->get_type()) << " " <<
419 (*m_iter)->get_name();
420 ++m_iter;
421 if (m_iter != members.end()) {
422 out << "," << endl;
425 out << ")" << endl;
426 indent_down();
427 indent(out) << "{" << endl;
428 indent_up();
429 indent(out) << "this();" << endl;
430 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
431 indent(out) << "this." << (*m_iter)->get_name() << " = " <<
432 (*m_iter)->get_name() << ";" << endl;
433 indent(out) << "this.__isset." << (*m_iter)->get_name() << " = true;" << endl;
435 indent_down();
436 indent(out) << "}" << endl << endl;
439 if (bean_style_) {
440 generate_java_bean_boilerplate(out, tstruct);
442 generate_java_struct_reader(out, tstruct);
443 if (is_result) {
444 generate_java_struct_result_writer(out, tstruct);
445 } else {
446 generate_java_struct_writer(out, tstruct);
448 generate_java_struct_tostring(out, tstruct);
449 scope_down(out);
450 out << endl;
454 * Generates a function to read all the fields of the struct.
456 * @param tstruct The struct definition
458 void t_java_generator::generate_java_struct_reader(ofstream& out,
459 t_struct* tstruct) {
460 out <<
461 indent() << "public void read(TProtocol iprot) throws TException {" << endl;
462 indent_up();
464 const vector<t_field*>& fields = tstruct->get_members();
465 vector<t_field*>::const_iterator f_iter;
467 // Declare stack tmp variables and read struct header
468 out <<
469 indent() << "TField field;" << endl <<
470 indent() << "iprot.readStructBegin();" << endl;
472 // Loop over reading in fields
473 indent(out) <<
474 "while (true)" << endl;
475 scope_up(out);
477 // Read beginning field marker
478 indent(out) <<
479 "field = iprot.readFieldBegin();" << endl;
481 // Check for field STOP marker and break
482 indent(out) <<
483 "if (field.type == TType.STOP) { " << endl;
484 indent_up();
485 indent(out) <<
486 "break;" << endl;
487 indent_down();
488 indent(out) <<
489 "}" << endl;
491 // Switch statement on the field we are reading
492 indent(out) <<
493 "switch (field.id)" << endl;
495 scope_up(out);
497 // Generate deserialization code for known cases
498 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
499 indent(out) <<
500 "case " << (*f_iter)->get_key() << ":" << endl;
501 indent_up();
502 indent(out) <<
503 "if (field.type == " << type_to_enum((*f_iter)->get_type()) << ") {" << endl;
504 indent_up();
506 generate_deserialize_field(out, *f_iter, "this.");
507 out <<
508 indent() << "this.__isset." << (*f_iter)->get_name() << " = true;" << endl;
509 indent_down();
510 out <<
511 indent() << "} else { " << endl <<
512 indent() << " TProtocolUtil.skip(iprot, field.type);" << endl <<
513 indent() << "}" << endl <<
514 indent() << "break;" << endl;
515 indent_down();
518 // In the default case we skip the field
519 out <<
520 indent() << "default:" << endl <<
521 indent() << " TProtocolUtil.skip(iprot, field.type);" << endl <<
522 indent() << " break;" << endl;
524 scope_down(out);
526 // Read field end marker
527 indent(out) <<
528 "iprot.readFieldEnd();" << endl;
530 scope_down(out);
532 out <<
533 indent() << "iprot.readStructEnd();" << endl;
535 indent_down();
536 out <<
537 indent() << "}" << endl <<
538 endl;
542 * Generates a function to write all the fields of the struct
544 * @param tstruct The struct definition
546 void t_java_generator::generate_java_struct_writer(ofstream& out,
547 t_struct* tstruct) {
548 out <<
549 indent() << "public void write(TProtocol oprot) throws TException {" << endl;
550 indent_up();
552 string name = tstruct->get_name();
553 const vector<t_field*>& fields = tstruct->get_members();
554 vector<t_field*>::const_iterator f_iter;
556 indent(out) << "TStruct struct = new TStruct(\"" << name << "\");" << endl;
557 indent(out) << "oprot.writeStructBegin(struct);" << endl;
559 if (!fields.empty()) {
560 indent(out) << "TField field = new TField();" << endl;
562 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
563 bool null_allowed = type_can_be_null((*f_iter)->get_type());
564 if (null_allowed) {
565 out <<
566 indent() << "if (this." << (*f_iter)->get_name() << " != null) {" << endl;
567 indent_up();
570 out <<
571 indent() << "field.name = \"" << (*f_iter)->get_name() << "\";" << endl <<
572 indent() << "field.type = " << type_to_enum((*f_iter)->get_type()) << ";" << endl <<
573 indent() << "field.id = " << (*f_iter)->get_key() << ";" << endl <<
574 indent() << "oprot.writeFieldBegin(field);" << endl;
576 // Write field contents
577 generate_serialize_field(out, *f_iter, "this.");
579 // Write field closer
580 indent(out) <<
581 "oprot.writeFieldEnd();" << endl;
583 if (null_allowed) {
584 indent_down();
585 indent(out) << "}" << endl;
588 // Write the struct map
589 out <<
590 indent() << "oprot.writeFieldStop();" << endl <<
591 indent() << "oprot.writeStructEnd();" << endl;
593 indent_down();
594 out <<
595 indent() << "}" << endl <<
596 endl;
600 * Generates a function to write all the fields of the struct,
601 * which is a function result. These fields are only written
602 * if they are set in the Isset array, and only one of them
603 * can be set at a time.
605 * @param tstruct The struct definition
607 void t_java_generator::generate_java_struct_result_writer(ofstream& out,
608 t_struct* tstruct) {
609 out <<
610 indent() << "public void write(TProtocol oprot) throws TException {" << endl;
611 indent_up();
613 string name = tstruct->get_name();
614 const vector<t_field*>& fields = tstruct->get_members();
615 vector<t_field*>::const_iterator f_iter;
617 indent(out) << "TStruct struct = new TStruct(\"" << name << "\");" << endl;
618 indent(out) << "oprot.writeStructBegin(struct);" << endl;
620 if (!fields.empty()) {
621 indent(out) << "TField field = new TField();" << endl;
623 bool first = true;
624 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
625 if (first) {
626 first = false;
627 out <<
628 endl <<
629 indent() << "if ";
630 } else {
631 out <<
632 " else if ";
635 out <<
636 "(this.__isset." << (*f_iter)->get_name() << ") {" << endl;
637 indent_up();
639 bool null_allowed = type_can_be_null((*f_iter)->get_type());
640 if (null_allowed) {
641 out <<
642 indent() << "if (this." << (*f_iter)->get_name() << " != null) {" << endl;
643 indent_up();
646 out <<
647 indent() << "field.name = \"" << (*f_iter)->get_name() << "\";" << endl <<
648 indent() << "field.type = " << type_to_enum((*f_iter)->get_type()) << ";" << endl <<
649 indent() << "field.id = " << (*f_iter)->get_key() << ";" << endl <<
650 indent() << "oprot.writeFieldBegin(field);" << endl;
652 // Write field contents
653 generate_serialize_field(out, *f_iter, "this.");
655 // Write field closer
656 indent(out) <<
657 "oprot.writeFieldEnd();" << endl;
659 if (null_allowed) {
660 indent_down();
661 indent(out) << "}" << endl;
664 indent_down();
665 indent(out) << "}";
667 // Write the struct map
668 out <<
669 endl <<
670 indent() << "oprot.writeFieldStop();" << endl <<
671 indent() << "oprot.writeStructEnd();" << endl;
673 indent_down();
674 out <<
675 indent() << "}" << endl <<
676 endl;
680 * Generates a set of Java Bean boilerplate functions (setters, getters, etc.)
681 * for the given struct.
683 * @param tstruct The struct definition
685 void t_java_generator::generate_java_bean_boilerplate(ofstream& out,
686 t_struct* tstruct) {
687 const vector<t_field*>& fields = tstruct->get_members();
688 vector<t_field*>::const_iterator f_iter;
689 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
690 t_field* field = *f_iter;
691 t_type* type = get_true_type(field->get_type());
692 std::string field_name = field->get_name();
693 std::string cap_name = field_name;
694 cap_name[0] = toupper(cap_name[0]);
696 if (type->is_container()) {
697 // Method to return the size of the collection
698 indent(out) << "public int get" << cap_name << "Size() {" << endl;
699 indent_up();
700 indent(out) << "return (this." << field_name << " == null) ? 0 : " <<
701 "this." << field_name << ".size();" << endl;
702 indent_down();
703 indent(out) << "}" << endl << endl;
706 if (type->is_set() || type->is_list()) {
708 t_type* element_type;
709 if (type->is_set()) {
710 element_type = ((t_set*)type)->get_elem_type();
711 } else {
712 element_type = ((t_list*)type)->get_elem_type();
715 // Iterator getter for sets and lists
716 indent(out) << "public java.util.Iterator<" <<
717 type_name(element_type) << "> get" << cap_name << "Iterator() {" << endl;
718 indent_up();
719 indent(out) << "return (this." << field_name << " == null) ? null : " <<
720 "this." << field_name << ".iterator();" << endl;
721 indent_down();
722 indent(out) << "}" << endl << endl;
724 // Add to set or list, create if the set/list is null
725 indent(out) << "public void addTo" << cap_name << "(" <<
726 type_name(element_type) <<
727 " elem) {" << endl;
728 indent_up();
729 indent(out) << "if (this." << field_name << " == null) {" << endl;
730 indent_up();
731 indent(out) << "this." << field_name << " = new " << type_name(type) <<
732 "();" << endl;
733 indent_down();
734 indent(out) << "}" << endl;
735 indent(out) << "this." << field_name << ".add(elem);" << endl;
736 indent(out) << "this.__isset." << field_name << " = true;" << endl;
737 indent_down();
738 indent(out) << "}" << endl << endl;
740 } else if (type->is_map()) {
741 // Put to map
742 t_type* key_type = ((t_map*)type)->get_key_type();
743 t_type* val_type = ((t_map*)type)->get_val_type();
744 indent(out) << "public void putTo" << cap_name << "(" <<
745 type_name(key_type) << " key, " <<
746 type_name(val_type) << " val) {" << endl;
747 indent_up();
748 indent(out) << "if (this." << field_name << " == null) {" << endl;
749 indent_up();
750 indent(out) << "this." << field_name << " = new " <<
751 type_name(type, false, true) << "();" << endl;
752 indent_down();
753 indent(out) << "}" << endl;
754 indent(out) << "this." << field_name << ".put(key, val);" << endl;
755 indent(out) << "this.__isset." << field_name << " = true;" << endl;
756 indent_down();
757 indent(out) << "}" << endl << endl;
760 // Simple getter
761 indent(out) << "public " << type_name(type);
762 if (type->is_base_type() &&
763 ((t_base_type*)type)->get_base() == t_base_type::TYPE_BOOL) {
764 out << " is";
765 } else {
766 out << " get";
768 out << cap_name << "() {" << endl;
769 indent_up();
770 indent(out) << "return this." << field_name << ";" << endl;
771 indent_down();
772 indent(out) << "}" << endl << endl;
774 // Simple setter
775 indent(out) << "public void set" << cap_name << "(" << type_name(type) <<
776 " " << field_name << ") {" << endl;
777 indent_up();
778 indent(out) << "this." << field_name << " = " << field_name << ";" <<
779 endl;
780 indent(out) << "this.__isset." << field_name << " = true;" << endl;
781 indent_down();
782 indent(out) << "}" << endl << endl;
784 // Unsetter
785 indent(out) << "public void unset" << cap_name << "() {" << endl;
786 indent_up();
787 if (type->is_container() || type->is_struct() || type->is_xception()) {
788 indent(out) << "this." << field_name << " = null;" << endl;
790 indent(out) << "this.__isset." << field_name << " = false;" << endl;
791 indent_down();
792 indent(out) << "}" << endl << endl;
797 * Generates a toString() method for the given struct
799 * @param tstruct The struct definition
801 void t_java_generator::generate_java_struct_tostring(ofstream& out,
802 t_struct* tstruct) {
803 out <<
804 indent() << "public String toString() {" << endl;
805 indent_up();
807 out <<
808 indent() << "StringBuilder sb = new StringBuilder(\"" << tstruct->get_name() << "(\");" << endl;
810 const vector<t_field*>& fields = tstruct->get_members();
811 vector<t_field*>::const_iterator f_iter;
812 bool first = true;
813 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
814 if (first) {
815 first = false;
816 indent(out) << "sb.append(\"" << (*f_iter)->get_name() << ":\");" << endl;
817 } else {
818 indent(out) << "sb.append(\"," << (*f_iter)->get_name() << ":\");" << endl;
820 t_type* ttype = (*f_iter)->get_type();
821 if (ttype->is_xception() || ttype->is_struct()) {
822 indent(out) << "sb.append(this." << (*f_iter)->get_name() << ".toString());" << endl;
823 } else {
824 indent(out) << "sb.append(this." << (*f_iter)->get_name() << ");" << endl;
827 out <<
828 indent() << "sb.append(\")\");" << endl <<
829 indent() << "return sb.toString();" << endl;
831 indent_down();
832 indent(out) << "}" << endl <<
833 endl;
838 * Generates a thrift service. In C++, this comprises an entirely separate
839 * header and source file. The header file defines the methods and includes
840 * the data types defined in the main header file, and the implementation
841 * file contains implementations of the basic printer and default interfaces.
843 * @param tservice The service definition
845 void t_java_generator::generate_service(t_service* tservice) {
846 // Make output file
847 string f_service_name = package_dir_+"/"+service_name_+".java";
848 f_service_.open(f_service_name.c_str());
850 f_service_ <<
851 autogen_comment() <<
852 java_package() <<
853 java_type_imports() <<
854 java_thrift_imports();
856 f_service_ <<
857 "public class " << service_name_ << " {" << endl <<
858 endl;
859 indent_up();
861 // Generate the three main parts of the service
862 generate_service_interface(tservice);
863 generate_service_client(tservice);
864 generate_service_server(tservice);
865 generate_service_helpers(tservice);
867 indent_down();
868 f_service_ <<
869 "}" << endl;
870 f_service_.close();
874 * Generates a service interface definition.
876 * @param tservice The service to generate a header definition for
878 void t_java_generator::generate_service_interface(t_service* tservice) {
879 string extends = "";
880 string extends_iface = "";
881 if (tservice->get_extends() != NULL) {
882 extends = type_name(tservice->get_extends());
883 extends_iface = " extends " + extends + ".Iface";
886 generate_java_doc(f_service_, tservice);
887 f_service_ << indent() << "public interface Iface" << extends_iface <<
888 " {" << endl << endl;
889 indent_up();
890 vector<t_function*> functions = tservice->get_functions();
891 vector<t_function*>::iterator f_iter;
892 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
893 generate_java_doc(f_service_, *f_iter);
894 indent(f_service_) << "public " << function_signature(*f_iter) << ";" <<
895 endl << endl;
897 indent_down();
898 f_service_ <<
899 indent() << "}" << endl <<
900 endl;
904 * Generates structs for all the service args and return types
906 * @param tservice The service
908 void t_java_generator::generate_service_helpers(t_service* tservice) {
909 vector<t_function*> functions = tservice->get_functions();
910 vector<t_function*>::iterator f_iter;
911 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
912 t_struct* ts = (*f_iter)->get_arglist();
913 generate_java_struct_definition(f_service_, ts, false, true);
914 generate_function_helpers(*f_iter);
919 * Generates a service client definition.
921 * @param tservice The service to generate a server for.
923 void t_java_generator::generate_service_client(t_service* tservice) {
924 string extends = "";
925 string extends_client = "";
926 if (tservice->get_extends() != NULL) {
927 extends = type_name(tservice->get_extends());
928 extends_client = " extends " + extends + ".Client";
931 indent(f_service_) <<
932 "public static class Client" << extends_client << " implements Iface {" << endl;
933 indent_up();
935 indent(f_service_) <<
936 "public Client(TProtocol prot)" << endl;
937 scope_up(f_service_);
938 indent(f_service_) <<
939 "this(prot, prot);" << endl;
940 scope_down(f_service_);
941 f_service_ << endl;
943 indent(f_service_) <<
944 "public Client(TProtocol iprot, TProtocol oprot)" << endl;
945 scope_up(f_service_);
946 if (extends.empty()) {
947 f_service_ <<
948 indent() << "iprot_ = iprot;" << endl <<
949 indent() << "oprot_ = oprot;" << endl;
950 } else {
951 f_service_ <<
952 indent() << "super(iprot, oprot);" << endl;
954 scope_down(f_service_);
955 f_service_ << endl;
957 if (extends.empty()) {
958 f_service_ <<
959 indent() << "protected TProtocol iprot_;" << endl <<
960 indent() << "protected TProtocol oprot_;" << endl <<
961 endl <<
962 indent() << "protected int seqid_;" << endl <<
963 endl;
966 // Generate client method implementations
967 vector<t_function*> functions = tservice->get_functions();
968 vector<t_function*>::const_iterator f_iter;
969 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
970 string funname = (*f_iter)->get_name();
972 // Open function
973 indent(f_service_) <<
974 "public " << function_signature(*f_iter) << endl;
975 scope_up(f_service_);
976 indent(f_service_) <<
977 "send_" << funname << "(";
979 // Get the struct of function call params
980 t_struct* arg_struct = (*f_iter)->get_arglist();
982 // Declare the function arguments
983 const vector<t_field*>& fields = arg_struct->get_members();
984 vector<t_field*>::const_iterator fld_iter;
985 bool first = true;
986 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
987 if (first) {
988 first = false;
989 } else {
990 f_service_ << ", ";
992 f_service_ << (*fld_iter)->get_name();
994 f_service_ << ");" << endl;
996 if (!(*f_iter)->is_async()) {
997 f_service_ << indent();
998 if (!(*f_iter)->get_returntype()->is_void()) {
999 f_service_ << "return ";
1001 f_service_ <<
1002 "recv_" << funname << "();" << endl;
1004 scope_down(f_service_);
1005 f_service_ << endl;
1007 t_function send_function(g_type_void,
1008 string("send_") + (*f_iter)->get_name(),
1009 (*f_iter)->get_arglist());
1011 string argsname = (*f_iter)->get_name() + "_args";
1013 // Open function
1014 indent(f_service_) <<
1015 "public " << function_signature(&send_function) << endl;
1016 scope_up(f_service_);
1018 // Serialize the request
1019 f_service_ <<
1020 indent() << "oprot_.writeMessageBegin(new TMessage(\"" << funname << "\", TMessageType.CALL, seqid_));" << endl <<
1021 indent() << argsname << " args = new " << argsname << "();" << endl;
1023 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
1024 f_service_ <<
1025 indent() << "args." << (*fld_iter)->get_name() << " = " << (*fld_iter)->get_name() << ";" << endl;
1028 f_service_ <<
1029 indent() << "args.write(oprot_);" << endl <<
1030 indent() << "oprot_.writeMessageEnd();" << endl <<
1031 indent() << "oprot_.getTransport().flush();" << endl;
1033 scope_down(f_service_);
1034 f_service_ << endl;
1036 if (!(*f_iter)->is_async()) {
1037 string resultname = (*f_iter)->get_name() + "_result";
1039 t_struct noargs(program_);
1040 t_function recv_function((*f_iter)->get_returntype(),
1041 string("recv_") + (*f_iter)->get_name(),
1042 &noargs,
1043 (*f_iter)->get_xceptions());
1044 // Open function
1045 indent(f_service_) <<
1046 "public " << function_signature(&recv_function) << endl;
1047 scope_up(f_service_);
1049 // TODO(mcslee): Message validation here, was the seqid etc ok?
1051 f_service_ <<
1052 indent() << "TMessage msg = iprot_.readMessageBegin();" << endl <<
1053 indent() << "if (msg.type == TMessageType.EXCEPTION) {" << endl <<
1054 indent() << " TApplicationException x = TApplicationException.read(iprot_);" << endl <<
1055 indent() << " iprot_.readMessageEnd();" << endl <<
1056 indent() << " throw x;" << endl <<
1057 indent() << "}" << endl <<
1058 indent() << resultname << " result = new " << resultname << "();" << endl <<
1059 indent() << "result.read(iprot_);" << endl <<
1060 indent() << "iprot_.readMessageEnd();" << endl;
1062 // Careful, only return _result if not a void function
1063 if (!(*f_iter)->get_returntype()->is_void()) {
1064 f_service_ <<
1065 indent() << "if (result.__isset.success) {" << endl <<
1066 indent() << " return result.success;" << endl <<
1067 indent() << "}" << endl;
1070 t_struct* xs = (*f_iter)->get_xceptions();
1071 const std::vector<t_field*>& xceptions = xs->get_members();
1072 vector<t_field*>::const_iterator x_iter;
1073 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
1074 f_service_ <<
1075 indent() << "if (result.__isset." << (*x_iter)->get_name() << ") {" << endl <<
1076 indent() << " throw result." << (*x_iter)->get_name() << ";" << endl <<
1077 indent() << "}" << endl;
1080 // If you get here it's an exception, unless a void function
1081 if ((*f_iter)->get_returntype()->is_void()) {
1082 indent(f_service_) <<
1083 "return;" << endl;
1084 } else {
1085 f_service_ <<
1086 indent() << "throw new TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() << " failed: unknown result\");" << endl;
1089 // Close function
1090 scope_down(f_service_);
1091 f_service_ << endl;
1095 indent_down();
1096 indent(f_service_) <<
1097 "}" << endl;
1101 * Generates a service server definition.
1103 * @param tservice The service to generate a server for.
1105 void t_java_generator::generate_service_server(t_service* tservice) {
1106 // Generate the dispatch methods
1107 vector<t_function*> functions = tservice->get_functions();
1108 vector<t_function*>::iterator f_iter;
1110 // Extends stuff
1111 string extends = "";
1112 string extends_processor = "";
1113 if (tservice->get_extends() != NULL) {
1114 extends = type_name(tservice->get_extends());
1115 extends_processor = " extends " + extends + ".Processor";
1118 // Generate the header portion
1119 indent(f_service_) <<
1120 "public static class Processor" << extends_processor << " implements TProcessor {" << endl;
1121 indent_up();
1123 indent(f_service_) <<
1124 "public Processor(Iface iface)" << endl;
1125 scope_up(f_service_);
1126 if (!extends.empty()) {
1127 f_service_ <<
1128 indent() << "super(iface);" << endl;
1130 f_service_ <<
1131 indent() << "iface_ = iface;" << endl;
1133 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
1134 f_service_ <<
1135 indent() << "processMap_.put(\"" << (*f_iter)->get_name() << "\", new " << (*f_iter)->get_name() << "());" << endl;
1138 scope_down(f_service_);
1139 f_service_ << endl;
1141 if (extends.empty()) {
1142 f_service_ <<
1143 indent() << "protected static interface ProcessFunction {" << endl <<
1144 indent() << " public void process(int seqid, TProtocol iprot, TProtocol oprot) throws TException;" << endl <<
1145 indent() << "}" << endl <<
1146 endl;
1149 f_service_ <<
1150 indent() << "private Iface iface_;" << endl;
1152 if (extends.empty()) {
1153 f_service_ <<
1154 indent() << "protected final HashMap<String,ProcessFunction> processMap_ = new HashMap<String,ProcessFunction>();" << endl;
1157 f_service_ << endl;
1159 // Generate the server implementation
1160 indent(f_service_) <<
1161 "public boolean process(TProtocol iprot, TProtocol oprot) throws TException" << endl;
1162 scope_up(f_service_);
1164 f_service_ <<
1165 indent() << "TMessage msg = iprot.readMessageBegin();" << endl;
1167 // TODO(mcslee): validate message, was the seqid etc. legit?
1169 f_service_ <<
1170 indent() << "ProcessFunction fn = processMap_.get(msg.name);" << endl <<
1171 indent() << "if (fn == null) {" << endl <<
1172 indent() << " TProtocolUtil.skip(iprot, TType.STRUCT);" << endl <<
1173 indent() << " iprot.readMessageEnd();" << endl <<
1174 indent() << " TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, \"Invalid method name: '\"+msg.name+\"'\");" << endl <<
1175 indent() << " oprot.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid));" << endl <<
1176 indent() << " x.write(oprot);" << endl <<
1177 indent() << " oprot.writeMessageEnd();" << endl <<
1178 indent() << " oprot.getTransport().flush();" << endl <<
1179 indent() << " return true;" << endl <<
1180 indent() << "}" << endl <<
1181 indent() << "fn.process(msg.seqid, iprot, oprot);" << endl;
1183 f_service_ <<
1184 indent() << "return true;" << endl;
1186 scope_down(f_service_);
1187 f_service_ << endl;
1189 // Generate the process subfunctions
1190 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
1191 generate_process_function(tservice, *f_iter);
1194 indent_down();
1195 indent(f_service_) <<
1196 "}" << endl <<
1197 endl;
1201 * Generates a struct and helpers for a function.
1203 * @param tfunction The function
1205 void t_java_generator::generate_function_helpers(t_function* tfunction) {
1206 if (tfunction->is_async()) {
1207 return;
1210 t_struct result(program_, tfunction->get_name() + "_result");
1211 t_field success(tfunction->get_returntype(), "success", 0);
1212 if (!tfunction->get_returntype()->is_void()) {
1213 result.append(&success);
1216 t_struct* xs = tfunction->get_xceptions();
1217 const vector<t_field*>& fields = xs->get_members();
1218 vector<t_field*>::const_iterator f_iter;
1219 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1220 result.append(*f_iter);
1223 generate_java_struct_definition(f_service_, &result, false, true, true);
1227 * Generates a process function definition.
1229 * @param tfunction The function to write a dispatcher for
1231 void t_java_generator::generate_process_function(t_service* tservice,
1232 t_function* tfunction) {
1233 // Open class
1234 indent(f_service_) <<
1235 "private class " << tfunction->get_name() << " implements ProcessFunction {" << endl;
1236 indent_up();
1238 // Open function
1239 indent(f_service_) <<
1240 "public void process(int seqid, TProtocol iprot, TProtocol oprot) throws TException" << endl;
1241 scope_up(f_service_);
1243 string argsname = tfunction->get_name() + "_args";
1244 string resultname = tfunction->get_name() + "_result";
1246 f_service_ <<
1247 indent() << argsname << " args = new " << argsname << "();" << endl <<
1248 indent() << "args.read(iprot);" << endl <<
1249 indent() << "iprot.readMessageEnd();" << endl;
1251 t_struct* xs = tfunction->get_xceptions();
1252 const std::vector<t_field*>& xceptions = xs->get_members();
1253 vector<t_field*>::const_iterator x_iter;
1255 // Declare result for non async function
1256 if (!tfunction->is_async()) {
1257 f_service_ <<
1258 indent() << resultname << " result = new " << resultname << "();" << endl;
1261 // Try block for a function with exceptions
1262 if (xceptions.size() > 0) {
1263 f_service_ <<
1264 indent() << "try {" << endl;
1265 indent_up();
1268 // Generate the function call
1269 t_struct* arg_struct = tfunction->get_arglist();
1270 const std::vector<t_field*>& fields = arg_struct->get_members();
1271 vector<t_field*>::const_iterator f_iter;
1273 f_service_ << indent();
1274 if (!tfunction->is_async() && !tfunction->get_returntype()->is_void()) {
1275 f_service_ << "result.success = ";
1277 f_service_ <<
1278 "iface_." << tfunction->get_name() << "(";
1279 bool first = true;
1280 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1281 if (first) {
1282 first = false;
1283 } else {
1284 f_service_ << ", ";
1286 f_service_ << "args." << (*f_iter)->get_name();
1288 f_service_ << ");" << endl;
1290 // Set isset on success field
1291 if (!tfunction->is_async() && !tfunction->get_returntype()->is_void()) {
1292 f_service_ <<
1293 indent() << "result.__isset.success = true;" << endl;
1296 if (!tfunction->is_async() && xceptions.size() > 0) {
1297 indent_down();
1298 f_service_ << indent() << "}";
1299 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
1300 f_service_ << " catch (" << type_name((*x_iter)->get_type(), false, false) << " " << (*x_iter)->get_name() << ") {" << endl;
1301 if (!tfunction->is_async()) {
1302 indent_up();
1303 f_service_ <<
1304 indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name() << ";" << endl <<
1305 indent() << "result.__isset." << (*x_iter)->get_name() << " = true;" << endl;
1306 indent_down();
1307 f_service_ << indent() << "}";
1308 } else {
1309 f_service_ << "}";
1312 f_service_ << endl;
1315 // Shortcut out here for async functions
1316 if (tfunction->is_async()) {
1317 f_service_ <<
1318 indent() << "return;" << endl;
1319 scope_down(f_service_);
1321 // Close class
1322 indent_down();
1323 f_service_ <<
1324 indent() << "}" << endl <<
1325 endl;
1326 return;
1329 f_service_ <<
1330 indent() << "oprot.writeMessageBegin(new TMessage(\"" << tfunction->get_name() << "\", TMessageType.REPLY, seqid));" << endl <<
1331 indent() << "result.write(oprot);" << endl <<
1332 indent() << "oprot.writeMessageEnd();" << endl <<
1333 indent() << "oprot.getTransport().flush();" << endl;
1335 // Close function
1336 scope_down(f_service_);
1337 f_service_ << endl;
1339 // Close class
1340 indent_down();
1341 f_service_ <<
1342 indent() << "}" << endl <<
1343 endl;
1347 * Deserializes a field of any type.
1349 * @param tfield The field
1350 * @param prefix The variable name or container for this field
1352 void t_java_generator::generate_deserialize_field(ofstream& out,
1353 t_field* tfield,
1354 string prefix) {
1355 t_type* type = get_true_type(tfield->get_type());
1357 if (type->is_void()) {
1358 throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " +
1359 prefix + tfield->get_name();
1362 string name = prefix + tfield->get_name();
1364 if (type->is_struct() || type->is_xception()) {
1365 generate_deserialize_struct(out,
1366 (t_struct*)type,
1367 name);
1368 } else if (type->is_container()) {
1369 generate_deserialize_container(out, type, name);
1370 } else if (type->is_base_type() || type->is_enum()) {
1372 indent(out) <<
1373 name << " = iprot.";
1375 if (type->is_base_type()) {
1376 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1377 switch (tbase) {
1378 case t_base_type::TYPE_VOID:
1379 throw "compiler error: cannot serialize void field in a struct: " +
1380 name;
1381 break;
1382 case t_base_type::TYPE_STRING:
1383 if (((t_base_type*)type)->is_binary()) {
1384 out << "readBinary();";
1385 } else {
1386 out << "readString();";
1388 break;
1389 case t_base_type::TYPE_BOOL:
1390 out << "readBool();";
1391 break;
1392 case t_base_type::TYPE_BYTE:
1393 out << "readByte();";
1394 break;
1395 case t_base_type::TYPE_I16:
1396 out << "readI16();";
1397 break;
1398 case t_base_type::TYPE_I32:
1399 out << "readI32();";
1400 break;
1401 case t_base_type::TYPE_I64:
1402 out << "readI64();";
1403 break;
1404 case t_base_type::TYPE_DOUBLE:
1405 out << "readDouble();";
1406 break;
1407 default:
1408 throw "compiler error: no Java name for base type " + t_base_type::t_base_name(tbase);
1410 } else if (type->is_enum()) {
1411 out << "readI32();";
1413 out <<
1414 endl;
1415 } else {
1416 printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
1417 tfield->get_name().c_str(), type_name(type).c_str());
1422 * Generates an unserializer for a struct, invokes read()
1424 void t_java_generator::generate_deserialize_struct(ofstream& out,
1425 t_struct* tstruct,
1426 string prefix) {
1427 out <<
1428 indent() << prefix << " = new " << type_name(tstruct) << "();" << endl <<
1429 indent() << prefix << ".read(iprot);" << endl;
1433 * Deserializes a container by reading its size and then iterating
1435 void t_java_generator::generate_deserialize_container(ofstream& out,
1436 t_type* ttype,
1437 string prefix) {
1438 scope_up(out);
1440 string obj;
1442 if (ttype->is_map()) {
1443 obj = tmp("_map");
1444 } else if (ttype->is_set()) {
1445 obj = tmp("_set");
1446 } else if (ttype->is_list()) {
1447 obj = tmp("_list");
1450 // Declare variables, read header
1451 if (ttype->is_map()) {
1452 indent(out) << "TMap " << obj << " = iprot.readMapBegin();" << endl;
1453 } else if (ttype->is_set()) {
1454 indent(out) << "TSet " << obj << " = iprot.readSetBegin();" << endl;
1455 } else if (ttype->is_list()) {
1456 indent(out) << "TList " << obj << " = iprot.readListBegin();" << endl;
1459 indent(out)
1460 << prefix << " = new " << type_name(ttype, false, true)
1461 // size the collection correctly
1462 << "("
1463 << (ttype->is_list() ? "" : "2*" )
1464 << obj << ".size"
1465 << ");" << endl;
1467 // For loop iterates over elements
1468 string i = tmp("_i");
1469 indent(out) <<
1470 "for (int " << i << " = 0; " <<
1471 i << " < " << obj << ".size" << "; " <<
1472 "++" << i << ")" << endl;
1474 scope_up(out);
1476 if (ttype->is_map()) {
1477 generate_deserialize_map_element(out, (t_map*)ttype, prefix);
1478 } else if (ttype->is_set()) {
1479 generate_deserialize_set_element(out, (t_set*)ttype, prefix);
1480 } else if (ttype->is_list()) {
1481 generate_deserialize_list_element(out, (t_list*)ttype, prefix);
1484 scope_down(out);
1486 // Read container end
1487 if (ttype->is_map()) {
1488 indent(out) << "iprot.readMapEnd();" << endl;
1489 } else if (ttype->is_set()) {
1490 indent(out) << "iprot.readSetEnd();" << endl;
1491 } else if (ttype->is_list()) {
1492 indent(out) << "iprot.readListEnd();" << endl;
1495 scope_down(out);
1500 * Generates code to deserialize a map
1502 void t_java_generator::generate_deserialize_map_element(ofstream& out,
1503 t_map* tmap,
1504 string prefix) {
1505 string key = tmp("_key");
1506 string val = tmp("_val");
1507 t_field fkey(tmap->get_key_type(), key);
1508 t_field fval(tmap->get_val_type(), val);
1510 indent(out) <<
1511 declare_field(&fkey) << endl;
1512 indent(out) <<
1513 declare_field(&fval) << endl;
1515 generate_deserialize_field(out, &fkey);
1516 generate_deserialize_field(out, &fval);
1518 indent(out) <<
1519 prefix << ".put(" << key << ", " << val << ");" << endl;
1523 * Deserializes a set element
1525 void t_java_generator::generate_deserialize_set_element(ofstream& out,
1526 t_set* tset,
1527 string prefix) {
1528 string elem = tmp("_elem");
1529 t_field felem(tset->get_elem_type(), elem);
1531 indent(out) <<
1532 declare_field(&felem, true) << endl;
1534 generate_deserialize_field(out, &felem);
1536 indent(out) <<
1537 prefix << ".add(" << elem << ");" << endl;
1541 * Deserializes a list element
1543 void t_java_generator::generate_deserialize_list_element(ofstream& out,
1544 t_list* tlist,
1545 string prefix) {
1546 string elem = tmp("_elem");
1547 t_field felem(tlist->get_elem_type(), elem);
1549 indent(out) <<
1550 declare_field(&felem, true) << endl;
1552 generate_deserialize_field(out, &felem);
1554 indent(out) <<
1555 prefix << ".add(" << elem << ");" << endl;
1560 * Serializes a field of any type.
1562 * @param tfield The field to serialize
1563 * @param prefix Name to prepend to field name
1565 void t_java_generator::generate_serialize_field(ofstream& out,
1566 t_field* tfield,
1567 string prefix) {
1568 t_type* type = get_true_type(tfield->get_type());
1570 // Do nothing for void types
1571 if (type->is_void()) {
1572 throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " +
1573 prefix + tfield->get_name();
1576 if (type->is_struct() || type->is_xception()) {
1577 generate_serialize_struct(out,
1578 (t_struct*)type,
1579 prefix + tfield->get_name());
1580 } else if (type->is_container()) {
1581 generate_serialize_container(out,
1582 type,
1583 prefix + tfield->get_name());
1584 } else if (type->is_base_type() || type->is_enum()) {
1586 string name = prefix + tfield->get_name();
1587 indent(out) <<
1588 "oprot.";
1590 if (type->is_base_type()) {
1591 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1592 switch (tbase) {
1593 case t_base_type::TYPE_VOID:
1594 throw
1595 "compiler error: cannot serialize void field in a struct: " + name;
1596 break;
1597 case t_base_type::TYPE_STRING:
1598 if (((t_base_type*)type)->is_binary()) {
1599 out << "writeBinary(" << name << ");";
1600 } else {
1601 out << "writeString(" << name << ");";
1603 break;
1604 case t_base_type::TYPE_BOOL:
1605 out << "writeBool(" << name << ");";
1606 break;
1607 case t_base_type::TYPE_BYTE:
1608 out << "writeByte(" << name << ");";
1609 break;
1610 case t_base_type::TYPE_I16:
1611 out << "writeI16(" << name << ");";
1612 break;
1613 case t_base_type::TYPE_I32:
1614 out << "writeI32(" << name << ");";
1615 break;
1616 case t_base_type::TYPE_I64:
1617 out << "writeI64(" << name << ");";
1618 break;
1619 case t_base_type::TYPE_DOUBLE:
1620 out << "writeDouble(" << name << ");";
1621 break;
1622 default:
1623 throw "compiler error: no Java name for base type " + t_base_type::t_base_name(tbase);
1625 } else if (type->is_enum()) {
1626 out << "writeI32(" << name << ");";
1628 out << endl;
1629 } else {
1630 printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s%s' TYPE '%s'\n",
1631 prefix.c_str(),
1632 tfield->get_name().c_str(),
1633 type_name(type).c_str());
1638 * Serializes all the members of a struct.
1640 * @param tstruct The struct to serialize
1641 * @param prefix String prefix to attach to all fields
1643 void t_java_generator::generate_serialize_struct(ofstream& out,
1644 t_struct* tstruct,
1645 string prefix) {
1646 out <<
1647 indent() << prefix << ".write(oprot);" << endl;
1651 * Serializes a container by writing its size then the elements.
1653 * @param ttype The type of container
1654 * @param prefix String prefix for fields
1656 void t_java_generator::generate_serialize_container(ofstream& out,
1657 t_type* ttype,
1658 string prefix) {
1659 scope_up(out);
1661 if (ttype->is_map()) {
1662 indent(out) <<
1663 "oprot.writeMapBegin(new TMap(" <<
1664 type_to_enum(((t_map*)ttype)->get_key_type()) << ", " <<
1665 type_to_enum(((t_map*)ttype)->get_val_type()) << ", " <<
1666 prefix << ".size()));" << endl;
1667 } else if (ttype->is_set()) {
1668 indent(out) <<
1669 "oprot.writeSetBegin(new TSet(" <<
1670 type_to_enum(((t_set*)ttype)->get_elem_type()) << ", " <<
1671 prefix << ".size()));" << endl;
1672 } else if (ttype->is_list()) {
1673 indent(out) <<
1674 "oprot.writeListBegin(new TList(" <<
1675 type_to_enum(((t_list*)ttype)->get_elem_type()) << ", " <<
1676 prefix << ".size()));" << endl;
1679 string iter = tmp("_iter");
1680 if (ttype->is_map()) {
1681 indent(out) <<
1682 "for (" <<
1683 type_name(((t_map*)ttype)->get_key_type()) << " " << iter <<
1684 " : " <<
1685 prefix << ".keySet())";
1686 } else if (ttype->is_set()) {
1687 indent(out) <<
1688 "for (" <<
1689 type_name(((t_set*)ttype)->get_elem_type()) << " " << iter <<
1690 " : " <<
1691 prefix << ")";
1692 } else if (ttype->is_list()) {
1693 indent(out) <<
1694 "for (" <<
1695 type_name(((t_list*)ttype)->get_elem_type()) << " " << iter <<
1696 " : " <<
1697 prefix << ")";
1700 scope_up(out);
1702 if (ttype->is_map()) {
1703 generate_serialize_map_element(out, (t_map*)ttype, iter, prefix);
1704 } else if (ttype->is_set()) {
1705 generate_serialize_set_element(out, (t_set*)ttype, iter);
1706 } else if (ttype->is_list()) {
1707 generate_serialize_list_element(out, (t_list*)ttype, iter);
1710 if (ttype->is_map()) {
1711 indent(out) <<
1712 "oprot.writeMapEnd();" << endl;
1713 } else if (ttype->is_set()) {
1714 indent(out) <<
1715 "oprot.writeSetEnd();" << endl;
1716 } else if (ttype->is_list()) {
1717 indent(out) <<
1718 "oprot.writeListEnd();" << endl;
1721 scope_down(out);
1723 scope_down(out);
1727 * Serializes the members of a map.
1729 void t_java_generator::generate_serialize_map_element(ofstream& out,
1730 t_map* tmap,
1731 string iter,
1732 string map) {
1733 t_field kfield(tmap->get_key_type(), iter);
1734 generate_serialize_field(out, &kfield, "");
1735 t_field vfield(tmap->get_val_type(), map + ".get(" + iter + ")");
1736 generate_serialize_field(out, &vfield, "");
1740 * Serializes the members of a set.
1742 void t_java_generator::generate_serialize_set_element(ofstream& out,
1743 t_set* tset,
1744 string iter) {
1745 t_field efield(tset->get_elem_type(), iter);
1746 generate_serialize_field(out, &efield, "");
1750 * Serializes the members of a list.
1752 void t_java_generator::generate_serialize_list_element(ofstream& out,
1753 t_list* tlist,
1754 string iter) {
1755 t_field efield(tlist->get_elem_type(), iter);
1756 generate_serialize_field(out, &efield, "");
1760 * Returns a Java type name
1762 * @param ttype The type
1763 * @param container Is the type going inside a container?
1764 * @return Java type name, i.e. HashMap<Key,Value>
1766 string t_java_generator::type_name(t_type* ttype, bool in_container, bool in_init) {
1767 // In Java typedefs are just resolved to their real type
1768 ttype = get_true_type(ttype);
1770 if (ttype->is_base_type()) {
1771 return base_type_name((t_base_type*)ttype, in_container);
1772 } else if (ttype->is_enum()) {
1773 return (in_container ? "Integer" : "int");
1774 } else if (ttype->is_map()) {
1775 t_map* tmap = (t_map*) ttype;
1776 string prefix;
1777 if (in_init) {
1778 prefix = "HashMap";
1779 } else {
1780 prefix = "AbstractMap";
1782 return prefix + "<" +
1783 type_name(tmap->get_key_type(), true) + "," +
1784 type_name(tmap->get_val_type(), true) + ">";
1785 } else if (ttype->is_set()) {
1786 t_set* tset = (t_set*) ttype;
1787 return "HashSet<" + type_name(tset->get_elem_type(), true) + ">";
1788 } else if (ttype->is_list()) {
1789 t_list* tlist = (t_list*) ttype;
1790 return "ArrayList<" + type_name(tlist->get_elem_type(), true) + ">";
1793 // Check for namespacing
1794 t_program* program = ttype->get_program();
1795 if (program != NULL && program != program_) {
1796 string package = program->get_java_package();
1797 if (!package.empty()) {
1798 return package + "." + ttype->get_name();
1802 return ttype->get_name();
1806 * Returns the C++ type that corresponds to the thrift type.
1808 * @param tbase The base type
1809 * @param container Is it going in a Java container?
1811 string t_java_generator::base_type_name(t_base_type* type,
1812 bool in_container) {
1813 t_base_type::t_base tbase = type->get_base();
1815 switch (tbase) {
1816 case t_base_type::TYPE_VOID:
1817 return "void";
1818 case t_base_type::TYPE_STRING:
1819 if (type->is_binary()) {
1820 return "byte[]";
1821 } else {
1822 return "String";
1824 case t_base_type::TYPE_BOOL:
1825 return "boolean";
1826 case t_base_type::TYPE_BYTE:
1827 return "byte";
1828 case t_base_type::TYPE_I16:
1829 return (in_container ? "Short" : "short");
1830 case t_base_type::TYPE_I32:
1831 return (in_container ? "Integer" : "int");
1832 case t_base_type::TYPE_I64:
1833 return (in_container ? "Long" : "long");
1834 case t_base_type::TYPE_DOUBLE:
1835 return (in_container ? "Double" : "double");
1836 default:
1837 throw "compiler error: no C++ name for base type " + t_base_type::t_base_name(tbase);
1842 * Declares a field, which may include initialization as necessary.
1844 * @param ttype The type
1846 string t_java_generator::declare_field(t_field* tfield, bool init) {
1847 // TODO(mcslee): do we ever need to initialize the field?
1848 string result = type_name(tfield->get_type()) + " " + tfield->get_name();
1849 if (init) {
1850 t_type* ttype = get_true_type(tfield->get_type());
1851 if (ttype->is_base_type() && tfield->get_value() != NULL) {
1852 ofstream dummy;
1853 result += " = " + render_const_value(dummy, tfield->get_name(), ttype, tfield->get_value());
1854 } else if (ttype->is_base_type()) {
1855 t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base();
1856 switch (tbase) {
1857 case t_base_type::TYPE_VOID:
1858 throw "NO T_VOID CONSTRUCT";
1859 case t_base_type::TYPE_STRING:
1860 result += " = null";
1861 break;
1862 case t_base_type::TYPE_BOOL:
1863 result += " = false";
1864 break;
1865 case t_base_type::TYPE_BYTE:
1866 case t_base_type::TYPE_I16:
1867 case t_base_type::TYPE_I32:
1868 case t_base_type::TYPE_I64:
1869 result += " = 0";
1870 break;
1871 case t_base_type::TYPE_DOUBLE:
1872 result += " = (double)0";
1873 break;
1876 } else if (ttype->is_enum()) {
1877 result += " = 0";
1878 } else if (ttype->is_container()) {
1879 result += " = new " + type_name(ttype, false, true) + "()";
1880 } else {
1881 result += " = new " + type_name(ttype, false, true) + "()";;
1884 return result + ";";
1888 * Renders a function signature of the form 'type name(args)'
1890 * @param tfunction Function definition
1891 * @return String of rendered function definition
1893 string t_java_generator::function_signature(t_function* tfunction,
1894 string prefix) {
1895 t_type* ttype = tfunction->get_returntype();
1896 std::string result =
1897 type_name(ttype) + " " + prefix + tfunction->get_name() + "(" + argument_list(tfunction->get_arglist()) + ") throws ";
1898 t_struct* xs = tfunction->get_xceptions();
1899 const std::vector<t_field*>& xceptions = xs->get_members();
1900 vector<t_field*>::const_iterator x_iter;
1901 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
1902 result += type_name((*x_iter)->get_type(), false, false) + ", ";
1904 result += "TException";
1905 return result;
1909 * Renders a comma separated field list, with type names
1911 string t_java_generator::argument_list(t_struct* tstruct) {
1912 string result = "";
1914 const vector<t_field*>& fields = tstruct->get_members();
1915 vector<t_field*>::const_iterator f_iter;
1916 bool first = true;
1917 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1918 if (first) {
1919 first = false;
1920 } else {
1921 result += ", ";
1923 result += type_name((*f_iter)->get_type()) + " " + (*f_iter)->get_name();
1925 return result;
1929 * Converts the parse type to a C++ enum string for the given type.
1931 string t_java_generator::type_to_enum(t_type* type) {
1932 type = get_true_type(type);
1934 if (type->is_base_type()) {
1935 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1936 switch (tbase) {
1937 case t_base_type::TYPE_VOID:
1938 throw "NO T_VOID CONSTRUCT";
1939 case t_base_type::TYPE_STRING:
1940 return "TType.STRING";
1941 case t_base_type::TYPE_BOOL:
1942 return "TType.BOOL";
1943 case t_base_type::TYPE_BYTE:
1944 return "TType.BYTE";
1945 case t_base_type::TYPE_I16:
1946 return "TType.I16";
1947 case t_base_type::TYPE_I32:
1948 return "TType.I32";
1949 case t_base_type::TYPE_I64:
1950 return "TType.I64";
1951 case t_base_type::TYPE_DOUBLE:
1952 return "TType.DOUBLE";
1954 } else if (type->is_enum()) {
1955 return "TType.I32";
1956 } else if (type->is_struct() || type->is_xception()) {
1957 return "TType.STRUCT";
1958 } else if (type->is_map()) {
1959 return "TType.MAP";
1960 } else if (type->is_set()) {
1961 return "TType.SET";
1962 } else if (type->is_list()) {
1963 return "TType.LIST";
1966 throw "INVALID TYPE IN type_to_enum: " + type->get_name();
1970 * Emits a JavaDoc comment if the provided object has a doc in Thrift
1972 void t_java_generator::generate_java_doc(ofstream &out,
1973 t_doc* tdoc) {
1974 if (tdoc->has_doc()) {
1975 indent(out) << "/**" << endl;
1976 stringstream docs(tdoc->get_doc(), ios_base::in);
1977 while (!docs.eof()) {
1978 char line[1024];
1979 docs.getline(line, 1024);
1980 if (strlen(line) > 0 || !docs.eof()) { // skip the empty last line
1981 indent(out) << " * " << line << endl;
1984 indent(out) << " */" << endl;