示例#1
0
    def __repr__(self):
        class_annotations = []
        if len(self.__suppress_warnings) > 0:
            class_annotations.append(
                "@SuppressWarnings({%s})" % \
                    ', '.join('"' + warning + '"'
                               for warning in sorted(self.__suppress_warnings)))
        class_annotations = rpad("\n".join(class_annotations), "\n")
        class_modifiers = rpad(' '.join(self.__class_modifiers), ' ')
        javadoc = self.java_doc()
        name = self.java_name()
        extends = lpad(' extends ', self._java_extends())
        implements = lpad(' implements ', ', '.join(self._java_implements()))
        methods = self._java_methods()
        sections = []
        sections.append(indent(' ' * 4, repr(self._JavaBuilder(self))))
        sections.append("\n\n".join(indent(' ' * 4,
            self._java_constructors() + \
            [methods[key] for key in sorted(methods.iterkeys())])))
        sections.append("\n\n".join(
            indent(' ' * 4, self._java_member_declarations())))
        sections = lpad(
            "\n",
            "\n\n".join(section for section in sections if len(section) > 0))
        return """\
%(javadoc)s%(class_annotations)s%(class_modifiers)sclass %(name)s%(extends)s%(implements)s {%(sections)s
}""" % locals()
示例#2
0
    def java_repr(self):
        class_annotations = []
        if len(self._suppress_warnings) > 0:
            class_annotations.append(
                "@SuppressWarnings({%s})" % \
                    ', '.join('"' + warning + '"'
                               for warning in sorted(self._suppress_warnings)))
        class_annotations = rpad("\n".join(class_annotations), "\n")
        class_modifiers = rpad(' '.join(self.__class_modifiers), ' ')
        javadoc = self.java_doc()
        name = self.java_name()
        extends = lpad(' extends ', self._java_extends())
        implements = lpad(' implements ', ', '.join(self._java_implements()))
        methods = self._java_methods()
        sections = []
        sections.append(indent(' ' * 4, self._JavaBuilder(self).java_repr()))
        sections.append(indent(' ' * 4, self._JavaFactory(self).java_repr()))
        field_metadata_enum = self._java_field_metadata_enum()
        if field_metadata_enum is not None:
            sections.append(indent(' ' * 4, field_metadata_enum))
        sections.append(indent(' ' * 4, self._JavaValidator(self).java_repr()))
        sections.append("\n\n".join(indent(' ' * 4,
            self._java_constructors() + \
            [methods[key] for key in sorted(methods.iterkeys())])))
        sections.append("\n\n".join(indent(' ' * 4, self._java_member_declarations())))
        sections = lpad("\n", "\n\n".join(section for section in sections if len(section) > 0))
        return """\
%(javadoc)s%(class_annotations)s%(class_modifiers)sclass %(name)s%(extends)s%(implements)s {%(sections)s
}""" % locals()
示例#3
0
 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"))
示例#4
0
 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")
     )
示例#5
0
    def __repr__(self):
        imports = []
        # Don't import anything that isn't required
        #        for include in self.includes:
        #            imports.append(str(include))
        for definition in self.definitions:
            imports.extend(definition.py_imports_definition())
        imports = "\n".join(list(sorted(set(imports))))

        definitions = \
            "\n\n".join(repr(definition)
                         for definition in self.definitions)
        return rpad(imports, "\n\n\n") + rpad(definitions, "\n")
示例#6
0
    def __repr__(self):
        imports = []
# Don't import anything that isn't required
#        for include in self.includes:
#            imports.append(str(include))
        for definition in self.definitions:
            imports.extend(definition.py_imports_definition())
        imports = "\n".join(list(sorted(set(imports))))

        definitions = \
            "\n\n".join(repr(definition)
                         for definition in self.definitions)
        return rpad(imports, "\n\n\n") + rpad(definitions, "\n")
示例#7
0
    def cpp_repr(self):
        definitions = []
        definitions.append("\n\n".join(definition.cpp_repr()
                                       for definition in self.definitions))
        definitions = "\n\n".join(definitions)
        if len(definitions) == 0:
            return definitions

        global_operators = lpad("\n\n",
                                "\n\n".join(self.cpp_global_operators()))
        guard = self.cpp_guard()
        namespace_block_closes = self.cpp_namespace_block_closes()
        namespace_block_opens = self.cpp_namespace_block_opens()

        includes = rpad("\n".join(self.cpp_includes_definition()), "\n\n")

        repr_ = """\
#ifndef %(guard)s
#define %(guard)s

%(includes)s%(namespace_block_opens)s%(definitions)s%(namespace_block_closes)s%(global_operators)s

#endif  // %(guard)s
""" % locals()

        return repr_
示例#8
0
    def cpp_repr(self):
        definitions = []
        definitions.append(
            "\n\n".join(definition.cpp_repr()
                         for definition in self.definitions)
        )
        definitions = "\n\n".join(definitions)
        if len(definitions) == 0:
            return definitions

        global_operators = lpad("\n\n", "\n\n".join(self.cpp_global_operators()))
        guard = self.cpp_guard()
        namespace_block_closes = self.cpp_namespace_block_closes()
        namespace_block_opens = self.cpp_namespace_block_opens()

        includes = rpad("\n".join(self.cpp_includes_definition()), "\n\n")

        repr_ = """\
#ifndef %(guard)s
#define %(guard)s

%(includes)s%(namespace_block_opens)s%(definitions)s%(namespace_block_closes)s%(global_operators)s

#endif  // %(guard)s
""" % locals()

        return repr_
示例#9
0
 def _dart_imports_use(self, caller_stack):
     return [
         "import 'package:%s/%s';" %
         (self.__package_name,
          rpad(self.namespace_by_scope('dart').name.replace('.', '/'), '/')
          + self.dart_name() + '.dart')
     ]
示例#10
0
 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 "%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")
     )
示例#12
0
 def __repr__(self):
     return "%s%s%s %s(%s)%s" % (
         self.doc is not None and rpad(repr(self.doc), "\n") or '',
         self.oneway and 'oneway ' or '',
         self.return_field is not None and self.return_field.type.thrift_qname() or 'void',
         self.name,
         ', '.join(repr(parameter) for parameter in self.parameters),
         len(self.throws) > 0 and \
             (' throws (' + ', '.join(repr(throws) for throws in self.throws) + ')')
             or ''
     )
示例#13
0
        def __repr__(self):
            annotations = rpad("\n".join(self.java_annotations()), "\n")
            name = self.java_name()
            request_type_name = self.java_request_type().java_name()
            service_qname = self.parent.java_qname()
            upper_camelized_name = upper_camelize(self.name)

            if len(self.parameters) > 0:
                read_request = """
    final %(service_qname)s.Messages.%(request_type_name)s serviceRequest;
    try {
        serviceRequest = new %(service_qname)s.Messages.%(request_type_name)s(iprot, iprot.getCurrentFieldType());
    } catch (final IllegalArgumentException | org.thryft.protocol.InputProtocolException | NullPointerException e) {
        logger.debug("error deserializing service request: ", e);
        __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, -32602, "invalid JSON-RPC request method parameters: " + String.valueOf(e.getMessage())), jsonRpcRequestId);
        return;
    }
""" % locals()
            else:
                read_request = ''
            parameters = ', '.join([
                'serviceRequest.' + parameter.java_getter_name() + '()'
                for parameter in self.parameters
            ])
            service_call = "service.%(name)s(%(parameters)s);" % locals()
            if self.return_field is not None:
                service_call = 'result = ' + service_call
            if len(self.throws) > 0:
                catches = ' '.join([
                    """\
catch (final %s e) {
    __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, 1, e.getClass().getCanonicalName() + ": " + String.valueOf(e.getMessage())), jsonRpcRequestId);
    return;
}""" % throw.type.java_qname() for throw in self.throws
                ])
                service_call = """\
try {
    %(service_call)s
} %(catches)s
""" % locals()
            service_call = indent(' ' * 4, service_call)

            return """\
%(annotations)sprivate void __doPost%(upper_camelized_name)s(final javax.servlet.http.HttpServletRequest httpServletRequest, final javax.servlet.http.HttpServletResponse httpServletResponse, final org.thryft.protocol.JsonRpcInputProtocol iprot, final Object jsonRpcRequestId) throws java.io.IOException {%(read_request)s
    Object result = null;
%(service_call)s

    __doPostResponse(httpServletRequest, httpServletResponse, jsonRpcRequestId, result);
}
""" % locals()
示例#14
0
 def __repr__(self):
     repr_ = []
     if self.id is not None:
         repr_.append(str(self.id) + ':')
     if self.required:
         repr_.append('required')
     else:
         repr_.append('optional')
     repr_.append(self.type.thrift_qname())
     repr_.append(self.name)
     if self.value is not None:
         repr_.extend(('=', str(self.value)))
     return (self.doc is not None and rpad(repr(self.doc), "\n") or '') + \
            ' '.join(repr_)
示例#15
0
    def __repr__(self):
        imports = "\n".join(self.dart_imports_definition())
        definitions = "\n\n".join(repr(definition)
                        for definition in self.definitions)
        if len(definitions) == 0:
            return ''

        sections = []
        sections.append("library " + rpad(self.namespace_by_scope('dart').name, '.') + self.dart_name() + ';')
        if len(imports) > 0:
            sections.append(imports)
        sections.append(definitions)

        return "\n\n".join(sections) + "\n"
示例#16
0
    def cpp_repr(self):
        name = self.cpp_name()
        extends = lpad(' : public ', self._cpp_extends())
        template_parameters = rpad(self._cpp_template_parameters(), "\n")
        sections = []
        # sections.append(indent(' ' * 4, repr(self._CppBuilder(self))))
        sections.append(lpad("public:\n", "\n\n".join(indent(' ' * 2,
            self._cpp_constructors() + [self._cpp_destructor()] + self._cpp_methods_list()
            ))))
        sections.append(lpad("private:\n", "\n".join(indent(' ' * 2, self._cpp_member_declarations()))))
        sections = lpad("\n", "\n\n".join(section for section in sections if len(section) > 0))
        return """\
%(template_parameters)sclass %(name)s%(extends)s {%(sections)s
};""" % locals()
示例#17
0
    def __repr__(self):
        imports = "\n".join(self.dart_imports_definition())
        definitions = "\n\n".join(
            repr(definition) for definition in self.definitions)
        if len(definitions) == 0:
            return ''

        sections = []
        sections.append("library " +
                        rpad(self.namespace_by_scope('dart').name, '.') +
                        self.dart_name() + ';')
        if len(imports) > 0:
            sections.append(imports)
        sections.append(definitions)

        return "\n\n".join(sections) + "\n"
        def __repr__(self):
            annotations = rpad("\n".join(self.java_annotations()), "\n")
            name = self.java_name()
            request_type_name = self.java_request_type().java_name()
            service_qname = self.parent.java_qname()
            upper_camelized_name = upper_camelize(self.name)

            if len(self.parameters) > 0:
                read_request = """
    final %(service_qname)s.Messages.%(request_type_name)s serviceRequest;
    try {
        serviceRequest = new %(service_qname)s.Messages.%(request_type_name)s(iprot, iprot.getCurrentFieldType());
    } catch (final IllegalArgumentException | org.thryft.protocol.InputProtocolException | NullPointerException e) {
        logger.debug("error deserializing service request: ", e);
        __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, -32602, "invalid JSON-RPC request method parameters: " + String.valueOf(e.getMessage())), jsonRpcRequestId);
        return;
    }
""" % locals()
            else:
                read_request = ''
            parameters = ', '.join(['serviceRequest.' + parameter.java_getter_name() + '()'
                                    for parameter in self.parameters])
            service_call = "service.%(name)s(%(parameters)s);" % locals()
            if self.return_field is not None:
                service_call = 'result = ' + service_call
            if len(self.throws) > 0:
                catches = ' '.join(["""\
catch (final %s e) {
    __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, 1, e.getClass().getCanonicalName() + ": " + String.valueOf(e.getMessage())), jsonRpcRequestId);
    return;
}""" % throw.type.java_qname() for throw in self.throws])
                service_call = """\
try {
    %(service_call)s
} %(catches)s
""" % locals()
            service_call = indent(' ' * 4, service_call)

            return """\
%(annotations)sprivate void __doPost%(upper_camelized_name)s(final javax.servlet.http.HttpServletRequest httpServletRequest, final javax.servlet.http.HttpServletResponse httpServletResponse, final org.thryft.protocol.JsonRpcInputProtocol iprot, final Object jsonRpcRequestId) throws java.io.IOException {%(read_request)s
    Object result = null;
%(service_call)s

    __doPostResponse(httpServletRequest, httpServletResponse, jsonRpcRequestId, result);
}
""" % locals()
示例#19
0
    def py_repr(self):
        sections = []
        imports = []
# Don't import anything that isn't required
#        for include in self.includes:
#            imports.append(str(include))
        for definition in self.definitions:
            imports.extend(definition.py_imports_definition())
        if len(imports) > 0:
            sections.append("\n".join(list(sorted(set(imports)))) + "\n")

        definitions = \
            "\n\n".join(definition.py_repr()
                         for definition in self.definitions)
        if len(definitions) > 0:
            sections.append(definitions)

        return rpad("\n\n".join(sections), "\n")
示例#20
0
    def py_repr(self):
        sections = []
        imports = []
        # Don't import anything that isn't required
        #        for include in self.includes:
        #            imports.append(str(include))
        for definition in self.definitions:
            imports.extend(definition.py_imports_definition())
        if len(imports) > 0:
            sections.append("\n".join(list(sorted(set(imports)))) + "\n")

        definitions = \
            "\n\n".join(definition.py_repr()
                         for definition in self.definitions)
        if len(definitions) > 0:
            sections.append(definitions)

        return rpad("\n\n".join(sections), "\n")
示例#21
0
    def dart_repr(self):
        try:
            dart_namespace_name = self.namespace_by_scope(('dart', '*')).name
        except KeyError:
            return ''

        imports = "\n".join(self.dart_imports_definition())
        definitions = "\n\n".join(definition.dart_repr()
                        for definition in self.definitions)
        if len(definitions) == 0:
            return ''

        sections = []
        sections.append("library " + rpad(dart_namespace_name, '.') + self.dart_name() + ';')
        if len(imports) > 0:
            sections.append(imports)
        sections.append(definitions)

        return "\n\n".join(sections) + "\n"
示例#22
0
    def dart_repr(self):
        try:
            dart_namespace_name = self.namespace_by_scope(('dart', '*')).name
        except KeyError:
            return ''

        imports = "\n".join(self.dart_imports_definition())
        definitions = "\n\n".join(definition.dart_repr()
                                  for definition in self.definitions)
        if len(definitions) == 0:
            return ''

        sections = []
        sections.append("library " + rpad(dart_namespace_name, '.') +
                        self.dart_name() + ';')
        if len(imports) > 0:
            sections.append(imports)
        sections.append(definitions)

        return "\n\n".join(sections) + "\n"
示例#23
0
        def _java_constructor_from_immutable(self):
            annotations = []
            name = self.java_bean_name()
            immutable_name = JavaGenerator.StructType.java_qname(self)  # @UndefinedVariable
            initializers = []
            for field in self.fields:
                if field.deprecated:
                    annotations.append("@SuppressWarnings(\"deprecation\")")
                lhs = "this." + field.java_name()
                field_getter_call = 'other.' + field.java_getter_name() + '()'
                if field.required:
                    rhs = field.type.java_from_immutable(field_getter_call)
                else:
                    field_conversion = field.type.java_from_immutable("%(field_getter_call)s.get()" % locals())
                    rhs = "%(field_getter_call)s.isPresent() ? %(field_conversion)s : null" % locals()
                initializers.append("%(lhs)s = %(rhs)s;" % locals())
            annotations = rpad("\n".join(set(annotations)), "\n")
            initializers = lpad("\n", "\n".join(indent(' ' * 4, initializers)))
            return """\
%(annotations)spublic %(name)s(final %(immutable_name)s other) {%(initializers)s
}""" % locals()
示例#24
0
    def cpp_repr(self):
        name = self.cpp_name()
        extends = lpad(' : public ', self._cpp_extends())
        template_parameters = rpad(self._cpp_template_parameters(), "\n")
        sections = []
        # sections.append(indent(' ' * 4, repr(self._CppBuilder(self))))
        sections.append(
            lpad(
                "public:\n", "\n\n".join(
                    indent(
                        ' ' * 2,
                        self._cpp_constructors() + [self._cpp_destructor()] +
                        self._cpp_methods_list()))))
        sections.append(
            lpad("private:\n",
                 "\n".join(indent(' ' * 2, self._cpp_member_declarations()))))
        sections = lpad(
            "\n",
            "\n\n".join(section for section in sections if len(section) > 0))
        return """\
%(template_parameters)sclass %(name)s%(extends)s {%(sections)s
};""" % locals()
示例#25
0
    def __repr__(self):
        definitions = []
        definitions.append(
            "\n\n".join(repr(definition)
                         for definition in self.definitions)
        )
        definitions = "\n\n".join(definitions)
        if len(definitions) == 0:
            return definitions

        guard = []
        namespace = self.cpp_namespace()
        if namespace is not None:
            namespace_split = namespace.split('.')
            guard.extend(s.upper() for s in namespace_split)
            namespaces_prefix = "\n".join("namespace %s {" % s for s in namespace_split) + "\n"
            namespaces_suffix = "\n" + "\n".join('}' for _ in namespace_split)

        global_operators = []
        for definition in self.definitions:
            if isinstance(definition, _CppCompoundType):
                global_operators.extend(definition.cpp_global_operators())
        global_operators = lpad("\n\n", "\n\n".join(global_operators))

        guard.append(self.cpp_name().upper())
        guard = '_' + '_'.join(guard) + '_HPP_'

        includes = rpad("\n".join(self.cpp_includes_definition()), "\n\n")

        repr_ = """\
#ifndef %(guard)s
#define %(guard)s

%(includes)s%(namespaces_prefix)s%(definitions)s%(namespaces_suffix)s%(global_operators)s

#endif  // %(guard)s
""" % locals()

        return repr_
示例#26
0
        def _java_constructor_from_immutable(self):
            annotations = []
            name = self.java_bean_name()
            immutable_name = JavaGenerator.StructType.java_qname(
                self)  # @UndefinedVariable
            initializers = []
            for field in self.fields:
                if field.deprecated:
                    annotations.append("@SuppressWarnings(\"deprecation\")")
                lhs = "this." + field.java_name()
                field_getter_call = 'other.' + field.java_getter_name() + '()'
                if field.required:
                    rhs = field.type.java_from_immutable(field_getter_call)
                else:
                    field_conversion = field.type.java_from_immutable(
                        "%(field_getter_call)s.get()" % locals())
                    rhs = "%(field_getter_call)s.isPresent() ? %(field_conversion)s : null" % locals(
                    )
                initializers.append("%(lhs)s = %(rhs)s;" % locals())
            annotations = rpad("\n".join(set(annotations)), "\n")
            initializers = lpad("\n", "\n".join(indent(' ' * 4, initializers)))
            return """\
%(annotations)spublic %(name)s(final %(immutable_name)s other) {%(initializers)s
}""" % locals()
示例#27
0
        def java_definition(self):
            annotations = rpad("\n".join(self.java_annotations()), "\n")
            name = self.java_name()
            request_type_name = self.java_request_type().java_name()
            service_qname = self.parent.java_qname()
            upper_camelized_name = upper_camelize(self.name)

            if len(self.parameters) > 0:
                read_request = """
    final %(service_qname)s.Messages.%(request_type_name)s serviceRequest;
    try {
        serviceRequest = %(service_qname)s.Messages.%(request_type_name)s.readAs(iprot, iprot.getCurrentFieldType(), unknownFieldCallback);
    } catch (final IllegalArgumentException | org.thryft.protocol.InputProtocolException | NullPointerException e) {
        logger.debug("error deserializing service request: ", e);
        __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, -32602, "invalid JSON-RPC request method parameters: " + String.valueOf(e.getMessage())), jsonRpcRequestId);
        return;
    }
""" % locals()
            else:
                read_request = ''
            parameters = ', '.join(['serviceRequest.' + parameter.java_getter_name() + '()'
                                    for parameter in self.parameters])
            service_call = "service.%(name)s(%(parameters)s);" % locals()
            if self.return_field is not None:
                result_declaration = "    final %s result;\n" % self.return_field.type.java_qname()
                service_call = 'result = ' + service_call
                write_result = self.return_field.type.java_write_protocol(value='result')
            else:
                result_declaration = ''
                write_result = '''\
oprot.writeStructBegin("response");
oprot.writeStructEnd();
'''
            write_result = indent(' ' * 12, write_result)
            if len(self.throws) > 0:
                catches = ' '.join(["""\
catch (final %s e) {
    __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, 1, e.getClass().getCanonicalName() + ": " + String.valueOf(e.getMessage())), jsonRpcRequestId);
    return;
}""" % throw.type.java_qname() for throw in self.throws])
                service_call = """\
try {
    %(service_call)s
} %(catches)s
""" % locals()
            service_call = indent(' ' * 4, service_call)

            return """\
%(annotations)spublic void doPost%(upper_camelized_name)s(final javax.servlet.http.HttpServletRequest httpServletRequest, final javax.servlet.http.HttpServletResponse httpServletResponse, final org.thryft.protocol.JsonRpcInputProtocol iprot, final Object jsonRpcRequestId) throws java.io.IOException {%(read_request)s
%(result_declaration)s%(service_call)s

    final String httpServletResponseBody;
    {
        final java.io.StringWriter httpServletResponseBodyWriter = new java.io.StringWriter();
        try {
            final org.thryft.protocol.JsonRpcOutputProtocol oprot = new org.thryft.protocol.JsonRpcOutputProtocol(new org.thryft.protocol.JacksonJsonOutputProtocol(httpServletResponseBodyWriter));
            oprot.writeMessageBegin("", org.thryft.protocol.MessageType.REPLY, jsonRpcRequestId);
%(write_result)s
            oprot.writeMessageEnd();
            oprot.flush();
        } catch (final org.thryft.protocol.OutputProtocolException e) {
            logger.error("error serializing service error response: ", e);
            throw new IllegalStateException(e);
        }
        httpServletResponseBody = httpServletResponseBodyWriter.toString();
    }
    __doPostResponse(httpServletRequest, httpServletResponse, httpServletResponseBody);
}
""" % locals()
示例#28
0
 def _dart_imports_use(self, caller_stack):
     return ["import 'package:%s/%s';" % (
                 self.__package_name,
                 rpad(self.namespace_by_scope(('dart', '*')).name.replace('.', '/'), '/') + self.dart_name() + '.dart')]
示例#29
0
 def java_class_qname(self):
     return rpad(self.__java_package, '.') + self.__java_class_name
        def __repr__(self):
            annotations = self.java_annotations()
            name = '__do' + self.java_name()[0].upper() + self.java_name()[1:]

            sections = []

            variable_declarations = []
            for parameter in self.parameters:
                variable_declarations.append(
                    parameter.java_local_declaration(final=False))
            if self.return_field is not None:
                variable_declarations.append(
                    self.return_field.type.java_declaration_name() +
                    " __return_value;")
            if len(variable_declarations) > 0:
                sections.append("\n".join(
                    indent(' ' * 4, variable_declarations)))

            read_request = []
            if len(self.parameters) > 0:
                path_parameter = self.java_rest_path_parameter()
                if path_parameter is None or len(self.parameters) > 1:
                    request_type_name = 'Messages.' + upper_camelize(
                        self.name) + 'Request'
                else:
                    request_type_name = None
                if self.java_rest_request_method() in ('POST', 'PUT'):
                    read_http_servlet_request_body = self._java_read_http_servlet_request_body(
                        variable_name_prefix='__')
                    read_request.append("""\
%(read_http_servlet_request_body)s
final org.thryft.protocol.InputProtocol __restRequestProtocol = new org.thryft.protocol.JacksonJsonInputProtocol(new java.io.StringReader(__httpServletRequestBody));
""" % locals())
                else:
                    if path_parameter is not None:
                        path_info_prefix = self.java_rest_path_prefix()
                        path_info_prefix_len = len(path_info_prefix)
                        path_parameter_name = path_parameter.java_name()
                        path_parameter_from_string = path_parameter.type.java_from_string(
                            "java.net.URLDecoder.decode(__httpServletRequest.getPathInfo().substring(%(path_info_prefix_len)u), \"UTF-8\")"
                            % locals())
                        read_request.append("""\
if (__httpServletRequest.getPathInfo().length() > %(path_info_prefix_len)u) {
    %(path_parameter_name)s = %(path_parameter_from_string)s;
} else {
    __httpServletResponse.sendError(404);
    return;
}
""" % locals())
                    if path_parameter is None or len(self.parameters) > 1:
                        annotations.append('@SuppressWarnings("unchecked")')
                        read_request.append("""\
java.util.Map<String, String> __restRequestParameterStringMap = new java.util.LinkedHashMap<String, String>();
for (final java.util.Map.Entry<String, String[]> __httpServletRequestParameter : ((java.util.Map<String, String[]>)__httpServletRequest.getParameterMap()).entrySet()) {
    __restRequestParameterStringMap.put(__httpServletRequestParameter.getKey(), __httpServletRequestParameter.getValue()[0]);
}
final org.thryft.protocol.InputProtocol __restRequestProtocol = new org.thryft.protocol.StringMapInputProtocol(__restRequestParameterStringMap);
""" % locals())
                if request_type_name is not None:
                    variable_assignments = []
                    for parameter in self.parameters:
                        if parameter is path_parameter:
                            continue
                        variable_assignments.append(
                            parameter.java_name() + ' = __serviceRequest.' +
                            parameter.java_getter_name() + '();')
                    variable_assignments = "\n".join(
                        indent(' ' * 4, variable_assignments))
                    read_request.append("""\
try {
    final %(request_type_name)s __serviceRequest = new %(request_type_name)s(__restRequestProtocol);
%(variable_assignments)s
} catch (final IllegalArgumentException e) {
    logger.debug("error deserializing service request: ", e);
    __httpServletResponse.sendError(400);
    return;
} catch (final NullPointerException e) {
    logger.debug("error deserializing service request: ", e);
    __httpServletResponse.sendError(400);
    return;
} catch (final org.thryft.protocol.InputProtocolException e) {
    logger.debug("error deserializing service request: ", e);
    __httpServletResponse.sendError(400);
    return;
}
""" % locals())

            if len(read_request) > 0:
                sections.append("\n".join(indent(' ' * 4, read_request)))

            service_call = \
                "service.%s(%s);" % (
                    _servlet_java_generator._ServletJavaGenerator._Function.java_name(self),
                    ', '.join([parameter.java_name() for parameter in self.parameters])
                )
            if self.return_field is not None:
                service_call = '__return_value = ' + service_call
            if len(self.throws) > 0:
                catches = ' '.join([
                    """\
catch (final %s e) {
    final java.io.StringWriter __httpServletResponseBodyWriter = new java.io.StringWriter();
    final org.thryft.protocol.OutputProtocol __oprot = new org.thryft.protocol.JacksonJsonOutputProtocol(__httpServletResponseBodyWriter);
    try {
        e.write(__oprot);
        __oprot.flush();
    } catch (final org.thryft.protocol.OutputProtocolException e1) {
        logger.error("error serializing service error response: ", e1);
        __httpServletResponse.sendError(500);
        return;
    }
    final String __httpServletResponseBody = __httpServletResponseBodyWriter.toString();
    __httpServletResponse.getWriter().write(__httpServletResponseBody);
    __httpServletResponse.setHeader("Content-Type", "application/json");
    __httpServletResponse.setHeader("Warning", e.getClass().getName());
    __httpServletResponse.setStatus(404);
    return;
}""" % throw.type.java_qname() for throw in self.throws
                ])
                service_call = """\
try {
    %(service_call)s
} %(catches)s
""" % locals()
            sections.append(indent(' ' * 4, service_call))

            if self.return_field is None:
                write_response = """\
    __httpServletResponse.setStatus(204);"""
            elif isinstance(self.return_field.type, JavaBoolType):
                # assert self.java_rest_request_method() in ('DELETE', 'HEAD'), self.java_rest_request_method()
                write_response = """\
    if (__return_value) {
        __httpServletResponse.setStatus(204);
    } else {
        __httpServletResponse.setStatus(404);
    }""" % locals()
            else:
                return_write = \
                    indent(' ' * 8, self.return_field.type.java_write_protocol('__return_value'))
                if isinstance(self.return_field.type, _JavaBaseType):
                    return_ttype_id = self.return_field.type.thrift_ttype_id()
                    return_write = """\
        oprot.writeListBegin(new org.thryft.protocol.TList((byte)%(return_ttype_id)u, 1));
%(return_write)s
        oprot.writeListEnd();""" % locals()
                write_http_servlet_response_body = indent(
                    ' ' * 4,
                    self._java_write_http_servlet_response_body(
                        variable_name_prefix='__'))
                write_response = """\
    final java.io.StringWriter __httpServletResponseBodyWriter = new java.io.StringWriter();
    final org.thryft.protocol.OutputProtocol oprot = new org.thryft.protocol.JacksonJsonOutputProtocol(__httpServletResponseBodyWriter);
    try {
%(return_write)s
        oprot.flush();
    } catch (final org.thryft.protocol.OutputProtocolException e) {
        logger.error("error serializing service response: ", e);
        __httpServletResponse.sendError(500);
        return;
    }
    String __httpServletResponseBody = __httpServletResponseBodyWriter.toString();

    __httpServletResponse.setStatus(200);

%(write_http_servlet_response_body)s
""" % locals()
            sections.append(write_response)

            annotations = rpad("\n".join(annotations), "\n")
            sections = "\n\n".join(sections)

            return """\
%(annotations)sprivate void %(name)s(final javax.servlet.http.HttpServletRequest __httpServletRequest, final javax.servlet.http.HttpServletResponse __httpServletResponse) throws java.io.IOException, javax.servlet.ServletException {
%(sections)s
}
""" % locals()
示例#31
0
 def __repr__(self):
     return "%sconst %s %s = %s;" % (
         self.doc is not None and rpad(repr(self.doc), "\n") or '',
         self.type.thrift_qname(), self.name, isinstance(self.value, str)
         and '"%s"' % self.value or str(self.value))
        def __repr__(self):
            annotations = self.java_annotations()
            name = '__do' + self.java_name()[0].upper() + self.java_name()[1:]

            sections = []

            variable_declarations = []
            for parameter in self.parameters:
                variable_declarations.append(parameter.java_local_declaration(final=False))
            if self.return_field is not None:
                variable_declarations.append(self.return_field.type.java_declaration_name() + " __return_value;")
            if len(variable_declarations) > 0:
                sections.append("\n".join(indent(' ' * 4, variable_declarations)))

            read_request = []
            if len(self.parameters) > 0:
                path_parameter = self.java_rest_path_parameter()
                if path_parameter is None or len(self.parameters) > 1:
                    request_type_name = 'Messages.' + upper_camelize(self.name) + 'Request'
                else:
                    request_type_name = None
                if self.java_rest_request_method() in ('POST', 'PUT'):
                    read_http_servlet_request_body = self._java_read_http_servlet_request_body(variable_name_prefix='__')
                    read_request.append("""\
%(read_http_servlet_request_body)s
final org.thryft.protocol.InputProtocol __restRequestProtocol = new org.thryft.protocol.JacksonJsonInputProtocol(new java.io.StringReader(__httpServletRequestBody));
""" % locals())
                else:
                    if path_parameter is not None:
                        path_info_prefix = self.java_rest_path_prefix()
                        path_info_prefix_len = len(path_info_prefix)
                        path_parameter_name = path_parameter.java_name()
                        path_parameter_from_string = path_parameter.type.java_from_string("java.net.URLDecoder.decode(__httpServletRequest.getPathInfo().substring(%(path_info_prefix_len)u), \"UTF-8\")" % locals())
                        read_request.append("""\
if (__httpServletRequest.getPathInfo().length() > %(path_info_prefix_len)u) {
    %(path_parameter_name)s = %(path_parameter_from_string)s;
} else {
    __httpServletResponse.sendError(404);
    return;
}
""" % locals())
                    if path_parameter is None or len(self.parameters) > 1:
                        annotations.append('@SuppressWarnings("unchecked")')
                        read_request.append("""\
java.util.Map<String, String> __restRequestParameterStringMap = new java.util.LinkedHashMap<String, String>();
for (final java.util.Map.Entry<String, String[]> __httpServletRequestParameter : ((java.util.Map<String, String[]>)__httpServletRequest.getParameterMap()).entrySet()) {
    __restRequestParameterStringMap.put(__httpServletRequestParameter.getKey(), __httpServletRequestParameter.getValue()[0]);
}
final org.thryft.protocol.InputProtocol __restRequestProtocol = new org.thryft.protocol.StringMapInputProtocol(__restRequestParameterStringMap);
""" % locals())
                if request_type_name is not None:
                    variable_assignments = []
                    for parameter in self.parameters:
                        if parameter is path_parameter:
                            continue
                        variable_assignments.append(parameter.java_name() + ' = __serviceRequest.' + parameter.java_getter_name() + '();')
                    variable_assignments = "\n".join(indent(' ' * 4, variable_assignments))
                    read_request.append("""\
try {
    final %(request_type_name)s __serviceRequest = new %(request_type_name)s(__restRequestProtocol);
%(variable_assignments)s
} catch (final IllegalArgumentException e) {
    logger.debug("error deserializing service request: ", e);
    __httpServletResponse.sendError(400);
    return;
} catch (final NullPointerException e) {
    logger.debug("error deserializing service request: ", e);
    __httpServletResponse.sendError(400);
    return;
} catch (final org.thryft.protocol.InputProtocolException e) {
    logger.debug("error deserializing service request: ", e);
    __httpServletResponse.sendError(400);
    return;
}
""" % locals())

            if len(read_request) > 0:
                sections.append("\n".join(indent(' ' * 4, read_request)))

            service_call = \
                "service.%s(%s);" % (
                    _servlet_java_generator._ServletJavaGenerator._Function.java_name(self),
                    ', '.join([parameter.java_name() for parameter in self.parameters])
                )
            if self.return_field is not None:
                service_call = '__return_value = ' + service_call
            if len(self.throws) > 0:
                catches = ' '.join(["""\
catch (final %s e) {
    final java.io.StringWriter __httpServletResponseBodyWriter = new java.io.StringWriter();
    final org.thryft.protocol.OutputProtocol __oprot = new org.thryft.protocol.JacksonJsonOutputProtocol(__httpServletResponseBodyWriter);
    try {
        e.write(__oprot);
        __oprot.flush();
    } catch (final org.thryft.protocol.OutputProtocolException e1) {
        logger.error("error serializing service error response: ", e1);
        __httpServletResponse.sendError(500);
        return;
    }
    final String __httpServletResponseBody = __httpServletResponseBodyWriter.toString();
    __httpServletResponse.getWriter().write(__httpServletResponseBody);
    __httpServletResponse.setHeader("Content-Type", "application/json");
    __httpServletResponse.setHeader("Warning", e.getClass().getName());
    __httpServletResponse.setStatus(404);
    return;
}""" % throw.type.java_qname() for throw in self.throws])
                service_call = """\
try {
    %(service_call)s
} %(catches)s
""" % locals()
            sections.append(indent(' ' * 4, service_call))

            if self.return_field is None:
                write_response = """\
    __httpServletResponse.setStatus(204);"""
            elif isinstance(self.return_field.type, JavaBoolType):
                # assert self.java_rest_request_method() in ('DELETE', 'HEAD'), self.java_rest_request_method()
                write_response = """\
    if (__return_value) {
        __httpServletResponse.setStatus(204);
    } else {
        __httpServletResponse.setStatus(404);
    }""" % locals()
            else:
                return_write = \
                    indent(' ' * 8, self.return_field.type.java_write_protocol('__return_value'))
                if isinstance(self.return_field.type, _JavaBaseType):
                    return_ttype_id = self.return_field.type.thrift_ttype_id()
                    return_write = """\
        oprot.writeListBegin(new org.thryft.protocol.TList((byte)%(return_ttype_id)u, 1));
%(return_write)s
        oprot.writeListEnd();""" % locals()
                write_http_servlet_response_body = indent(' ' * 4, self._java_write_http_servlet_response_body(variable_name_prefix='__'))
                write_response = """\
    final java.io.StringWriter __httpServletResponseBodyWriter = new java.io.StringWriter();
    final org.thryft.protocol.OutputProtocol oprot = new org.thryft.protocol.JacksonJsonOutputProtocol(__httpServletResponseBodyWriter);
    try {
%(return_write)s
        oprot.flush();
    } catch (final org.thryft.protocol.OutputProtocolException e) {
        logger.error("error serializing service response: ", e);
        __httpServletResponse.sendError(500);
        return;
    }
    String __httpServletResponseBody = __httpServletResponseBodyWriter.toString();

    __httpServletResponse.setStatus(200);

%(write_http_servlet_response_body)s
""" % locals()
            sections.append(write_response)

            annotations = rpad("\n".join(annotations), "\n")
            sections = "\n\n".join(sections)

            return """\
%(annotations)sprivate void %(name)s(final javax.servlet.http.HttpServletRequest __httpServletRequest, final javax.servlet.http.HttpServletResponse __httpServletResponse) throws java.io.IOException, javax.servlet.ServletException {
%(sections)s
}
""" % locals()
示例#33
0
        def java_definition(self):
            annotations = rpad("\n".join(self.java_annotations()), "\n")
            name = self.java_name()
            request_type_name = self.java_request_type().java_name()
            service_qname = self.parent.java_qname()
            upper_camelized_name = upper_camelize(self.name)

            if len(self.parameters) > 0:
                read_request = """
    final %(service_qname)s.Messages.%(request_type_name)s serviceRequest;
    try {
        serviceRequest = %(service_qname)s.Messages.%(request_type_name)s.readAs(iprot, iprot.getCurrentFieldType(), unknownFieldCallback);
    } catch (final IllegalArgumentException | org.thryft.protocol.InputProtocolException | NullPointerException e) {
        logger.debug("error deserializing service request: ", e);
        __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, -32602, "invalid JSON-RPC request method parameters: " + String.valueOf(e.getMessage())), jsonRpcRequestId);
        return;
    }
""" % locals()
            else:
                read_request = ''
            parameters = ', '.join([
                'serviceRequest.' + parameter.java_getter_name() + '()'
                for parameter in self.parameters
            ])
            service_call = "service.%(name)s(%(parameters)s);" % locals()
            if self.return_field is not None:
                result_declaration = "    final %s result;\n" % self.return_field.type.java_qname(
                )
                service_call = 'result = ' + service_call
                write_result = self.return_field.type.java_write_protocol(
                    value='result')
            else:
                result_declaration = ''
                write_result = '''\
oprot.writeStructBegin("response");
oprot.writeStructEnd();
'''
            write_result = indent(' ' * 12, write_result)
            if len(self.throws) > 0:
                catches = ' '.join([
                    """\
catch (final %s e) {
    __doPostError(httpServletRequest, httpServletResponse, new org.thryft.protocol.JsonRpcErrorResponse(e, 1, e.getClass().getCanonicalName() + ": " + String.valueOf(e.getMessage())), jsonRpcRequestId);
    return;
}""" % throw.type.java_qname() for throw in self.throws
                ])
                service_call = """\
try {
    %(service_call)s
} %(catches)s
""" % locals()
            service_call = indent(' ' * 4, service_call)

            return """\
%(annotations)spublic void doPost%(upper_camelized_name)s(final javax.servlet.http.HttpServletRequest httpServletRequest, final javax.servlet.http.HttpServletResponse httpServletResponse, final org.thryft.protocol.JsonRpcInputProtocol iprot, final Object jsonRpcRequestId) throws java.io.IOException {%(read_request)s
%(result_declaration)s%(service_call)s

    final String httpServletResponseBody;
    {
        final java.io.StringWriter httpServletResponseBodyWriter = new java.io.StringWriter();
        try {
            final org.thryft.protocol.JsonRpcOutputProtocol oprot = new org.thryft.protocol.JsonRpcOutputProtocol(new org.thryft.protocol.JacksonJsonOutputProtocol(httpServletResponseBodyWriter));
            oprot.writeMessageBegin("", org.thryft.protocol.MessageType.REPLY, jsonRpcRequestId);
%(write_result)s
            oprot.writeMessageEnd();
            oprot.flush();
        } catch (final org.thryft.protocol.OutputProtocolException e) {
            logger.error("error serializing service error response: ", e);
            throw new IllegalStateException(e);
        }
        httpServletResponseBody = httpServletResponseBodyWriter.toString();
    }
    __doPostResponse(httpServletRequest, httpServletResponse, httpServletResponseBody);
}
""" % locals()