From 322caa2f9289e8174069dbac1f8d7949e1130af6 Mon Sep 17 00:00:00 2001 From: T Jake Luciani Date: Mon, 15 Feb 2010 03:24:55 +0000 Subject: [PATCH] THRIFT-550: Added javascript support git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@910158 13f79535-47bb-0310-9956-ffa450edef68 --- compiler/cpp/Makefile.am | 3 + compiler/cpp/src/generate/t_js_generator.cc | 1477 +++++++++++++++++++ configure.ac | 2 + lib/js/README | 40 + lib/js/test/RunTestServer.sh | 40 + lib/js/test/src/test/Httpd.java | 298 ++++ lib/js/test/src/test/TestHandler.java | 123 ++ lib/js/test/test.html | 115 ++ lib/js/thrift.js | 671 +++++++++ test/ThriftTest.thrift | 1 + 10 files changed, 2770 insertions(+) create mode 100644 compiler/cpp/src/generate/t_js_generator.cc create mode 100644 lib/js/README create mode 100755 lib/js/test/RunTestServer.sh create mode 100644 lib/js/test/src/test/Httpd.java create mode 100644 lib/js/test/src/test/TestHandler.java create mode 100644 lib/js/test/test.html create mode 100644 lib/js/thrift.js diff --git a/compiler/cpp/Makefile.am b/compiler/cpp/Makefile.am index fa8d1cab..b1b6b01d 100644 --- a/compiler/cpp/Makefile.am +++ b/compiler/cpp/Makefile.am @@ -100,6 +100,9 @@ endif if THRIFT_GEN_html thrift_SOURCES += src/generate/t_html_generator.cc endif +if THRIFT_GEN_js +thrift_SOURCES += src/generate/t_js_generator.cc +endif thrift_CXXFLAGS = -Wall -I$(srcdir)/src $(BOOST_CPPFLAGS) thrift_LDFLAGS = -Wall $(BOOST_LDFLAGS) diff --git a/compiler/cpp/src/generate/t_js_generator.cc b/compiler/cpp/src/generate/t_js_generator.cc new file mode 100644 index 00000000..79be1252 --- /dev/null +++ b/compiler/cpp/src/generate/t_js_generator.cc @@ -0,0 +1,1477 @@ +/* + * 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. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include "platform.h" +using namespace std; + + +#include "t_oop_generator.h" + +/** + * JS code generator. + */ +class t_js_generator : public t_oop_generator { + public: + t_js_generator(t_program* program, + const std::map& parsed_options, + const std::string& option_string) : + t_oop_generator(program) { + + out_dir_base_ = "gen-js"; + } + + /** + * Init and close methods + */ + + void init_generator(); + void close_generator(); + + /** + * Program-level generation functions + */ + + void generate_typedef (t_typedef* ttypedef); + void generate_enum (t_enum* tenum); + void generate_const (t_const* tconst); + void generate_struct (t_struct* tstruct); + void generate_xception (t_struct* txception); + void generate_service (t_service* tservice); + + + std::string render_const_value(t_type* type, t_const_value* value); + + + /** + * Structs! + */ + void generate_js_struct(t_struct* tstruct, bool is_exception); + void generate_js_struct_definition(std::ofstream& out, t_struct* tstruct, bool is_xception=false); + void generate_js_struct_reader(std::ofstream& out, t_struct* tstruct); + void generate_js_struct_writer(std::ofstream& out, t_struct* tstruct); + void generate_js_function_helpers(t_function* tfunction); + + /** + * Service-level generation functions + */ + void generate_service_helpers (t_service* tservice); + void generate_service_interface (t_service* tservice); + void generate_service_rest (t_service* tservice); + void generate_service_client (t_service* tservice); + void generate_service_processor (t_service* tservice); + void generate_process_function (t_service* tservice, t_function* tfunction); + + /** + * Serialization constructs + */ + + void generate_deserialize_field (std::ofstream &out, + t_field* tfield, + std::string prefix="", + bool inclass=false); + + void generate_deserialize_struct (std::ofstream &out, + t_struct* tstruct, + std::string prefix=""); + + void generate_deserialize_container (std::ofstream &out, + t_type* ttype, + std::string prefix=""); + + void generate_deserialize_set_element (std::ofstream &out, + t_set* tset, + std::string prefix=""); + + void generate_deserialize_map_element (std::ofstream &out, + t_map* tmap, + std::string prefix=""); + + void generate_deserialize_list_element (std::ofstream &out, + t_list* tlist, + std::string prefix=""); + + void generate_serialize_field (std::ofstream &out, + t_field* tfield, + std::string prefix=""); + + void generate_serialize_struct (std::ofstream &out, + t_struct* tstruct, + std::string prefix=""); + + void generate_serialize_container (std::ofstream &out, + t_type* ttype, + std::string prefix=""); + + void generate_serialize_map_element (std::ofstream &out, + t_map* tmap, + std::string kiter, + std::string viter); + + void generate_serialize_set_element (std::ofstream &out, + t_set* tmap, + std::string iter); + + void generate_serialize_list_element (std::ofstream &out, + t_list* tlist, + std::string iter); + + /** + * Helper rendering functions + */ + + std::string js_includes(); + std::string declare_field(t_field* tfield, bool init=false, bool obj=false); + std::string function_signature(t_function* tfunction, std::string prefix=""); + std::string argument_list(t_struct* tstruct); + std::string type_to_enum(t_type* ttype); + + std::string autogen_comment() { + return + std::string("//\n") + + "// Autogenerated by Thrift\n" + + "//\n" + + "// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" + + "//\n"; + } + + std::vector js_namespace_pieces(t_program* p) { + std::string ns = p->get_namespace("js"); + + std::string::size_type loc; + std::vector pieces; + + if (ns.size() > 0) { + while ((loc = ns.find(".")) != std::string::npos) { + pieces.push_back(ns.substr(0, loc)); + ns = ns.substr(loc+1); + } + } + + if (ns.size() > 0) { + pieces.push_back(ns); + } + + return pieces; + } + + std::string js_namespace(t_program* p) { + std::string ns = p->get_namespace("js"); + if (ns.size() > 0) { + ns += "."; + } + + + return ns; + } + + private: + + /** + * File streams + */ + std::ofstream f_types_; + std::ofstream f_service_; +}; + + +/** + * Prepares for file generation by opening up the necessary file output + * streams. + * + * @param tprogram The program to generate + */ +void t_js_generator::init_generator() { + // Make output directory + MKDIR(get_out_dir().c_str()); + + string outdir = get_out_dir(); + + // Make output file + string f_types_name = outdir+program_->get_name()+"_types.js"; + f_types_.open(f_types_name.c_str()); + + // Print header + f_types_ << + autogen_comment() << + js_includes(); + + + string pns; + + //setup the namespace + vector ns_pieces = js_namespace_pieces( program_ ); + if( ns_pieces.size() > 0){ + f_types_ << "var " << ns_pieces[0] << " = {}"<get_program())<get_name()<<" = { "< constants = tenum->get_constants(); + vector::iterator c_iter; + int value = -1; + for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { + if ((*c_iter)->has_value()) { + value = (*c_iter)->get_value(); + } else { + ++value; + } + + if(c_iter != constants.begin()) + f_types_ << ","; + + f_types_ << "'" << (*c_iter)->get_name() << "' : " << value << endl; + } + + f_types_ << "}"<get_type(); + string name = tconst->get_name(); + t_const_value* value = tconst->get_value(); + + f_types_ << js_namespace(program_) << name << " = "; + f_types_ << render_const_value(type, value) << endl; +} + +/** + * Prints the value of a constant with the given type. Note that type checking + * is NOT performed in this function as it is always run beforehand using the + * validate_types method in main.cc + */ +string t_js_generator::render_const_value(t_type* type, t_const_value* value) { + std::ostringstream out; + + type = get_true_type(type); + + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_STRING: + out << "'" << value->get_string() << "'"; + break; + case t_base_type::TYPE_BOOL: + out << (value->get_integer() > 0 ? "true" : "false"); + break; + case t_base_type::TYPE_BYTE: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + out << value->get_integer(); + break; + case t_base_type::TYPE_DOUBLE: + if (value->get_type() == t_const_value::CV_INTEGER) { + out << value->get_integer(); + } else { + out << value->get_double(); + } + break; + default: + throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); + } + } else if (type->is_enum()) { + out << value->get_integer(); + } else if (type->is_struct() || type->is_xception()) { + out << "new " << js_namespace(type->get_program()) << type->get_name() << "({" << endl; + indent_up(); + const vector& fields = ((t_struct*)type)->get_members(); + vector::const_iterator f_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + t_type* field_type = NULL; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + if ((*f_iter)->get_name() == v_iter->first->get_string()) { + field_type = (*f_iter)->get_type(); + } + } + if (field_type == NULL) { + throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string(); + } + out << render_const_value(g_type_string, v_iter->first); + out << " : "; + out << render_const_value(field_type, v_iter->second); + out << ","; + } + + out << "})"; + } else if (type->is_map()) { + t_type* ktype = ((t_map*)type)->get_key_type(); + bool key_is_string = false; + if (ktype->is_base_type() && ((t_base_type*)ktype)->get_base() == t_base_type::TYPE_STRING){ + key_is_string = true; + } + + t_type* vtype = ((t_map*)type)->get_val_type(); + out << "{"; + + const map& val = value->get_map(); + map::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + + out << render_const_value(ktype, v_iter->first); + + out << " : "; + out << render_const_value(vtype, v_iter->second); + out << "," << endl; + } + + out << "}"; + } else if (type->is_list() || type->is_set()) { + t_type* etype; + if (type->is_list()) { + etype = ((t_list*)type)->get_elem_type(); + } else { + etype = ((t_set*)type)->get_elem_type(); + } + out << "["; + const vector& val = value->get_list(); + vector::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + + out << render_const_value(etype, *v_iter); + out << ","; + } + out << "]"; + } + return out.str(); +} + +/** + * Make a struct + */ +void t_js_generator::generate_struct(t_struct* tstruct) { + generate_js_struct(tstruct, false); +} + +/** + * Generates a struct definition for a thrift exception. Basically the same + * as a struct but extends the Exception class. + * + * @param txception The struct definition + */ +void t_js_generator::generate_xception(t_struct* txception) { + generate_js_struct(txception, true); +} + +/** + * Structs can be normal or exceptions. + */ +void t_js_generator::generate_js_struct(t_struct* tstruct, + bool is_exception) { + generate_js_struct_definition(f_types_, tstruct, is_exception); +} + +/** + * Generates a struct definition for a thrift data type. This is nothing in JS + * where the objects are all just associative arrays (unless of course we + * decide to start using objects for them...) + * + * @param tstruct The struct definition + */ +void t_js_generator::generate_js_struct_definition(ofstream& out, + t_struct* tstruct, + bool is_exception) { + const vector& members = tstruct->get_members(); + vector::const_iterator m_iter; + + out << js_namespace(tstruct->get_program()) << tstruct->get_name() <<" = function(args){\n"; + + + //members with arguments + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + string dval = declare_field(*m_iter,true,true); + t_type* t = get_true_type((*m_iter)->get_type()); + if ((*m_iter)->get_value() != NULL && !(t->is_struct() || t->is_xception())) { + dval = render_const_value((*m_iter)->get_type(), (*m_iter)->get_value()); + out << indent() << "this." << (*m_iter)->get_name() << " = " << dval << endl; + } else { + out << indent() << dval << endl; + } + + } + + // Generate constructor from array + if (members.size() > 0) { + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + t_type* t = get_true_type((*m_iter)->get_type()); + if ((*m_iter)->get_value() != NULL && (t->is_struct() || t->is_xception())) { + indent(out) << "this." << (*m_iter)->get_name() << " = " << render_const_value(t, (*m_iter)->get_value()) << endl; + } + } + + out << "if( args != null ){"; + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + out << indent() << "if (null != args." << (*m_iter)->get_name() << ")" <get_name() << " = args." << (*m_iter)->get_name() << endl ; + + } + + out << "}"; + + } + + indent_down(); + out << "}\n"; + + if (is_exception) { + out << "for (var property in Thrift.Exception)"<get_program())<get_name()<<"[property] = Thrift.Exception[property]"<get_program())<get_name() <<".prototype = {}\n"; + + + generate_js_struct_reader(out, tstruct); + generate_js_struct_writer(out, tstruct); + +} + +/** + * Generates the read() method for a struct + */ +void t_js_generator::generate_js_struct_reader(ofstream& out, + t_struct* tstruct) { + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + + out << js_namespace(tstruct->get_program())<get_name() << ".prototype.read = function(input){ "<get_key() << ":"; + indent(out) << "if (ftype == " << type_to_enum((*f_iter)->get_type()) << ") {" << endl; + + indent_up(); + generate_deserialize_field(out, *f_iter, "this."); + indent_down(); + + indent(out) << "} else {" << endl; + + indent(out) << " input.skip(ftype)" << endl; + + out << + indent() << "}" << endl << + indent() << "break" << endl; + + } + // In the default case we skip the field + indent(out) << "default:" << endl; + indent(out) << " input.skip(ftype)" << endl; + + scope_down(out); + + indent(out) << "input.readFieldEnd()" << endl; + + scope_down(out); + + indent(out) << "input.readStructEnd()" << endl; + + indent(out) << "return" << endl; + + indent_down(); + out << indent() << "}" << endl << endl; +} + +/** + * Generates the write() method for a struct + */ +void t_js_generator::generate_js_struct_writer(ofstream& out, + t_struct* tstruct) { + string name = tstruct->get_name(); + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + + out << js_namespace(tstruct->get_program())<< tstruct->get_name() << ".prototype.write = function(output){ "<get_name() << ") {" << endl; + indent_up(); + + indent(out) << + "output.writeFieldBegin(" << + "'" << (*f_iter)->get_name() << "', " << + type_to_enum((*f_iter)->get_type()) << ", " << + (*f_iter)->get_key() << ")" << endl; + + + // Write field contents + generate_serialize_field(out, *f_iter, "this."); + + indent(out) << + "output.writeFieldEnd()" << endl; + + indent_down(); + indent(out) << "}" << endl; + } + + + out << + indent() << "output.writeFieldStop()" << endl << + indent() << "output.writeStructEnd()" << endl; + + out < functions = tservice->get_functions(); + vector::iterator f_iter; + + f_service_ << + "//HELPER FUNCTIONS AND STRUCTURES" << endl << endl; + + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + t_struct* ts = (*f_iter)->get_arglist(); + string name = ts->get_name(); + ts->set_name(service_name_ + "_" + name); + generate_js_struct_definition(f_service_, ts, false); + generate_js_function_helpers(*f_iter); + ts->set_name(name); + } +} + +/** + * Generates a struct and helpers for a function. + * + * @param tfunction The function + */ +void t_js_generator::generate_js_function_helpers(t_function* tfunction) { + t_struct result(program_, service_name_ + "_" + tfunction->get_name() + "_result"); + t_field success(tfunction->get_returntype(), "success", 0); + if (!tfunction->get_returntype()->is_void()) { + result.append(&success); + } + + t_struct* xs = tfunction->get_xceptions(); + const vector& fields = xs->get_members(); + vector::const_iterator f_iter; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + result.append(*f_iter); + } + + generate_js_struct_definition(f_service_, &result, false); +} + +/** + * Generates a service interface definition. + * + * @param tservice The service to generate a header definition for + */ +void t_js_generator::generate_service_interface(t_service* tservice) { + +} + +/** + * Generates a REST interface + */ +void t_js_generator::generate_service_rest(t_service* tservice) { + +} + +/** + * Generates a service client definition. + * + * @param tservice The service to generate a server for. + */ +void t_js_generator::generate_service_client(t_service* tservice) { + string extends = ""; + + f_service_ << + js_namespace(tservice->get_program()) << service_name_ << "Client = function(input, output) {"<get_extends() != NULL) { + extends = tservice->get_extends()->get_name(); + + f_service_ << "for (var property in "<get_program()) << service_name_<<"Client[property] = "<get_program())< functions = tservice->get_functions(); + vector::const_iterator f_iter; + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + t_struct* arg_struct = (*f_iter)->get_arglist(); + const vector& fields = arg_struct->get_members(); + vector::const_iterator fld_iter; + string funname = (*f_iter)->get_name(); + + // Open function + f_service_ << js_namespace(tservice->get_program())<get_name(); + } + f_service_ << ")" << endl; + + if (!(*f_iter)->is_oneway()) { + f_service_ << indent(); + if (!(*f_iter)->get_returntype()->is_void()) { + f_service_ << "return "; + } + f_service_ << + "this.recv_" << funname << "()" << endl; + } + + indent_down(); + + f_service_ << "}" << endl << endl; + + f_service_ << js_namespace(tservice->get_program())<get_name() + "_args"; + + // Serialize the request header + f_service_ << + indent() << "this.output.writeMessageBegin('" << (*f_iter)->get_name() << "', Thrift.MessageType.CALL, this.seqid)" << endl; + + f_service_ << + indent() << "var args = new " << argsname << "()" << endl; + + for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { + f_service_ << + indent() << "args." << (*fld_iter)->get_name() << " = " << (*fld_iter)->get_name() << endl; + } + + // Write to the stream + f_service_ << + indent() << "args.write(this.output)" << endl << + indent() << "this.output.writeMessageEnd()" << endl << + indent() << "return this.output.getTransport().flush()" << endl; + + + indent_down(); + + f_service_ << "}" << endl; + + + if (!(*f_iter)->is_oneway()) { + std::string resultname = js_namespace(tservice->get_program()) + service_name_ + "_" + (*f_iter)->get_name() + "_result"; + t_struct noargs(program_); + + t_function recv_function((*f_iter)->get_returntype(), + string("recv_") + (*f_iter)->get_name(), + &noargs); + // Open function + f_service_ << + endl << js_namespace(tservice->get_program())<get_returntype()->is_void()) { + f_service_ << + indent() << "if (null != result.success ) {" << endl << + indent() << " return result.success" << endl << + indent() << "}" << endl; + } + + t_struct* xs = (*f_iter)->get_xceptions(); + const std::vector& xceptions = xs->get_members(); + vector::const_iterator x_iter; + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + f_service_ << + indent() << "if (null != result." << (*x_iter)->get_name() << ") {" << endl << + indent() << " throw result." << (*x_iter)->get_name() << endl << + indent() << "}" << endl; + } + + // Careful, only return _result if not a void function + if ((*f_iter)->get_returntype()->is_void()) { + indent(f_service_) << + "return" << endl; + } else { + f_service_ << + indent() << "throw \"" << (*f_iter)->get_name() << " failed: unknown result\"" << endl; + } + + // Close function + indent_down(); + f_service_ << "}"<get_type()); + + if (type->is_void()) { + throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " + + prefix + tfield->get_name(); + } + + string name = prefix+tfield->get_name(); + + if (type->is_struct() || type->is_xception()) { + generate_deserialize_struct(out, + (t_struct*)type, + name); + } else if (type->is_container()) { + generate_deserialize_container(out, type, name); + } else if (type->is_base_type() || type->is_enum()) { + indent(out) << "var rtmp = input."; + + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_VOID: + throw "compiler error: cannot serialize void field in a struct: " + + name; + break; + case t_base_type::TYPE_STRING: + out << "readString()"; + break; + case t_base_type::TYPE_BOOL: + out << "readBool()"; + break; + case t_base_type::TYPE_BYTE: + out << "readByte()"; + break; + case t_base_type::TYPE_I16: + out << "readI16()"; + break; + case t_base_type::TYPE_I32: + out << "readI32()"; + break; + case t_base_type::TYPE_I64: + out << "readI64()"; + break; + case t_base_type::TYPE_DOUBLE: + out << "readDouble()"; + break; + default: + throw "compiler error: no JS name for base type " + t_base_type::t_base_name(tbase); + } + } else if (type->is_enum()) { + out << "readI32()"; + } + out << endl; + + out <get_name().c_str(), type->get_name().c_str()); + } +} + +/** + * Generates an unserializer for a variable. This makes two key assumptions, + * first that there is a const char* variable named data that points to the + * buffer for deserialization, and that there is a variable protocol which + * is a reference to a TProtocol serialization object. + */ +void t_js_generator::generate_deserialize_struct(ofstream &out, + t_struct* tstruct, + string prefix) { + out << + indent() << prefix << " = new " << js_namespace(tstruct->get_program())<get_name() << "()" << endl << + indent() << prefix << ".read(input)" << endl; + +} + +void t_js_generator::generate_deserialize_container(ofstream &out, + t_type* ttype, + string prefix) { + scope_up(out); + + string size = tmp("_size"); + string ktype = tmp("_ktype"); + string vtype = tmp("_vtype"); + string etype = tmp("_etype"); + + t_field fsize(g_type_i32, size); + t_field fktype(g_type_byte, ktype); + t_field fvtype(g_type_byte, vtype); + t_field fetype(g_type_byte, etype); + + out << indent() << "var " << size << " = 0" << endl; + out << indent() << "var rtmp3" << endl; + + + // Declare variables, read header + if (ttype->is_map()) { + out << + indent() << prefix << " = {}" << endl << + indent() << "var " << ktype << " = 0" << endl << + indent() << "var " << vtype << " = 0" << endl; + + out << indent() << "rtmp3 = input.readMapBegin()" << endl; + out << indent() << ktype << "= rtmp3.ktype" << endl; + out << indent() << vtype << "= rtmp3.vtype" << endl; + out << indent() << size << "= rtmp3.size" << endl; + + + } else if (ttype->is_set()) { + + out << + indent() << prefix << " = []" << endl << + indent() << "var " << etype << " = 0" << endl << + indent() << "rtmp3 = input.readSetBegin()" << endl << + indent() << etype << "= rtmp3.etype"<is_list()) { + + out << + indent() << prefix << " = []" << endl << + indent() << "var " << etype << " = 0" << endl << + indent() << "rtmp3 = input.readListBegin()" << endl << + indent() << etype << " = rtmp3.etype"<is_map()) { + generate_deserialize_map_element(out, (t_map*)ttype, prefix); + } else if (ttype->is_set()) { + generate_deserialize_set_element(out, (t_set*)ttype, prefix); + } else if (ttype->is_list()) { + generate_deserialize_list_element(out, (t_list*)ttype, prefix); + } + + scope_down(out); + + + // Read container end + if (ttype->is_map()) { + indent(out) << "input.readMapEnd()" << endl; + } else if (ttype->is_set()) { + indent(out) << "input.readSetEnd()" << endl; + } else if (ttype->is_list()) { + indent(out) << "input.readListEnd()" << endl; + } + + scope_down(out); +} + + +/** + * Generates code to deserialize a map + */ +void t_js_generator::generate_deserialize_map_element(ofstream &out, + t_map* tmap, + string prefix) { + string key = tmp("key"); + string val = tmp("val"); + t_field fkey(tmap->get_key_type(), key); + t_field fval(tmap->get_val_type(), val); + + indent(out) << + declare_field(&fkey, true, false) << endl; + indent(out) << + declare_field(&fval, true, false) << endl; + + generate_deserialize_field(out, &fkey); + generate_deserialize_field(out, &fval); + + indent(out) << + prefix << "[" << key << "] = " << val << endl; +} + +void t_js_generator::generate_deserialize_set_element(ofstream &out, + t_set* tset, + string prefix) { + string elem = tmp("elem"); + t_field felem(tset->get_elem_type(), elem); + + indent(out) << + "var " << elem << " = null" << endl; + + generate_deserialize_field(out, &felem); + + indent(out) << + prefix << ".push(" << elem << ")" << endl; +} + +void t_js_generator::generate_deserialize_list_element(ofstream &out, + t_list* tlist, + string prefix) { + string elem = tmp("elem"); + t_field felem(tlist->get_elem_type(), elem); + + indent(out) << + "var " << elem << " = null" << endl; + + generate_deserialize_field(out, &felem); + + indent(out) << + prefix << ".push(" << elem << ")" << endl; +} + + +/** + * Serializes a field of any type. + * + * @param tfield The field to serialize + * @param prefix Name to prepend to field name + */ +void t_js_generator::generate_serialize_field(ofstream &out, + t_field* tfield, + string prefix) { + t_type* type = get_true_type(tfield->get_type()); + + // Do nothing for void types + if (type->is_void()) { + throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " + + prefix + tfield->get_name(); + } + + if (type->is_struct() || type->is_xception()) { + generate_serialize_struct(out, + (t_struct*)type, + prefix +tfield->get_name() ); + } else if (type->is_container()) { + generate_serialize_container(out, + type, + prefix + tfield->get_name()); + } else if (type->is_base_type() || type->is_enum()) { + + string name = tfield->get_name(); + + //Hack for when prefix is defined (always a hash ref) + if(!prefix.empty()) + name = prefix + tfield->get_name(); + + indent(out) << "output."; + + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_VOID: + throw + "compiler error: cannot serialize void field in a struct: " + name; + break; + case t_base_type::TYPE_STRING: + out << "writeString(" << name << ")"; + break; + case t_base_type::TYPE_BOOL: + out << "writeBool(" << name << ")"; + break; + case t_base_type::TYPE_BYTE: + out << "writeByte(" << name << ")"; + break; + case t_base_type::TYPE_I16: + out << "writeI16(" << name << ")"; + break; + case t_base_type::TYPE_I32: + out << "writeI32(" << name << ")"; + break; + case t_base_type::TYPE_I64: + out << "writeI64(" << name << ")"; + break; + case t_base_type::TYPE_DOUBLE: + out << "writeDouble(" << name << ")"; + break; + default: + throw "compiler error: no JS name for base type " + t_base_type::t_base_name(tbase); + } + } else if (type->is_enum()) { + out << "writeI32(" << name << ")"; + } + out << endl; + + } else { + printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s%s' TYPE '%s'\n", + prefix.c_str(), + tfield->get_name().c_str(), + type->get_name().c_str()); + } +} + +/** + * Serializes all the members of a struct. + * + * @param tstruct The struct to serialize + * @param prefix String prefix to attach to all fields + */ +void t_js_generator::generate_serialize_struct(ofstream &out, + t_struct* tstruct, + string prefix) { + indent(out) << prefix << ".write(output)" << endl; +} + +/** + * Writes out a container + */ +void t_js_generator::generate_serialize_container(ofstream &out, + t_type* ttype, + string prefix) { + scope_up(out); + + if (ttype->is_map()) { + indent(out) << + "output.writeMapBegin(" << + type_to_enum(((t_map*)ttype)->get_key_type()) << ", " << + type_to_enum(((t_map*)ttype)->get_val_type()) << ", " << + prefix << ".length)" << endl; + } else if (ttype->is_set()) { + indent(out) << + "output.writeSetBegin(" << + type_to_enum(((t_set*)ttype)->get_elem_type()) << ", " << + prefix << ".length)" << endl; + + } else if (ttype->is_list()) { + + indent(out) << + "output.writeListBegin(" << + type_to_enum(((t_list*)ttype)->get_elem_type()) << ", " << + prefix << ".length)" << endl; + + } + + scope_up(out); + + if (ttype->is_map()) { + string kiter = tmp("kiter"); + string viter = tmp("viter"); + indent(out) << "for(var "<is_set()) { + string iter = tmp("iter"); + indent(out) << + "for(var "<is_list()) { + string iter = tmp("iter"); + indent(out) << + "for(var "<is_map()) { + indent(out) << + "output.writeMapEnd()" << endl; + } else if (ttype->is_set()) { + indent(out) << + "output.writeSetEnd()" << endl; + } else if (ttype->is_list()) { + indent(out) << + "output.writeListEnd()" << endl; + } + + scope_down(out); +} + +/** + * Serializes the members of a map. + * + */ +void t_js_generator::generate_serialize_map_element(ofstream &out, + t_map* tmap, + string kiter, + string viter) { + t_field kfield(tmap->get_key_type(), kiter); + generate_serialize_field(out, &kfield); + + t_field vfield(tmap->get_val_type(), viter); + generate_serialize_field(out, &vfield); +} + +/** + * Serializes the members of a set. + */ +void t_js_generator::generate_serialize_set_element(ofstream &out, + t_set* tset, + string iter) { + t_field efield(tset->get_elem_type(), iter); + generate_serialize_field(out, &efield); +} + +/** + * Serializes the members of a list. + */ +void t_js_generator::generate_serialize_list_element(ofstream &out, + t_list* tlist, + string iter) { + t_field efield(tlist->get_elem_type(), iter); + generate_serialize_field(out, &efield); +} + +/** + * Declares a field, which may include initialization as necessary. + * + * @param ttype The type + */ +string t_js_generator::declare_field(t_field* tfield, bool init, bool obj) { + string result = "this." + tfield->get_name(); + + if(!obj){ + result = tfield->get_name(); + } + + if (init) { + t_type* type = get_true_type(tfield->get_type()); + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_VOID: + break; + case t_base_type::TYPE_STRING: + result += " = ''"; + break; + case t_base_type::TYPE_BOOL: + result += " = false"; + break; + case t_base_type::TYPE_BYTE: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + result += " = 0"; + break; + case t_base_type::TYPE_DOUBLE: + result += " = 0.0"; + break; + default: + throw "compiler error: no JS initializer for base type " + t_base_type::t_base_name(tbase); + } + } else if (type->is_enum()) { + result += " = 0"; + } else if (type->is_map()){ + result += " = {}"; + } else if (type->is_container()) { + result += " = []"; + } else if (type->is_struct() || type->is_xception()) { + if (obj) { + result += " = new " +js_namespace(type->get_program()) + type->get_name() + "()"; + } else { + result += " = null"; + } + } + } + return result; +} + +/** + * Renders a function signature of the form 'type name(args)' + * + * @param tfunction Function definition + * @return String of rendered function definition + */ +string t_js_generator::function_signature(t_function* tfunction, + string prefix) { + + string str; + + str = prefix + tfunction->get_name() + " = function("; + + + //Need to create js function arg inputs + const vector &fields = tfunction->get_arglist()->get_members(); + vector::const_iterator f_iter; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + + if(f_iter != fields.begin()) + str += ","; + + str += (*f_iter)->get_name(); + } + + + str += ")"; + return str; +} + +/** + * Renders a field list + */ +string t_js_generator::argument_list(t_struct* tstruct) { + string result = ""; + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + bool first = true; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + if (first) { + first = false; + } else { + result += ", "; + } + result += (*f_iter)->get_name(); + } + return result; +} + +/** + * Converts the parse type to a C++ enum string for the given type. + */ +string t_js_generator ::type_to_enum(t_type* type) { + type = get_true_type(type); + + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_VOID: + throw "NO T_VOID CONSTRUCT"; + case t_base_type::TYPE_STRING: + return "Thrift.Type.STRING"; + case t_base_type::TYPE_BOOL: + return "Thrift.Type.BOOL"; + case t_base_type::TYPE_BYTE: + return "Thrift.Type.BYTE"; + case t_base_type::TYPE_I16: + return "Thrift.Type.I16"; + case t_base_type::TYPE_I32: + return "Thrift.Type.I32"; + case t_base_type::TYPE_I64: + return "Thrift.Type.I64"; + case t_base_type::TYPE_DOUBLE: + return "Thrift.Type.DOUBLE"; + } + } else if (type->is_enum()) { + return "Thrift.Type.I32"; + } else if (type->is_struct() || type->is_xception()) { + return "Thrift.Type.STRUCT"; + } else if (type->is_map()) { + return "Thrift.Type.MAP"; + } else if (type->is_set()) { + return "Thrift.Type.SET"; + } else if (type->is_list()) { + return "Thrift.Type.LIST"; + } + + throw "INVALID TYPE IN type_to_enum: " + type->get_name(); +} + + +THRIFT_REGISTER_GENERATOR(js, "Javascript", ""); diff --git a/configure.ac b/configure.ac index a3b0b4b8..515e0b49 100644 --- a/configure.ac +++ b/configure.ac @@ -231,6 +231,8 @@ AX_THRIFT_GEN(xsd, [XSD], yes) AM_CONDITIONAL([THRIFT_GEN_xsd], [test "$ax_thrift_gen_xsd" = "yes"]) AX_THRIFT_GEN(html, [HTML], yes) AM_CONDITIONAL([THRIFT_GEN_html], [test "$ax_thrift_gen_html" = "yes"]) +AX_THRIFT_GEN(js, [JavaScript], yes) +AM_CONDITIONAL([THRIFT_GEN_js], [test "$ax_thrift_gen_js" = "yes"]) AC_CONFIG_HEADERS(config.h:config.hin) diff --git a/lib/js/README b/lib/js/README new file mode 100644 index 00000000..fafdc431 --- /dev/null +++ b/lib/js/README @@ -0,0 +1,40 @@ +Thrift Javascript Library + +License +======= + +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. + +Using Thrift with Javascript +===================== + +Allows javascript client interfaces to Thrift services. +This is geared for use in a web browser. + +This client can only speak the JSON Protocol and the only supported +transport is AJAX. + +There is a test httpd service in the test dir that requires +http://hc.apache.org under test dir + +Dependencies +============ +A JavaScript enabled browser. Tested with: + *IE 6,7,8 + *FF 2,3 + *Safari 3 & 4 diff --git a/lib/js/test/RunTestServer.sh b/lib/js/test/RunTestServer.sh new file mode 100755 index 00000000..574f7c5b --- /dev/null +++ b/lib/js/test/RunTestServer.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +# +# 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. +# + +LOG4J="../../java/build/ivy/lib/slf4j-api-1.5.8.jar:../../java/build/ivy/lib/log4j-1.2.15.jar:../../java/build/ivy/lib/slf4j-simple-1.5.8.jar" +HTTPCORE="./httpcore-4.0.1.jar" + +if [ -f ${HTTPCORE} ] +then + echo "compiling test..." +else + echo "Missing required file ${HTTPCORE}" + echo "You can download this from http://archive.apache.org/dist/httpcomponents/httpcore/binary/httpcomponents-core-4.0.1-bin.tar.gz" + echo "Place the jar in this directory and try again." + exit +fi + +../../../compiler/cpp/thrift --gen java ../../../test/ThriftTest.thrift +../../../compiler/cpp/thrift --gen js ../../../test/ThriftTest.thrift + +javac -cp ${LOG4J}:../../java/libthrift.jar gen-java/thrift/test/*.java +javac -cp ${LOG4J}:${HTTPCORE}:../../java/libthrift.jar:gen-java/ src/test/*.java +java -cp ${LOG4J}:${HTTPCORE}:../../java/libthrift.jar:gen-java:src test.Httpd ../ diff --git a/lib/js/test/src/test/Httpd.java b/lib/js/test/src/test/Httpd.java new file mode 100644 index 00000000..155a8b8b --- /dev/null +++ b/lib/js/test/src/test/Httpd.java @@ -0,0 +1,298 @@ +/* + * ==================================================================== + * 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 software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package test; + +import java.io.File; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URLDecoder; +import java.util.Locale; + +import org.apache.http.ConnectionClosedException; +import org.apache.http.HttpEntity; +import org.apache.http.HttpEntityEnclosingRequest; +import org.apache.http.HttpException; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.HttpServerConnection; +import org.apache.http.HttpStatus; +import org.apache.http.MethodNotSupportedException; +import org.apache.http.entity.ContentProducer; +import org.apache.http.entity.EntityTemplate; +import org.apache.http.entity.FileEntity; +import org.apache.http.impl.DefaultHttpResponseFactory; +import org.apache.http.impl.DefaultHttpServerConnection; +import org.apache.http.impl.NoConnectionReuseStrategy; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.CoreConnectionPNames; +import org.apache.http.params.CoreProtocolPNames; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.BasicHttpProcessor; +import org.apache.http.protocol.HttpContext; +import org.apache.http.protocol.HttpProcessor; +import org.apache.http.protocol.HttpRequestHandler; +import org.apache.http.protocol.HttpRequestHandlerRegistry; +import org.apache.http.protocol.HttpService; +import org.apache.http.util.EntityUtils; +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TJSONProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TMemoryBuffer; + +import thrift.test.ThriftTest; + +/** + * Basic, yet fully functional and spec compliant, HTTP/1.1 file server. + *

+ * Please note the purpose of this application is demonstrate the usage of + * HttpCore APIs. It is NOT intended to demonstrate the most efficient way of + * building an HTTP file server. + * + * + */ +public class Httpd { + + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.err.println("Please specify document root directory"); + System.exit(1); + } + Thread t = new RequestListenerThread(8088, args[0]); + t.setDaemon(false); + t.start(); + } + + static class HttpFileHandler implements HttpRequestHandler { + + private final String docRoot; + + public HttpFileHandler(final String docRoot) { + super(); + this.docRoot = docRoot; + } + + public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { + + String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); + if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { + throw new MethodNotSupportedException(method + " method not supported"); + } + String target = request.getRequestLine().getUri(); + + if (request instanceof HttpEntityEnclosingRequest && target.equals("/service")) { + HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); + byte[] entityContent = EntityUtils.toByteArray(entity); + System.out.println("Incoming content: " + new String(entityContent)); + + final String output = this.thriftRequest(entityContent); + + System.out.println("Outgoing content: "+output); + + EntityTemplate body = new EntityTemplate(new ContentProducer() { + + public void writeTo(final OutputStream outstream) throws IOException { + OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); + writer.write(output); + writer.flush(); + } + + }); + body.setContentType("text/html; charset=UTF-8"); + response.setEntity(body); + } else { + + final File file = new File(this.docRoot, URLDecoder.decode(target)); + if (!file.exists()) { + + response.setStatusCode(HttpStatus.SC_NOT_FOUND); + EntityTemplate body = new EntityTemplate(new ContentProducer() { + + public void writeTo(final OutputStream outstream) throws IOException { + OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); + writer.write("

"); + writer.write("File "); + writer.write(file.getPath()); + writer.write(" not found"); + writer.write("

"); + writer.flush(); + } + + }); + body.setContentType("text/html; charset=UTF-8"); + response.setEntity(body); + System.out.println("File " + file.getPath() + " not found"); + + } else if (!file.canRead() || file.isDirectory()) { + + response.setStatusCode(HttpStatus.SC_FORBIDDEN); + EntityTemplate body = new EntityTemplate(new ContentProducer() { + + public void writeTo(final OutputStream outstream) throws IOException { + OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); + writer.write("

"); + writer.write("Access denied"); + writer.write("

"); + writer.flush(); + } + + }); + body.setContentType("text/html; charset=UTF-8"); + response.setEntity(body); + System.out.println("Cannot read file " + file.getPath()); + + } else { + + response.setStatusCode(HttpStatus.SC_OK); + FileEntity body = new FileEntity(file, "text/html"); + response.setEntity(body); + System.out.println("Serving file " + file.getPath()); + + } + } + } + + private String thriftRequest(byte[] input){ + try{ + + //Input + TMemoryBuffer inbuffer = new TMemoryBuffer(input.length); + inbuffer.write(input); + TProtocol inprotocol = new TJSONProtocol(inbuffer); + + //Output + TMemoryBuffer outbuffer = new TMemoryBuffer(100); + TProtocol outprotocol = new TJSONProtocol(outbuffer); + + TProcessor processor = new ThriftTest.Processor(new TestHandler()); + processor.process(inprotocol, outprotocol); + + byte[] output = new byte[outbuffer.length()]; + outbuffer.readAll(output, 0, output.length); + + return new String(output,"UTF-8"); + }catch(Throwable t){ + return "Error:"+t.getMessage(); + } + + + } + + } + + static class RequestListenerThread extends Thread { + + private final ServerSocket serversocket; + private final HttpParams params; + private final HttpService httpService; + + public RequestListenerThread(int port, final String docroot) throws IOException { + this.serversocket = new ServerSocket(port); + this.params = new BasicHttpParams(); + this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 1000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) + .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) + .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); + + // Set up the HTTP protocol processor + HttpProcessor httpproc = new BasicHttpProcessor(); + + // Set up request handlers + HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); + reqistry.register("*", new HttpFileHandler(docroot)); + + // Set up the HTTP service + this.httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory()); + this.httpService.setParams(this.params); + this.httpService.setHandlerResolver(reqistry); + } + + public void run() { + System.out.println("Listening on port " + this.serversocket.getLocalPort()); + System.out.println("Point your browser to http://localhost:8088/test/test.html"); + + while (!Thread.interrupted()) { + try { + // Set up HTTP connection + Socket socket = this.serversocket.accept(); + DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); + System.out.println("Incoming connection from " + socket.getInetAddress()); + conn.bind(socket, this.params); + + // Start worker thread + Thread t = new WorkerThread(this.httpService, conn); + t.setDaemon(true); + t.start(); + } catch (InterruptedIOException ex) { + break; + } catch (IOException e) { + System.err.println("I/O error initialising connection thread: " + e.getMessage()); + break; + } + } + } + } + + static class WorkerThread extends Thread { + + private final HttpService httpservice; + private final HttpServerConnection conn; + + public WorkerThread(final HttpService httpservice, final HttpServerConnection conn) { + super(); + this.httpservice = httpservice; + this.conn = conn; + } + + public void run() { + System.out.println("New connection thread"); + HttpContext context = new BasicHttpContext(null); + try { + while (!Thread.interrupted() && this.conn.isOpen()) { + this.httpservice.handleRequest(this.conn, context); + } + } catch (ConnectionClosedException ex) { + System.err.println("Client closed connection"); + } catch (IOException ex) { + System.err.println("I/O error: " + ex.getMessage()); + } catch (HttpException ex) { + System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage()); + } finally { + try { + this.conn.shutdown(); + } catch (IOException ignore) { + } + } + } + + } + +} diff --git a/lib/js/test/src/test/TestHandler.java b/lib/js/test/src/test/TestHandler.java new file mode 100644 index 00000000..2eaf6c60 --- /dev/null +++ b/lib/js/test/src/test/TestHandler.java @@ -0,0 +1,123 @@ +package test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.thrift.TException; + +import thrift.test.Insanity; +import thrift.test.ThriftTest; +import thrift.test.Xception; +import thrift.test.Xception2; +import thrift.test.Xtruct; +import thrift.test.Xtruct2; +import thrift.test.Numberz; + +public class TestHandler implements ThriftTest.Iface { + + public byte testByte(byte thing) throws TException { + return thing; + } + + public double testDouble(double thing) throws TException { + return thing; + } + + public Numberz testEnum(Numberz thing) throws TException { + return thing; + } + + public void testException(String arg) throws Xception, TException { + throw new Xception(1,"server test exception"); + } + + public int testI32(int thing) throws TException { + return thing; + } + + public long testI64(long thing) throws TException { + return thing; + } + + public Map> testInsanity(Insanity argument) throws TException { + Map> result = new HashMap>(); + + result.put(Long.valueOf(1), new HashMap()); + result.get(Long.valueOf(1)).put(Numberz.ONE, argument); + + result.put(Long.valueOf(2), new HashMap()); + result.get(Long.valueOf(2)).put(Numberz.ONE, argument); + + return result; + } + + public List testList(List thing) throws TException { + return thing; + } + + public Map testMap(Map thing) throws TException { + return thing; + } + + public Map> testMapMap(int hello) throws TException { + Map> result = new HashMap>(); + + result.put(Integer.valueOf(1), new HashMap()); + result.get(Integer.valueOf(1)).put(Integer.valueOf(1), Integer.valueOf(1)); + result.get(Integer.valueOf(1)).put(Integer.valueOf(2), Integer.valueOf(2)); + result.get(Integer.valueOf(2)).put(Integer.valueOf(1), Integer.valueOf(1)); + + return result; + } + + public Xtruct testMulti(byte arg0, int arg1, long arg2, Map arg3, Numberz arg4, long arg5) throws TException { + Xtruct xtr = new Xtruct(); + + xtr.byte_thing = arg0; + xtr.i32_thing = arg1; + xtr.i64_thing = arg2; + xtr.string_thing = "server string"; + + return xtr; + } + + public Xtruct testMultiException(String arg0, String arg1) throws Xception, Xception2, TException { + Xtruct xtr = new Xtruct(); + xtr.setString_thing(arg0); + throw new Xception2(1,xtr); + } + + public Xtruct2 testNest(Xtruct2 thing) throws TException { + return thing; + } + + public void testOneway(int secondsToSleep) throws TException { + try{ + Thread.sleep(secondsToSleep * 1000); + }catch(InterruptedException e){ + + } + } + + public Set testSet(Set thing) throws TException { + return thing; + } + + public String testString(String thing) throws TException { + return thing; + } + + public Xtruct testStruct(Xtruct thing) throws TException { + return thing; + } + + public long testTypedef(long thing) throws TException { + return thing; + } + + public void testVoid() throws TException { + + } +} diff --git a/lib/js/test/test.html b/lib/js/test/test.html new file mode 100644 index 00000000..903ea401 --- /dev/null +++ b/lib/js/test/test.html @@ -0,0 +1,115 @@ + + + Thrift Javascript Bindings - Example + + + + + + + + + + + + + + + diff --git a/lib/js/thrift.js b/lib/js/thrift.js new file mode 100644 index 00000000..b70986f6 --- /dev/null +++ b/lib/js/thrift.js @@ -0,0 +1,671 @@ +/* + * 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. + */ +var Thrift = { + + Type : { + "STOP" : 0, + "VOID" : 1, + "BOOL" : 2, + "BYTE" : 3, + "I08" : 3, + "DOUBLE" : 4, + "I16" : 6, + "I32" : 8, + "I64" : 10, + "STRING" : 11, + "UTF7" : 11, + "STRUCT" : 12, + "MAP" : 13, + "SET" : 14, + "LIST" : 15, + "UTF8" : 16, + "UTF16" : 17 + }, + + MessageType : { + "CALL" : 1, + "REPLY" : 2, + "EXCEPTION" : 3 + } +} + +Thrift.TException = {} +Thrift.TException.prototype = { + initialize: function( message, code ) { + this.message = message; + this.code = (code == null) ? 0 : code; + } +} + + +Thrift.TApplicationException = { + "UNKNOWN" : 0, + "UNKNOWN_METHOD" : 1, + "INVALID_MESSAGE_TYPE" : 2, + "WRONG_METHOD_NAME" : 3, + "BAD_SEQUENCE_ID" : 4, + "MISSING_RESULT" : 5 +} + +Thrift.TApplicationException = function(message, code){ + this.message = message + this.code = (code == null) ? 0 : code +} + +Thrift.TApplicationException.prototype = { + + read : function(input){ + + var ftype + var fid + var ret = input.readStructBegin(fname) + + this.fname = ret.fname + + while(1){ + + ret = input.readFieldBegin() + + if(ret.ftype == TType.STOP) + break + + var fid = ret.fid + + switch(fid){ + case 1: + if( ret.ftype == Type.STRING ){ + ret = input.readString() + this.message = ret.value + } else { + ret = input.skip(ret.ftype) + } + + break + case 2: + if( ret.ftype == Type.I32 ){ + ret = input.readI32() + this.code = ret.value + } else { + ret = input.skip(ret.ftype) + } + break + + default: + ret = input.skip(ret.ftype) + break + } + + input.readFieldEnd() + + } + + input.readStructEnd() + + }, + + write: function(output){ + var xfer = 0; + + output.writeStructBegin('TApplicationException'); + + if (this.message) { + output.writeFieldBegin('message', Type.STRING, 1) + output.writeString(this.getMessage()) + output.writeFieldEnd() + } + + if (this.code) { + output.writeFieldBegin('type', Type.I32, 2) + output.writeI32(this.code) + output.writeFieldEnd() + } + + output.writeFieldStop() + output.writeStructEnd() + + }, + + getCode : function() { + return this.code + }, + + getMessage : function() { + return this.message + } +} + + + +/** + *If you do not specify a url then you must handle ajax on your own. + *This is how to use js bindings in a async fashion. + */ +Thrift.Transport = function(url){ + this.url = url + this.wpos = 0 + this.rpos = 0 + + this.send_buf = '' + this.recv_buf = '' +} + +Thrift.Transport.prototype = { + + //Gets the browser specific XmlHttpRequest Object + getXmlHttpRequestObject : function() { + + try { return new XMLHttpRequest() } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {} + try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {} + + throw "Your browser doesn't support the XmlHttpRequest object. Try upgrading to Firefox." + + }, + + flush : function(){ + + //async mode + if(this.url == undefined || this.url == '') + return this.send_buf; + + var xreq = this.getXmlHttpRequestObject() + + if (xreq.overrideMimeType) + xreq.overrideMimeType("application/json") + + xreq.open("POST", this.url, false) + xreq.send(this.send_buf) + + if (xreq.readyState != 4) + throw "encountered an unknown ajax ready state: "+xreq.readyState + + if (xreq.status != 200) + throw "encountered a unknown request status: "+xreq.status + + this.recv_buf = xreq.responseText + this.recv_buf_sz = this.recv_buf.length + this.wpos = this.recv_buf.length + this.rpos = 0 + }, + + setRecvBuffer : function(buf){ + this.recv_buf = buf + this.recv_buf_sz = this.recv_buf.length + this.wpos = this.recv_buf.length + this.rpos = 0 + }, + + isOpen : function() { + return true + }, + + open : function() {}, + + close: function() {}, + + read : function(len) { + var avail = this.wpos - this.rpos + + if(avail == 0) + return '' + + var give = len + + if(avail < len) + give = avail + + var ret = this.read_buf.substr(this.rpos,give) + this.rpos += give + + //clear buf when complete? + return ret + }, + + readAll : function() { + return this.recv_buf + }, + + write : function(buf){ + this.send_buf = buf + }, + + getSendBuffer : function(){ + return this.send_buf + } + +} + + + +Thrift.Protocol = function(transport){ + this.transport = transport +} + +Thrift.Protocol.Type = {} +Thrift.Protocol.Type[ Thrift.Type.BOOL ] = '"tf"' +Thrift.Protocol.Type[ Thrift.Type.BYTE ] = '"i8"' +Thrift.Protocol.Type[ Thrift.Type.I16 ] = '"i16"' +Thrift.Protocol.Type[ Thrift.Type.I32 ] = '"i32"' +Thrift.Protocol.Type[ Thrift.Type.I64 ] = '"i64"' +Thrift.Protocol.Type[ Thrift.Type.DOUBLE ] = '"dbl"' +Thrift.Protocol.Type[ Thrift.Type.STRUCT ] = '"rec"' +Thrift.Protocol.Type[ Thrift.Type.STRING ] = '"str"' +Thrift.Protocol.Type[ Thrift.Type.MAP ] = '"map"' +Thrift.Protocol.Type[ Thrift.Type.LIST ] = '"lst"' +Thrift.Protocol.Type[ Thrift.Type.SET ] = '"set"' + + +Thrift.Protocol.RType = {} +Thrift.Protocol.RType[ "tf" ] = Thrift.Type.BOOL +Thrift.Protocol.RType[ "i8" ] = Thrift.Type.BYTE +Thrift.Protocol.RType[ "i16"] = Thrift.Type.I16 +Thrift.Protocol.RType[ "i32"] = Thrift.Type.I32 +Thrift.Protocol.RType[ "i64"] = Thrift.Type.I64 +Thrift.Protocol.RType[ "dbl"] = Thrift.Type.DOUBLE +Thrift.Protocol.RType[ "rec"] = Thrift.Type.STRUCT +Thrift.Protocol.RType[ "str"] = Thrift.Type.STRING +Thrift.Protocol.RType[ "map"] = Thrift.Type.MAP +Thrift.Protocol.RType[ "lst"] = Thrift.Type.LIST +Thrift.Protocol.RType[ "set"] = Thrift.Type.SET + +Thrift.Protocol.Version = 1 + +Thrift.Protocol.prototype = { + + getTransport : function(){ + return this.transport + }, + + //Write functions + writeMessageBegin : function(name,messageType,seqid){ + this.tstack = new Array() + this.tpos = new Array(); + + this.tstack.push([Thrift.Protocol.Version,'"'+name+'"',messageType,seqid]); + }, + + writeMessageEnd : function(){ + var obj = this.tstack.pop() + + this.wobj = this.tstack.pop() + this.wobj.push(obj) + + this.wbuf = "["+this.wobj.join(",")+"]"; + + this.transport.write(this.wbuf); + }, + + + writeStructBegin : function(name){ + this.tpos.push(this.tstack.length) + this.tstack.push({}) + }, + + writeStructEnd : function(){ + + var p = this.tpos.pop() + var struct = this.tstack[p] + var str = "{" + var first = true + for( var key in struct ){ + if(first) + first = false; + else + str += ","; + + str += key+":"+struct[key] + } + + str += "}" + this.tstack[p] = str; + }, + + writeFieldBegin : function(name,fieldType,fieldId){ + this.tpos.push(this.tstack.length) + this.tstack.push({"fieldId" : '"'+fieldId+'"', "fieldType" : Thrift.Protocol.Type[fieldType]}); + + }, + + writeFieldEnd : function(){ + var value = this.tstack.pop() + var fieldInfo = this.tstack.pop() + + this.tstack[this.tstack.length-1][fieldInfo.fieldId] = "{"+fieldInfo.fieldType+":"+value+"}" + this.tpos.pop() + }, + + writeFieldStop : function(){ + //na + }, + + writeMapBegin : function(keyType,valType,size){ + //size is invalid, we'll set it on end. + this.tpos.push(this.tstack.length) + this.tstack.push([Thrift.Protocol.Type[keyType],Thrift.Protocol.Type[valType],0]) + }, + + writeMapEnd : function(){ + var p = this.tpos.pop() + + if(p == this.tstack.length) + return; + + if((this.tstack.length - p - 1) % 2 != 0) + this.tstack.push(""); + + var size = (this.tstack.length - p - 1)/2 + + this.tstack[p][this.tstack[p].length-1] = size; + + var map = "{" + var first = true + while( this.tstack.length > p+1 ){ + var v = this.tstack.pop() + var k = this.tstack.pop() + if(first){ + first = false + }else{ + map += "," + } + + map += '"'+k+'":'+v + } + map += "}" + + this.tstack[p].push(map) + this.tstack[p] = "["+this.tstack[p].join(",")+"]" + }, + + writeListBegin : function(elemType,size){ + this.tpos.push(this.tstack.length) + this.tstack.push([Thrift.Protocol.Type[elemType],size]); + }, + + writeListEnd : function(){ + var p = this.tpos.pop() + + while( this.tstack.length > p+1 ){ + this.tstack[p].push(this.tstack.pop()) + } + + this.tstack[p] = '['+this.tstack[p].join(",")+']'; + }, + + writeSetBegin : function(elemType,size){ + this.tpos.push(this.tstack.length) + this.tstack.push([Thrift.Protocol.Type[elemType],size]); + }, + + writeSetEnd : function(){ + var p = this.tpos.pop() + + while( this.tstack.length > p+1 ){ + this.tstack[p].push(this.tstack.pop()) + } + + this.tstack[p] = '['+this.tstack[p].join(",")+']'; + }, + + writeBool : function(value){ + this.tstack.push( value ? 1 : 0 ); + }, + + writeByte : function(i8){ + this.tstack.push(i8); + }, + + writeI16 : function(i16){ + this.tstack.push(i16); + }, + + writeI32 : function(i32){ + this.tstack.push(i32); + }, + + writeI64 : function(i64){ + this.tstack.push(i64); + }, + + writeDouble : function(dbl){ + this.tstack.push(dbl); + }, + + writeString : function(str){ + this.tstack.push('"'+encodeURIComponent(str)+'"'); + }, + + writeBinary : function(str){ + this.writeString(str); + }, + + + + // Reading functions + readMessageBegin : function(name, messageType, seqid){ + this.rstack = new Array() + this.rpos = new Array() + + this.robj = eval(this.transport.readAll()) + + var r = {} + var version = this.robj.shift() + + if(version != Thrift.Protocol.Version){ + throw "Wrong thrift protocol version: "+version + } + + r["fname"] = this.robj.shift() + r["mtype"] = this.robj.shift() + r["rseqid"] = this.robj.shift() + + + //get to the main obj + this.rstack.push(this.robj.shift()) + + return r + }, + + + readMessageEnd : function(){ + }, + + readStructBegin : function(name){ + var r = {}; + r["fname"] = ''; + + return r; + }, + + readStructEnd : function(){ + }, + + readFieldBegin : function(){ + var r = {}; + + var fid = -1 + var ftype = Thrift.Type.STOP + + //get a fieldId + for(var f in (this.rstack[this.rstack.length-1])){ + if(f == null) continue + + fid = parseInt(f) + this.rpos.push(this.rstack.length) + + var field = this.rstack[this.rstack.length-1][fid] + + //remove so we don't see it again + delete this.rstack[this.rstack.length-1][fid] + + this.rstack.push(field) + + break + } + + if(fid != -1){ + + //should only be 1 of these but this is the only + //way to match a key + for(var f in (this.rstack[this.rstack.length-1])){ + if(Thrift.Protocol.RType[f] == null ) continue + + ftype = Thrift.Protocol.RType[f] + this.rstack[this.rstack.length-1] = this.rstack[this.rstack.length-1][f] + } + } + + r["fname"] = '' + r["ftype"] = ftype + r["fid"] = fid + + + return r + }, + + readFieldEnd : function(){ + var pos = this.rpos.pop() + + //get back to the right place in the stack + while(this.rstack.length > pos) + this.rstack.pop(); + + }, + + readMapBegin : function(keyType,valType,size){ + + var map = this.rstack[this.rstack.length-1] + + var r = {}; + r["ktype"] = Thrift.Protocol.RType[map.shift()] + r["vtype"] = Thrift.Protocol.RType[map.shift()] + r["size"] = map.shift() + + + this.rpos.push(this.rstack.length) + this.rstack.push(map.shift()) + + return r; + }, + + readMapEnd : function(){ + this.readFieldEnd() + }, + + readListBegin : function(elemType,size){ + + var list = this.rstack[this.rstack.length-1] + + var r = {}; + r["etype"] = Thrift.Protocol.RType[list.shift()]; + r["size" ] = list.shift(); + + + this.rpos.push(this.rstack.length); + this.rstack.push(list.shift()) + + + return r; + }, + + readListEnd : function(){ + this.readFieldEnd() + }, + + readSetBegin : function(elemType,size){ + return this.readListBegin(elemType,size) + }, + + readSetEnd : function(){ + return this.readListEnd() + }, + + readBool : function(){ + var r = this.readI32() + + if( r != null && r["value"] == "1" ){ + r["value"] = true + }else{ + r["value"] = false + } + + return r + }, + + readByte : function(){ + return this.readI32() + }, + + readI16 : function(){ + return this.readI32() + }, + + + readI32 : function(){ + var f = this.rstack[this.rstack.length-1] + var r = {} + + if(f instanceof Array){ + r["value"] = f.pop() + + }else if(f instanceof Object){ + for(var i in f){ + if(i == null) continue + this.rstack.push(f[i]) + delete f[i] + + r["value"] = i + break + } + } else { + r["value"] = f + } + + + return r + }, + + readI64 : function(){ + return this.readI32() + }, + + readDouble : function(){ + return this.readI32() + }, + + readString : function(){ + var r = this.readI32() + r["value"] = decodeURIComponent(r["value"]) + + return r + }, + + readBinary : function(){ + return this.readString() + }, + + + //Method to arbitrarily skip over data. + skip : function(type){ + throw "skip not supported yet" + } + +} + + + diff --git a/test/ThriftTest.thrift b/test/ThriftTest.thrift index d25183be..919b68f1 100644 --- a/test/ThriftTest.thrift +++ b/test/ThriftTest.thrift @@ -26,6 +26,7 @@ namespace cpp thrift.test namespace rb Thrift.Test namespace perl ThriftTest namespace csharp Thrift.Test +namespace js ThriftTest /** * Docstring! -- 2.17.1