def __repr__(self): return "service %s%s {%s}" % ( self.name, self.extends is not None and (' ' + self.extends) or '', pad( "\n", "\n".join( indent(' ' * 4, (repr(function) + ';' for function in self.functions))), "\n"))
def __repr__(self): return "%sexception %s {%s}" % ( self.doc is not None and rpad(repr(self.doc), "\n") or '', self.name, pad( "\n", "\n".join( indent(' ' * 4, (repr(field) + ';' for field in self.fields))), "\n"))
def __repr__(self): return "service %s%s {%s}" % ( self.name, self.extends is not None and (' ' + self.extends) or '', pad("\n", "\n".join(indent(' ' * 4, (repr(function) + ';' for function in self.functions) )), "\n") )
def __repr__(self): return "%sexception %s {%s}" % ( self.doc is not None and rpad(repr(self.doc), "\n") or '', self.name, pad("\n", "\n".join(indent(' ' * 4, (repr(field) + ';' for field in self.fields) )), "\n") )
def _java_method_write(self): case_ttype_void = 'case VOID:' if len(self.fields) == 1: field = self.fields[0] from thryft.generators.java._java_container_type import _JavaContainerType from thryft.generators.java.java_struct_type import JavaStructType if isinstance(field.type, _JavaContainerType) or isinstance(field.type, JavaStructType): field_value_java_write_protocol = \ indent(' ' * 12, field.type.java_write_protocol(field.java_getter_name() + (field.required and '()' or '().get()'), depth=0)) field_thrift_ttype_name = field.type.thrift_ttype_name() case_ttype_void = """\ %(case_ttype_void)s { %(field_value_java_write_protocol)s break; } """ % locals() field_count = len(self.fields) field_write_protocols = \ lpad("\n\n", "\n\n".join(indent(' ' * 12, (field.java_write_protocol(depth=0, write_field=True) for field in self.fields) ))) field_value_write_protocols = \ pad("\n\n", "\n\n".join(indent(' ' * 12, (field.java_write_protocol(depth=0, write_field=False) for field in self.fields) )), "\n") name = self.java_name() return {'write': """\ @Override public void write(final org.thryft.protocol.OutputProtocol oprot) throws org.thryft.protocol.OutputProtocolException { write(oprot, org.thryft.protocol.Type.STRUCT); } public void write(final org.thryft.protocol.OutputProtocol oprot, final org.thryft.protocol.Type writeAsType) throws org.thryft.protocol.OutputProtocolException { switch (writeAsType) { %(case_ttype_void)s case LIST: oprot.writeListBegin(org.thryft.protocol.Type.VOID, %(field_count)u);%(field_value_write_protocols)s oprot.writeListEnd(); break; case STRUCT: default: oprot.writeStructBegin(\"%(name)s\");%(field_write_protocols)s oprot.writeFieldStop(); oprot.writeStructEnd(); break; } } """ % locals()}
def _dart_constructor_total(self): name = self.dart_name() parameters = pad('{', ', '.join(field.dart_parameter() for field in self.fields), '}') initializers = \ lpad(' : ', ', '.join( field.dart_initializer() for field in self.fields )) return """\ %(name)s(%(parameters)s)%(initializers)s;""" % locals()
def _cpp_method_write(self): case_ttype_void = 'case ::thryft::protocol::Type::VOID_:' if len(self.fields) == 1: field = self.fields[0] from thryft.generators.cpp._cpp_container_type import _CppContainerType from thryft.generators.cpp.cpp_struct_type import CppStructType if isinstance(field.type, _CppContainerType) or isinstance(field.type, CppStructType): field_value_cpp_write_protocol = \ indent(' ' * 4, field.type.cpp_write_protocol(field.cpp_getter_name() + (field.required and '()' or '().get()'))) case_ttype_void = """\ %(case_ttype_void)s %(field_value_cpp_write_protocol)s break; """ % locals() field_count = len(self.fields) field_write_protocols = \ lpad("\n\n", "\n\n".join(indent(' ' * 4, (field.cpp_write_protocol(write_field=True) for field in self.fields) ))) field_value_write_protocols = \ pad("\n\n", "\n\n".join(indent(' ' * 4, (field.cpp_write_protocol(write_field=False) for field in self.fields) )), "\n") name = self.cpp_name() return {'write': """\ void write(::thryft::protocol::OutputProtocol& oprot) const { write(oprot, ::thryft::protocol::Type::STRUCT); } void write(::thryft::protocol::OutputProtocol& oprot, ::thryft::protocol::Type as_type) const { switch (as_type) { %(case_ttype_void)s case ::thryft::protocol::Type::LIST: oprot.write_list_begin(::thryft::protocol::Type::VOID_, %(field_count)u);%(field_value_write_protocols)s oprot.write_list_end(); break; case ::thryft::protocol::Type::STRUCT: default: oprot.write_struct_begin();%(field_write_protocols)s oprot.write_field_stop(); oprot.write_struct_end(); break; } } """ % locals()}
def py_repr(self): name = self.py_name() enumerators = [] enumerator_placeholders = [] enumerator_qnames = [] value_of_statements = [] if len(self.enumerators) > 0: for enumerator in self.enumerators: enumerator_name = enumerator.name enumerator_value = enumerator.value enumerator_placeholders.append("%(enumerator_name)s = None" % locals()) enumerators.append( "%(name)s.%(enumerator_name)s = %(name)s('%(enumerator_name)s', %(enumerator_value)u)" % locals()) enumerator_qnames.append("%(name)s.%(enumerator_name)s" % locals()) value_of_statements.append("""\ if name == '%(enumerator_name)s' or name == '%(enumerator_value)u': return getattr(%(name)s, '%(enumerator_name)s') """ % locals()) enumerators = \ lpad("\n\n", "\n".join(enumerators)) enumerator_qnames = ', '.join(enumerator_qnames) enumerator_placeholders = \ pad("\n", "\n".join(indent(' ' * 4, enumerator_placeholders )), "\n") value_of_statements = \ lpad("\n", indent(' ' * 8, 'el'.join(value_of_statements))) return """\ class %(name)s(object):%(enumerator_placeholders)s def __init__(self, name, value): object.__init__(self) self.__name = name self.__value = value def __int__(self): return self.__value def __repr__(self): return self.__name def __str__(self): return self.__name @classmethod def value_of(cls, name):%(value_of_statements)s raise ValueError(name) @classmethod def values(cls): return (%(enumerator_qnames)s,)%(enumerators)s""" % locals()
def _java_constructor_copy(self): name = self.java_name() this_call = \ indent(' ' * 4, pad("\nthis(", ', '.join('other.' + field.java_getter_name() + '()' for field in self.fields), ");\n") ) return """\ public %(name)s(final %(name)s other) {%(this_call)s }""" % locals()
def _java_method_write_fields(self): field_write_protocols = \ pad("\n", "\n\n".join(indent(' ' * 4, (field.java_write_protocol(depth=0, write_field=True) for field in self.fields) )), "\n") qname = self.java_qname() return {'writeFields': """\ @Override public void writeFields(final org.thryft.protocol.OutputProtocol oprot) throws org.thryft.protocol.OutputProtocolException {%(field_write_protocols)s oprot.writeFieldStop(); }""" % locals()}
def _dart_constructor_total(self): name = self.dart_name() parameters = pad( '{', ', '.join(field.dart_parameter() for field in self.fields), '}') initializers = \ lpad(' : ', ', '.join( field.dart_initializer() for field in self.fields )) return """\ %(name)s(%(parameters)s)%(initializers)s;""" % locals()
def _cpp_operator_equality(self): field_comparisons = \ pad("\n", "\n\n".join(indent(' ' * 2, ("""\ if (!(%s() == other.%s())) { return false; }""")) % (field.cpp_getter_name(), field.cpp_getter_name()) for field in self.fields), "\n") name = self.cpp_name() return {'operator==': """\ bool operator==(const %(name)s& other) const {%(field_comparisons)s return true; }""" % locals()}
def __repr__(self): return "%senum %s {%s}" % ( self.doc is not None and rpad(self.doc, "\n") or '', self.name, pad( "\n", indent( ' ' * 4, ",\n".join("%s%s = %s" % ( enumerator.doc is not None and rpad(repr(enumerator.doc), "\n") or '', enumerator.name, enumerator.value, ) for enumerator in self.enumerators)), "\n"))
def __repr__(self): return "%senum %s {%s}" % ( self.doc is not None and rpad(self.doc, "\n") or '', self.name, pad("\n", indent(' ' * 4, ",\n".join( "%s%s = %s" % ( enumerator.doc is not None and rpad(repr(enumerator.doc), "\n") or '', enumerator.name, enumerator.value, ) for enumerator in self.enumerators )), "\n") )
def _java_method_write_as_list(self): field_count = len(self.fields) field_value_write_protocols = \ pad("\n\n", "\n\n".join(indent(' ' * 4, (field.java_write_protocol(depth=0, write_field=False) for field in self.fields) )), "\n") return {'writeAsList': """\ @Override public void writeAsList(final org.thryft.protocol.OutputProtocol oprot) throws org.thryft.protocol.OutputProtocolException { oprot.writeListBegin(org.thryft.protocol.Type.VOID_, %(field_count)u);%(field_value_write_protocols)s oprot.writeListEnd(); }""" % locals()}
def _java_method_compare_to(self): field_compare_tos = \ pad("\n\n int result;\n", "\n\n".join(indent(' ' * 4, \ (field.java_compare_to() for field in self.fields) )), "\n") name = self.java_name() return {'compareTo': """\ @Override public int compareTo(final %(name)s other) { if (other == null) { throw new NullPointerException(); }%(field_compare_tos)s return 0; }""" % locals()}
def py_repr(self): name = self.py_name() enumerators = [] enumerator_placeholders = [] enumerator_qnames = [] value_of_statements = [] if len(self.enumerators) > 0: for enumerator in self.enumerators: enumerator_name = enumerator.name enumerator_value = enumerator.value enumerator_placeholders.append("%(enumerator_name)s = None" % locals()) enumerators.append("%(name)s.%(enumerator_name)s = %(name)s('%(enumerator_name)s', %(enumerator_value)u)" % locals()) enumerator_qnames.append("%(name)s.%(enumerator_name)s" % locals()) value_of_statements.append("""\ if name == '%(enumerator_name)s' or name == '%(enumerator_value)u': return getattr(%(name)s, '%(enumerator_name)s') """ % locals()) enumerators = \ lpad("\n\n", "\n".join(enumerators)) enumerator_qnames = ', '.join(enumerator_qnames) enumerator_placeholders = \ pad("\n", "\n".join(indent(' ' * 4, enumerator_placeholders )), "\n") value_of_statements = \ lpad("\n", indent(' ' * 8, 'el'.join(value_of_statements))) return """\ class %(name)s(object):%(enumerator_placeholders)s def __init__(self, name, value): object.__init__(self) self.__name = name self.__value = value def __int__(self): return self.__value def __repr__(self): return self.__name def __str__(self): return self.__name @classmethod def value_of(cls, name):%(value_of_statements)s raise ValueError(name) @classmethod def values(cls): return (%(enumerator_qnames)s,)%(enumerators)s""" % locals()
def _java_method_set(self): if len(self.fields) == 0: return { 'set': """\ public Builder set(final String fieldThriftName, @javax.annotation.Nullable final java.lang.Object value) { throw new IllegalArgumentException(); } public Builder set(final org.thryft.Struct.FieldMetadata fieldMetadata, @javax.annotation.Nullable final java.lang.Object value) { throw new IllegalArgumentException(); }""" } cases = [] suppress_warnings = [] for field in self.fields: cases.extend(field.java_set_case()) for suppress_warning in field.java_set_suppress_warnings(): if not suppress_warning in suppress_warnings: suppress_warnings.append(suppress_warning) suppress_warnings = pad( "@SuppressWarnings({", ', '.join('"%s"' % suppress_warning for suppress_warning in suppress_warnings), "})\n") cases = lpad("\n", "\n".join(indent(' ' * 4, cases))) return { 'set': """\ public Builder set(final String fieldThriftName, @javax.annotation.Nullable final java.lang.Object value) { return set(FieldMetadata.valueOfThriftName(fieldThriftName), value); } public Builder set(final org.thryft.Struct.FieldMetadata fieldMetadata, @javax.annotation.Nullable final java.lang.Object value) { if (!(fieldMetadata instanceof FieldMetadata)) { throw new IllegalArgumentException(); } return set((FieldMetadata)fieldMetadata, value); } %(suppress_warnings)spublic Builder set(final FieldMetadata fieldMetadata, @javax.annotation.Nullable final java.lang.Object value) { com.google.common.base.Preconditions.checkNotNull(fieldMetadata); switch (fieldMetadata) {%(cases)s default: throw new IllegalStateException(); } }""" % locals() }
def _java_method_write_fields(self): field_write_protocols = \ pad("\n", "\n\n".join(indent(' ' * 4, (field.java_write_protocol(depth=0, write_field=True) for field in self.fields) )), "\n") qname = self.java_qname() return { 'writeFields': """\ @Override public void writeFields(final org.thryft.protocol.OutputProtocol oprot) throws org.thryft.protocol.OutputProtocolException {%(field_write_protocols)s oprot.writeFieldStop(); }""" % locals() }
def _java_method_write_as_list(self): field_count = len(self.fields) field_value_write_protocols = \ pad("\n\n", "\n\n".join(indent(' ' * 4, (field.java_write_protocol(depth=0, write_field=False) for field in self.fields) )), "\n") return { 'writeAsList': """\ @Override public void writeAsList(final org.thryft.protocol.OutputProtocol oprot) throws org.thryft.protocol.OutputProtocolException { oprot.writeListBegin(org.thryft.protocol.Type.VOID_, %(field_count)u);%(field_value_write_protocols)s oprot.writeListEnd(); }""" % locals() }
def java_repr(self): annotations = pad("\n", "\n".join(self._java_annotations()), "\n") extends = self._java_extends() extends = ' extends ' + extends if extends is not None else '' implements = lpad(' implements ', ', '.join(self._java_implements())) javadoc = self.java_doc() name = self.java_name() sections = lpad("\n", "\n\n".join(indent(' ' * 4, self._java_repr_sections()))) return """\ %(javadoc)s%(annotations)spublic interface %(name)s%(extends)s%(implements)s {%(sections)s }""" % locals()
def py_repr(self): enumerators = [] enumerator_placeholders = [] enumerator_qnames = [] for field in self.__py_compound_type.fields: field_name = field.name field_type = field.type.py_qname() field_validation = None for annotation in field.annotations: if annotation.name == "validation": field_validation = pformat(annotation.value) break enumerator_name = field.name.upper() enumerator_placeholders.append("%(enumerator_name)s = None" % locals()) enumerators.append( "FieldMetadata.%(enumerator_name)s = FieldMetadata('%(field_name)s', %(field_type)s, %(field_validation)s)" % locals() ) enumerator_qnames.append("cls.%(enumerator_name)s" % locals()) enumerators = lpad("\n\n", "\n".join(enumerators)) enumerator_qnames = ", ".join(enumerator_qnames) enumerator_placeholders = pad("\n", "\n".join(indent(" " * 4, enumerator_placeholders)), "\n") return ( """\ class FieldMetadata(object):%(enumerator_placeholders)s def __init__(self, name, type_, validation): object.__init__(self) self.__name = name self.__type = type_ self.__validation = validation def __repr__(self): return self.__name @property def type(self): return self.__type @property def validation(self): return self.__validation @classmethod def values(cls): return (%(enumerator_qnames)s,)%(enumerators)s""" % locals() )
def _java_method_compare_to(self): field_compare_tos = \ pad("\n\n int result;\n", "\n\n".join(indent(' ' * 4, \ (field.java_compare_to() for field in self.fields) )), "\n") name = self.java_name() return { 'compareTo': """\ @Override public int compareTo(final %(name)s other) { if (other == null) { throw new NullPointerException(); }%(field_compare_tos)s return 0; }""" % locals() }
def _java_method_read_as_list(self): body = indent(' ' * 4, self._java_method_read_as_list_body()) constructor_parameters = ', '.join(["DefaultReadValidator.getInstance().%s(%s)" % (field.java_validate_method_name(), field.java_name()) for field in self.fields] + \ ['NopConstructionValidator.getInstance()'])\ if len(self.fields) > 0 else '' field_declarations = \ pad("\n", indent(' ' * 4, "\n".join( field.java_local_declaration(final=False) for field in self.fields )), "\n") name = self.java_name() return {'readAsList': """\ public static %(name)s readAsList(final org.thryft.protocol.InputProtocol iprot) throws org.thryft.protocol.InputProtocolException {%(field_declarations)s %(body)s return new %(name)s(%(constructor_parameters)s); }""" % locals()}
def py_repr(self): enumerators = [] enumerator_placeholders = [] enumerator_qnames = [] for field in self.__py_compound_type.fields: field_name = field.name field_type = field.type.py_qname() field_validation = None for annotation in field.annotations: if annotation.name == 'validation': field_validation = pformat(annotation.value) break enumerator_name = field.name.upper() enumerator_placeholders.append("%(enumerator_name)s = None" % locals()) enumerators.append("FieldMetadata.%(enumerator_name)s = FieldMetadata('%(field_name)s', %(field_type)s, %(field_validation)s)" % locals()) enumerator_qnames.append("cls.%(enumerator_name)s" % locals()) enumerators = \ lpad("\n\n", "\n".join(enumerators)) enumerator_qnames = ', '.join(enumerator_qnames) enumerator_placeholders = \ pad("\n", "\n".join(indent(' ' * 4, enumerator_placeholders )), "\n") return """\ class FieldMetadata(object):%(enumerator_placeholders)s def __init__(self, name, type_, validation): object.__init__(self) self.__name = name self.__type = type_ self.__validation = validation def __repr__(self): return self.__name @property def type(self): return self.__type @property def validation(self): return self.__validation @classmethod def values(cls): return (%(enumerator_qnames)s,)%(enumerators)s""" % locals()
def _java_constructor_copy(self): name = self.java_name() if len(self.fields) > 0: this_call = \ indent(' ' * 4, pad("\nthis(", ', '.join(['other.' + field.java_getter_name() + '()' for field in self.fields] + \ ['NopConstructionValidator.getInstance()']), ");\n") ) else: this_call = '' return """\ /** * Copy constructor */ public %(name)s(final %(name)s other) {%(this_call)s }""" % locals()
def py_public_delegating_definition(self): name = self.py_name() parameters = ', '.join(['self'] + self.py_parameters()) parameter_checks = \ pad("\n", "\n".join(indent(' ' * 4, (parameter.py_check() for parameter in self.parameters) )), "\n") call = ', '.join("%s=%s" % (parameter.py_name(), parameter.py_name()) for parameter in self.parameters) if self.return_field is not None: return_value = name + '_return_value' while True: renamed_return_value = False for parameter in self.parameters: if parameter.name == return_value: return_value += '_' renamed_return_value = True break if not renamed_return_value: break return_prefix = return_value + ' = ' return_suffix = [] return_type_check = self.return_field.type.py_check(return_value) return_suffix.append("""\ if not %(return_type_check)s: raise TypeError(getattr(__builtin__, 'type')(%(return_value)s))""" % locals()) return_suffix.append('return ' + return_value) return_suffix = "\n\n" + "\n\n".join(indent( ' ' * 4, return_suffix)) else: return_prefix = return_suffix = '' return """\ def %(name)s(%(parameters)s):%(parameter_checks)s %(return_prefix)sself._%(name)s(%(call)s)%(return_suffix)s """ % locals()
def _java_method_read_as_list(self): body = indent(' ' * 4, self._java_method_read_as_list_body()) constructor_parameters = ', '.join(["DefaultReadValidator.getInstance().%s(%s)" % (field.java_validate_method_name(), field.java_name()) for field in self.fields] + \ ['NopConstructionValidator.getInstance()'])\ if len(self.fields) > 0 else '' field_declarations = \ pad("\n", indent(' ' * 4, "\n".join( field.java_local_declaration(final=False) for field in self.fields )), "\n") name = self.java_name() return { 'readAsList': """\ public static %(name)s readAsList(final org.thryft.protocol.InputProtocol iprot) throws org.thryft.protocol.InputProtocolException {%(field_declarations)s %(body)s return new %(name)s(%(constructor_parameters)s); }""" % locals() }
def _java_method_set(self): if len(self.fields) == 0: return {'set': """\ public Builder set(final String fieldThriftName, @javax.annotation.Nullable final java.lang.Object value) { throw new IllegalArgumentException(); } public Builder set(final org.thryft.Struct.FieldMetadata fieldMetadata, @javax.annotation.Nullable final java.lang.Object value) { throw new IllegalArgumentException(); }"""} cases = [] suppress_warnings = [] for field in self.fields: cases.extend(field.java_set_case()) for suppress_warning in field.java_set_suppress_warnings(): if not suppress_warning in suppress_warnings: suppress_warnings.append(suppress_warning) suppress_warnings = pad("@SuppressWarnings({", ', '.join('"%s"' % suppress_warning for suppress_warning in suppress_warnings), "})\n") cases = lpad("\n", "\n".join(indent(' ' * 4, cases))) return {'set': """\ public Builder set(final String fieldThriftName, @javax.annotation.Nullable final java.lang.Object value) { return set(FieldMetadata.valueOfThriftName(fieldThriftName), value); } public Builder set(final org.thryft.Struct.FieldMetadata fieldMetadata, @javax.annotation.Nullable final java.lang.Object value) { if (!(fieldMetadata instanceof FieldMetadata)) { throw new IllegalArgumentException(); } return set((FieldMetadata)fieldMetadata, value); } %(suppress_warnings)spublic Builder set(final FieldMetadata fieldMetadata, @javax.annotation.Nullable final java.lang.Object value) { com.google.common.base.Preconditions.checkNotNull(fieldMetadata); switch (fieldMetadata) {%(cases)s default: throw new IllegalStateException(); } }""" % locals()}
def __java_function_metadata_enum(self): if len(self.functions) == 0: return None enumerators = [] for function in self.functions: function_thrift_name = function.name enumerator_name = function.name.upper() enumerators.append("%(enumerator_name)s(\"%(function_thrift_name)s\")" % locals()) enumerators = pad("\n", indent(' ' * 4, ",\n".join(enumerators)), ";\n") return """\ public enum FunctionMetadata {%(enumerators)s public String getThriftName() { return thriftName; } private FunctionMetadata(final String thriftName) { this.thriftName = thriftName; } private final String thriftName; }""" % locals()
def py_public_delegating_definition(self): name = self.py_name() parameters = ', '.join(['self'] + self.py_parameters()) parameter_checks = \ pad("\n", "\n".join(indent(' ' * 4, (parameter.py_check() for parameter in self.parameters) )), "\n") call = ', '.join("%s=%s" % (parameter.py_name(), parameter.py_name()) for parameter in self.parameters) if self.return_field is not None: return_value = name + '_return_value' while True: renamed_return_value = False for parameter in self.parameters: if parameter.name == return_value: return_value += '_' renamed_return_value = True break if not renamed_return_value: break return_prefix = return_value + ' = ' return_suffix = [] return_type_check = self.return_field.type.py_check(return_value) return_suffix.append("""\ if not %(return_type_check)s: raise TypeError(getattr(__builtin__, 'type')(%(return_value)s))""" % locals()) return_suffix.append('return ' + return_value) return_suffix = "\n\n" + "\n\n".join(indent(' ' * 4, return_suffix)) else: return_prefix = return_suffix = '' return """\ def %(name)s(%(parameters)s):%(parameter_checks)s %(return_prefix)sself._%(name)s(%(call)s)%(return_suffix)s """ % locals()
def _cpp_operator_equality(self): name = self.cpp_name() if len(self.fields) == 0: return { 'operator==': """\ bool operator==(const %(name)s&) const { return true; }""" % locals() } field_comparisons = \ pad("\n", "\n\n".join(indent(' ' * 2, ("""\ if (!(%s() == other.%s())) { return false; }""")) % (field.cpp_getter_name(), field.cpp_getter_name()) for field in self.fields), "\n") return { 'operator==': """\ bool operator==(const %(name)s& other) const {%(field_comparisons)s return true; }""" % locals() }
def ts_repr(self): for parameter in self.parameters: assert parameter.name != 'error', self.parent.name assert parameter.name != 'success', self.parent.name name = self.name ts_name = self.ts_name() parameters = [parameter.ts_parameter() for parameter in self.parameters] async_call_setup = [] sync_call_setup = [] if len(self.parameters) > 0: parameters_to_json = [] for parameter in self.parameters: parameter_json_name = parameter.name parameter_ts_name = parameter.ts_name() if parameter.id is not None: parameter_json_name = str(parameter.id) + ':' + parameter_json_name parameter_to_json = """__jsonrpc_params["%(parameter_json_name)s"] = """ % locals() + parameter.type.ts_to_json("kwds.%(parameter_ts_name)s" % locals()) + ';' if not parameter.required: parameter_to_json = indent(' ' * 4, parameter_to_json) parameter_to_json = """\ if (typeof kwds.%(parameter_ts_name)s !== "undefined") { %(parameter_to_json)s }""" parameters_to_json.append(parameter_to_json) parameters_to_json = "\n".join(parameters_to_json) jsonrpc_params_setup = """\ var __jsonrpc_params: {[index: string]: any} = {}; %(parameters_to_json)s """ % locals() async_call_setup.append(jsonrpc_params_setup) sync_call_setup.append(jsonrpc_params_setup) jsonrpc_params = '__jsonrpc_params' else: jsonrpc_params = '{}' async_parameters = list(parameters) async_parameters.append('error: (jqXHR: JQueryXHR, textStatus: string, errorThrown: string) => any') if self.return_field is not None: return_field_parameter = self.return_field.ts_parameter() async_parameters.append('success: (%(return_field_parameter)s) => void' % locals()) return_value = self.return_field.type.ts_from_json('__response.result') sync_return_type_qname = self.return_field.type.ts_qname() sync_call_setup.append("var returnValue: %(sync_return_type_qname)s = null;" % locals()) sync_return = "\n\n return returnValue;" sync_return_value_assignment = indent(' ' * 12, """\ if (typeof __response.result !== "undefined") { returnValue = %(return_value)s; } else { throw new Error(__response.error); }""" % locals()) else: async_parameters.append('success: () => void') return_value = '' sync_return = '' sync_return_type_qname = 'void' sync_return_value_assignment = indent(' ' * 12, """\ if (typeof __response.result === "undefined") { throw new Error(__response.error); }""" % locals()) async_call_setup = pad("\n", indent(' ' * 4, "\n".join(async_call_setup)), "\n") async_parameters = "kwds: {%s}" % ', '.join(async_parameters) sync_call_setup = pad("\n", indent(' ' * 4, "\n".join(sync_call_setup)), "\n") sync_parameters = "kwds: {%s}" % ', '.join(parameters) if len(parameters) > 0 else '' jsonrpc_url = '\'/api/jsonrpc/' if self.parent.name.endswith('Service'): jsonrpc_url += '_'.join(decamelize(self.parent.name).split('_')[:-1]) else: jsonrpc_url += decamelize(self.parent.name) jsonrpc_url += '\'' return """\ %(ts_name)sAsync(%(async_parameters)s): void {%(async_call_setup)s $.ajax({ async:true, data:JSON.stringify({ jsonrpc:'2.0', method:'%(name)s', params:%(jsonrpc_params)s, id:'1234' }), dataType:'json', error:function(jqXHR, textStatus, errorThrown) { kwds.error(jqXHR, textStatus, errorThrown); }, mimeType:'application/json', type:'POST', success:function(__response) { if (typeof __response.result !== "undefined") { kwds.success(%(return_value)s); } else { kwds.error(null, __response.error.message, null); } }, url:%(jsonrpc_url)s, }); } %(ts_name)sSync(%(sync_parameters)s): %(sync_return_type_qname)s {%(sync_call_setup)s $.ajax({ async:false, data:JSON.stringify({ jsonrpc:'2.0', method:'%(name)s', params:%(jsonrpc_params)s, id:'1234' }), dataType:'json', error:function(jqXHR, textStatus, errorThrown) { throw new Error(errorThrown); }, mimeType:'application/json', type:'POST', success:function(__response) { %(sync_return_value_assignment)s }, url:%(jsonrpc_url)s, });%(sync_return)s }""" % locals()
def _java_method_write(self): case_ttype_void = 'case VOID:' if len(self.fields) == 1: field = self.fields[0] from thryft.generators.java._java_container_type import _JavaContainerType from thryft.generators.java.java_struct_type import JavaStructType if isinstance(field.type, _JavaContainerType) or isinstance( field.type, JavaStructType): field_value_java_write_protocol = \ indent(' ' * 12, field.type.java_write_protocol(field.java_getter_name() + (field.required and '()' or '().get()'), depth=0)) field_thrift_ttype_name = field.type.thrift_ttype_name() case_ttype_void = """\ %(case_ttype_void)s { %(field_value_java_write_protocol)s break; } """ % locals() field_count = len(self.fields) field_write_protocols = \ lpad("\n\n", "\n\n".join(indent(' ' * 12, (field.java_write_protocol(depth=0, write_field=True) for field in self.fields) ))) field_value_write_protocols = \ pad("\n\n", "\n\n".join(indent(' ' * 12, (field.java_write_protocol(depth=0, write_field=False) for field in self.fields) )), "\n") name = self.java_name() return { 'write': """\ @Override public void write(final org.thryft.protocol.OutputProtocol oprot) throws org.thryft.protocol.OutputProtocolException { write(oprot, org.thryft.protocol.Type.STRUCT); } public void write(final org.thryft.protocol.OutputProtocol oprot, final org.thryft.protocol.Type writeAsType) throws org.thryft.protocol.OutputProtocolException { switch (writeAsType) { %(case_ttype_void)s case LIST: oprot.writeListBegin(org.thryft.protocol.Type.VOID, %(field_count)u);%(field_value_write_protocols)s oprot.writeListEnd(); break; case STRUCT: default: oprot.writeStructBegin(\"%(name)s\");%(field_write_protocols)s oprot.writeFieldStop(); oprot.writeStructEnd(); break; } } """ % locals() }
def java_repr(self): enumerators = [] java_name_cases = [] thrift_name_cases = [] for field in self.__java_compound_type.fields: enumerators.append(field.java_field_metadata_enumerator_declaration()) java_name_cases.append(field.java_field_metadata_value_of_java_name_case()) thrift_name_cases.append(field.java_field_metadata_value_of_thrift_name_case()) class_suppress_warnings = '' if 'serial' in self.__java_compound_type._suppress_warnings else "@SuppressWarnings(\"serial\")\n" enumerators = pad("\n", indent(' ' * 4, ",\n".join(enumerators)), ";\n") java_name_cases = lpad("\n", indent(' ' * 8, "\n".join(java_name_cases))) thrift_name_cases = lpad("\n", indent(' ' * 8, "\n".join(thrift_name_cases))) return """\ %(class_suppress_warnings)spublic enum FieldMetadata implements org.thryft.CompoundType.FieldMetadata {%(enumerators)s @Override public String getJavaName() { return javaName; } @Override public com.google.common.reflect.TypeToken<?> getJavaType() { return javaType; } @Override public int getThriftId() { return thriftId; } @Override public String getThriftProtocolKey() { return thriftProtocolKey; } @Override public org.thryft.protocol.Type getThriftProtocolType() { return thriftProtocolType; } @Override public String getThriftName() { return thriftName; } @Override public boolean hasThriftId() { return thriftId != org.thryft.protocol.FieldBegin.ABSENT_ID; } @Override public boolean isRequired() { return required; } public static FieldMetadata valueOfJavaName(final String javaName) { switch (javaName) {%(java_name_cases)s default: throw new IllegalArgumentException(javaName); } } public static FieldMetadata valueOfThriftName(final String thriftName) { switch (thriftName) {%(thrift_name_cases)s default: throw new IllegalArgumentException(thriftName); } } private FieldMetadata(final String javaName, final com.google.common.reflect.TypeToken<?> javaType, final boolean required, final int thriftId, final String thriftName, final org.thryft.protocol.Type thriftProtocolType) { this.javaName = javaName; this.javaType = javaType; this.required = required; this.thriftId = thriftId; this.thriftName = thriftName; if (thriftId != org.thryft.protocol.FieldBegin.ABSENT_ID) { this.thriftProtocolKey = Integer.toString(thriftId) + ":" + thriftName; } else { this.thriftProtocolKey = thriftName; } this.thriftProtocolType = thriftProtocolType; } private final String javaName; private final com.google.common.reflect.TypeToken<?> javaType; private final boolean required; private final int thriftId; private final String thriftName; private final String thriftProtocolKey; private final org.thryft.protocol.Type thriftProtocolType; }""" % locals()
def _java_constructor_protocol(self): field_declarations = \ pad("\n", indent(' ' * 4, "\n".join( field.java_local_declaration(final=False) for field in self.fields )), "\n") field_initializers = \ lpad("\n\n", "\n".join(indent(' ' * 4, (field.java_initializer(check_optional_not_null=False) for field in self.fields) ))) field_protocol_named_initializers = \ lpad(' else ', indent(' ' * 16, ' else '.join( """\ if (ifield.getName().equals("%s")) { %s }""" % (field.name, indent(' ' * 4, field.java_protocol_initializer())) for field in self.fields )).lstrip()) field_protocol_positional_initializers = [] need_read_list_return = False for field_i, field in enumerate(self.fields): if field.required: field_required = True else: field_required = False # Field is optional, but it may be followed by a required field, # in which case it is required in a positional read if field_i + 1 < len(self.fields): for other_field in self.fields[field_i + 1:]: if other_field.required: field_required = True break field_protocol_initializer = field.java_protocol_initializer() if not field_required: field_protocol_initializer = indent( ' ' * 4, field_protocol_initializer) field_protocol_initializer = """\ if (__list.getSize() > %(field_i)u) { %(field_protocol_initializer)s }""" % locals() need_read_list_return = True field_protocol_positional_initializers.append( field_protocol_initializer) field_protocol_positional_initializers = \ lpad("\n", indent(' ' * 12, "\n".join(field_protocol_positional_initializers))) name = self.java_name() read_list = need_read_list_return and "final org.thryft.protocol.ListBegin __list = " or '' return """\ public %(name)s(final org.thryft.protocol.InputProtocol iprot) throws org.thryft.protocol.InputProtocolException { this(iprot, org.thryft.protocol.Type.STRUCT); } public %(name)s(final org.thryft.protocol.InputProtocol iprot, final org.thryft.protocol.Type readAsType) throws org.thryft.protocol.InputProtocolException {%(field_declarations)s switch (readAsType) { case LIST: %(read_list)siprot.readListBegin();%(field_protocol_positional_initializers)s iprot.readListEnd(); break; case STRUCT: default: iprot.readStructBegin(); while (true) { final org.thryft.protocol.FieldBegin ifield = iprot.readFieldBegin(); if (ifield.getType() == org.thryft.protocol.Type.STOP) { break; }%(field_protocol_named_initializers)s iprot.readFieldEnd(); } iprot.readStructEnd(); break; }%(field_initializers)s }""" % locals()
def _cpp_method_write(self): case_ttype_void = 'case ::thryft::protocol::Type::VOID_:' if len(self.fields) == 1: field = self.fields[0] from thryft.generators.cpp._cpp_container_type import _CppContainerType from thryft.generators.cpp.cpp_struct_type import CppStructType if isinstance(field.type, _CppContainerType) or isinstance(field.type, CppStructType): field_value_cpp_write_protocol = \ indent(' ' * 4, field.type.cpp_write_protocol(field.cpp_getter_name() + (field.required and '()' or '().get()'))) case_ttype_void = """\ %(case_ttype_void)s %(field_value_cpp_write_protocol)s break; """ % locals() field_count = len(self.fields) field_write_protocols = \ lpad("\n\n", "\n\n".join(indent(' ' * 4, (field.cpp_write_protocol(write_field=True) for field in self.fields) ))) field_value_write_protocols = \ pad("\n\n", "\n\n".join(indent(' ' * 4, (field.cpp_write_protocol(write_field=False) for field in self.fields) )), "\n") name = self.cpp_name() qname = self.cpp_qname() if self.__message_type is not None: message_type = self.__message_type write_struct_begin = "write_message_begin(\"%(qname)s\", ::thryft::protocol::MessageType::%(message_type)s)" % locals() write_struct_end = "write_message_end()" else: write_struct_begin = "write_struct_begin(\"%(qname)s\")" % locals() write_struct_end = "write_struct_end()" return {'write': """\ void write(::thryft::protocol::OutputProtocol& oprot) const override { write(oprot, ::thryft::protocol::Type::STRUCT); } void write(::thryft::protocol::OutputProtocol& oprot, const ::thryft::protocol::Type& as_type) const { switch (static_cast< ::thryft::protocol::Type::Enum >(as_type)) { %(case_ttype_void)s case ::thryft::protocol::Type::LIST: oprot.write_list_begin(::thryft::protocol::Type::VOID_, %(field_count)u);%(field_value_write_protocols)s oprot.write_list_end(); break; case ::thryft::protocol::Type::STRUCT: default: oprot.%(write_struct_begin)s;%(field_write_protocols)s oprot.write_field_stop(); oprot.%(write_struct_end)s; break; } } """ % locals()}
def py_public_delegating_definition(self): doc = self.py_doc() if doc is not None: doc = indent(' ' * 4, """ ''' %(doc)s ''' """ % locals()) else: doc = '' name = self.py_name() parameters = \ lpad("\n", "\n".join(indent(' ' * 4, ( parameter.py_parameter(default_value='None') for parameter in self.parameters )))) parameter_checks = \ pad("\n", "\n".join(indent(' ' * 4, (parameter.py_check() for parameter in self.parameters) )), "\n") call = ', '.join("%s=%s" % (parameter.py_name(), parameter.py_name()) for parameter in self.parameters) if self.return_field is not None: return_value = name + '_return_value' while True: renamed_return_value = False for parameter in self.parameters: if parameter.name == return_value: return_value += '_' renamed_return_value = True break if not renamed_return_value: break return_prefix = return_value + ' = ' return_suffix = [] return_type_check = self.return_field.type.py_check(return_value) return_suffix.append("""\ if not %(return_type_check)s: raise TypeError(getattr(__builtin__, 'type')(%(return_value)s))""" % locals()) return_suffix.append('return ' + return_value) return_suffix = "\n\n" + "\n\n".join(indent(' ' * 4, return_suffix)) else: return_prefix = return_suffix = '' suppress_warnings = '' if self._py_is_reserved_name(name): suppress_warnings = ' # @ReservedAssignment' for parameter in self.parameters: if self._py_is_reserved_name(parameter.py_name()): suppress_warnings = ' # @ReservedAssignment' break return """\ def %(name)s( self,%(parameters)s ):%(doc)s%(parameter_checks)s %(return_prefix)sself._%(name)s(%(call)s)%(return_suffix)s """ % locals()
def _java_constructor_protocol(self): field_declarations = \ pad("\n", indent(' ' * 4, "\n".join( field.java_local_declaration(final=False) for field in self.fields )), "\n") field_initializers = \ lpad("\n\n", "\n".join(indent(' ' * 4, (field.java_initializer(check_optional_not_null=False) for field in self.fields) ))) field_protocol_named_initializers = \ lpad(' else ', indent(' ' * 16, ' else '.join( """\ if (ifield.getName().equals("%s")) { %s }""" % (field.name, indent(' ' * 4, field.java_protocol_initializer())) for field in self.fields )).lstrip()) field_protocol_positional_initializers = [] need_read_list_return = False for field_i, field in enumerate(self.fields): if field.required: field_required = True else: field_required = False # Field is optional, but it may be followed by a required field, # in which case it is required in a positional read if field_i + 1 < len(self.fields): for other_field in self.fields[field_i + 1:]: if other_field.required: field_required = True break field_protocol_initializer = field.java_protocol_initializer() if not field_required: field_protocol_initializer = indent(' ' * 4, field_protocol_initializer) field_protocol_initializer = """\ if (__list.getSize() > %(field_i)u) { %(field_protocol_initializer)s }""" % locals() need_read_list_return = True field_protocol_positional_initializers.append(field_protocol_initializer) field_protocol_positional_initializers = \ lpad("\n", indent(' ' * 12, "\n".join(field_protocol_positional_initializers))) name = self.java_name() read_list = need_read_list_return and "final org.thryft.protocol.ListBegin __list = " or '' return """\ public %(name)s(final org.thryft.protocol.InputProtocol iprot) throws org.thryft.protocol.InputProtocolException { this(iprot, org.thryft.protocol.Type.STRUCT); } public %(name)s(final org.thryft.protocol.InputProtocol iprot, final org.thryft.protocol.Type readAsType) throws org.thryft.protocol.InputProtocolException {%(field_declarations)s switch (readAsType) { case LIST: %(read_list)siprot.readListBegin();%(field_protocol_positional_initializers)s iprot.readListEnd(); break; case STRUCT: default: iprot.readStructBegin(); while (true) { final org.thryft.protocol.FieldBegin ifield = iprot.readFieldBegin(); if (ifield.getType() == org.thryft.protocol.Type.STOP) { break; }%(field_protocol_named_initializers)s iprot.readFieldEnd(); } iprot.readStructEnd(); break; }%(field_initializers)s }""" % locals()
def java_repr(self): enumerators = [] java_name_cases = [] thrift_name_cases = [] for field in self.__java_compound_type.fields: enumerators.append( field.java_field_metadata_enumerator_declaration()) java_name_cases.append( field.java_field_metadata_value_of_java_name_case()) thrift_name_cases.append( field.java_field_metadata_value_of_thrift_name_case()) class_suppress_warnings = '' if 'serial' in self.__java_compound_type._suppress_warnings else "@SuppressWarnings(\"serial\")\n" enumerators = pad("\n", indent(' ' * 4, ",\n".join(enumerators)), ";\n") java_name_cases = lpad("\n", indent(' ' * 8, "\n".join(java_name_cases))) thrift_name_cases = lpad( "\n", indent(' ' * 8, "\n".join(thrift_name_cases))) return """\ %(class_suppress_warnings)spublic enum FieldMetadata implements org.thryft.CompoundType.FieldMetadata {%(enumerators)s @Override public String getJavaName() { return javaName; } @Override public com.google.common.reflect.TypeToken<?> getJavaType() { return javaType; } @Override public int getThriftId() { return thriftId; } @Override public String getThriftProtocolKey() { return thriftProtocolKey; } @Override public org.thryft.protocol.Type getThriftProtocolType() { return thriftProtocolType; } @Override public String getThriftName() { return thriftName; } @Override public boolean hasThriftId() { return thriftId != org.thryft.protocol.FieldBegin.ABSENT_ID; } @Override public boolean isRequired() { return required; } public static FieldMetadata valueOfJavaName(final String javaName) { switch (javaName) {%(java_name_cases)s default: throw new IllegalArgumentException(javaName); } } public static FieldMetadata valueOfThriftName(final String thriftName) { switch (thriftName) {%(thrift_name_cases)s default: throw new IllegalArgumentException(thriftName); } } private FieldMetadata(final String javaName, final com.google.common.reflect.TypeToken<?> javaType, final boolean required, final int thriftId, final String thriftName, final org.thryft.protocol.Type thriftProtocolType) { this.javaName = javaName; this.javaType = javaType; this.required = required; this.thriftId = thriftId; this.thriftName = thriftName; if (thriftId != org.thryft.protocol.FieldBegin.ABSENT_ID) { this.thriftProtocolKey = Integer.toString(thriftId) + ":" + thriftName; } else { this.thriftProtocolKey = thriftName; } this.thriftProtocolType = thriftProtocolType; } private final String javaName; private final com.google.common.reflect.TypeToken<?> javaType; private final boolean required; private final int thriftId; private final String thriftName; private final String thriftProtocolKey; private final org.thryft.protocol.Type thriftProtocolType; }""" % locals()
def _cpp_method_write(self): case_ttype_void = 'case ::thryft::protocol::Type::VOID_:' if len(self.fields) == 1: field = self.fields[0] from thryft.generators.cpp._cpp_container_type import _CppContainerType from thryft.generators.cpp.cpp_struct_type import CppStructType if isinstance(field.type, _CppContainerType) or isinstance( field.type, CppStructType): field_value_cpp_write_protocol = \ indent(' ' * 4, field.type.cpp_write_protocol(field.cpp_getter_name() + (field.required and '()' or '().get()'))) case_ttype_void = """\ %(case_ttype_void)s %(field_value_cpp_write_protocol)s break; """ % locals() field_count = len(self.fields) field_write_protocols = \ lpad("\n\n", "\n\n".join(indent(' ' * 4, (field.cpp_write_protocol(write_field=True) for field in self.fields) ))) field_value_write_protocols = \ pad("\n\n", "\n\n".join(indent(' ' * 4, (field.cpp_write_protocol(write_field=False) for field in self.fields) )), "\n") name = self.cpp_name() qname = self.cpp_qname() if self.__message_type is not None: message_type = self.__message_type write_struct_begin = "write_message_begin(\"%(qname)s\", ::thryft::protocol::MessageType::%(message_type)s)" % locals( ) write_struct_end = "write_message_end()" else: write_struct_begin = "write_struct_begin(\"%(qname)s\")" % locals() write_struct_end = "write_struct_end()" return { 'write': """\ void write(::thryft::protocol::OutputProtocol& oprot) const override { write(oprot, ::thryft::protocol::Type::STRUCT); } void write(::thryft::protocol::OutputProtocol& oprot, const ::thryft::protocol::Type& as_type) const { switch (static_cast< ::thryft::protocol::Type::Enum >(as_type)) { %(case_ttype_void)s case ::thryft::protocol::Type::LIST: oprot.write_list_begin(::thryft::protocol::Type::VOID_, %(field_count)u);%(field_value_write_protocols)s oprot.write_list_end(); break; case ::thryft::protocol::Type::STRUCT: default: oprot.%(write_struct_begin)s;%(field_write_protocols)s oprot.write_field_stop(); oprot.%(write_struct_end)s; break; } } """ % locals() }