def __native_constructor_with_variable(self): space_str = '' native_constructor = indent(4) + 'private native long nativeCreate{0}('.format(self.__class_name) for space_index in range(0, len(indent(4) + 'private native long nativeCreate{0}('.format(self.__class_name))): space_str += ' ' for index in range(0, len(self.__java_var_list)): java_var = self.__java_var_list[index] java_var_type = java_var.var_type if index == 0: if java_var_type == VarType.cpp_enum: native_constructor += 'int {0},\n'.format(java_var.name_str) elif java_var_type == VarType.cpp_string_array: native_constructor += 'String[] {0},\n'.format(java_var.name_str) else: native_constructor += '{0} {1},\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str) else: if java_var_type == VarType.cpp_enum: native_constructor += space_str + 'int {0},\n'.format(java_var.name_str) elif java_var_type == VarType.cpp_string_array: native_constructor += space_str + 'String[] {0},\n'.format(java_var.name_str) else: native_constructor += space_str + '{0} {1},\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str) native_constructor = native_constructor[:-2] native_constructor += ');' + _JAVA_BR return native_constructor
def generate_fetch_native(self): """Gets fetch method JNI part implementation code. Paris with <generate_fetch>. Returns: Implementation of JNI part of fetch methods. """ fetch_function = '' for fetch_command in self.__fetch_commands: by_list = [] if fetch_command.where != '': by_list = re.split(',', fetch_command.where) if fetch_command.alias != '': fetch_fun_name_native = fetch_command.alias elif not fetch_command.is_plural: fetch_fun_name_native = 'Fetch{0}FromCache'.format(self.__object_name) else: fetch_fun_name_native = 'Fetch{0}FromCache'.format(self.__plural_object_name) if not fetch_command.is_plural: if len(by_list) == 0: skr_log_warning('Singular often comes with at least one by parameter') fetch_function += indent(4) + 'private native long native' + fetch_fun_name_native fetch_function += self.__convert_bys_to_string(by_list, True, False) + ';' + _JAVA_BR else: fetch_function += indent(4) + 'private native long[] native' + fetch_fun_name_native fetch_function += self.__convert_bys_to_string(by_list, True, False) + ';' + _JAVA_BR return fetch_function
def generate_fetch_native(self): """Gets fetch method JNI part implementation code. Paris with <generate_fetch>. Returns: Implementation of JNI part of fetch methods. """ fetch_function = '' for fetch_command in self.__fetch_commands: by_list = [] if fetch_command.where != '': by_list = re.split(',', fetch_command.where) if fetch_command.alias != '': fetch_fun_name_native = fetch_command.alias elif not fetch_command.is_plural: fetch_fun_name_native = 'Fetch{0}FromCache'.format( self.__object_name) else: fetch_fun_name_native = 'Fetch{0}FromCache'.format( self.__plural_object_name) if not fetch_command.is_plural: if len(by_list) == 0: skr_log_warning( 'Singular often comes with at least one by parameter') fetch_function += indent( 4) + 'private native long native' + fetch_fun_name_native fetch_function += self.__convert_bys_to_string( by_list, True, False) + ';' + _JAVA_BR else: fetch_function += indent( 4) + 'private native long[] native' + fetch_fun_name_native fetch_function += self.__convert_bys_to_string( by_list, True, False) + ';' + _JAVA_BR return fetch_function
def __http_function(self, api): http_function = indent(4) + 'public void ' + string_utils.first_char_to_lower(api.function_name) input_variable = self.__input_variable_declarations(api.input_var_list) http_function += '({0}{1}response){{\n'\ .format(input_variable, self.__variable_type_from_var_list(api.output_var_list)) http_function += indent(8) + 'm{0}Response'.format(api.function_name) + ' = response;\n' for variable in api.input_var_list: if variable.var_type == VarType.cpp_enum: http_function += indent(8) + 'int {0} = {1}.getValue();\n'\ .format(variable.name_str + "_int", variable.name_str) if variable.var_type == VarType.cpp_object: http_function += indent(8) + 'long {0} = {1}.getNativeHandler();\n'\ .format(variable.name_str + '_handler', variable.name_str) if variable.var_type == VarType.cpp_object_array: http_function += indent(8) + 'long[] {0} = new long[{1}.size()];\n'\ .format(variable.name_str + '_handler', variable.name_str) http_function += indent(8) + 'for (int i = 0; i < {0}.size(); i++){{\n'.format(variable.name_str) http_function += indent(12) + '{0}[i] = {1}.get(i).getNativeHandler();\n'\ .format(variable.name_str + '_handler', variable.name_str) http_function += indent(8) + '}' input_variable_call = self.__input_variable_call(api.input_var_list) http_function += indent(8) + 'native{0}(mNativeHandler{1});\n'\ .format(api.function_name, input_variable_call) http_function += indent(4) + "}" return http_function
def objc_form_cpp_parameter(self, indent, config): """From coreCalendar to LCCCallendar *calendar = [LCCCalendar calendarWithCoreCalendar:coreCalendar]; (Objc Array also is) """ objc_code = '' if self.var_type == VarType.cpp_object_array: objc_code += string_utils.indent(indent) objc_code += 'NSMutableArray *{0} = [NSMutableArray array];\n'.format( self.__objc_name()) objc_code += string_utils.indent(indent) objc_code += 'for (auto it = core{0}.begin(); it != core{0}.end(); ++it) {{\n'\ .format(self.to_title_style_name()) objc_code += string_utils.indent(2 + indent) objc_code += '[{0} addObject:[{3}{1} {2}WithCore{1}:**it]];\n'\ .format(self.__objc_name(), self.var_type.object_class_name, string_utils.first_char_to_lower(self.var_type.object_class_name), config.objc_prefix) objc_code += string_utils.indent(indent) objc_code += '}' elif self.var_type == VarType.cpp_object: objc_code += string_utils.indent(indent) objc_code += '{2}{0} *{1} = [LCC{0} {1}WithCore{0}:*core{0}];'\ .format(self.var_type.object_class_name, self.__objc_name(), config.objc_prefix) return objc_code
def __manager_http_implementation(self, api_description): capture_parameters = '' input_parameters = '' for input_var in api_description.input_var_list: input_parameters += input_var.name + ', ' if input_var.capture: capture_parameters += input_var.name + ', ' output_callback_parameters = '' output_parameters = '(bool success, const std::string &error' if len(api_description.output_var_list) > 0: for output_var in api_description.output_var_list: output_parameters += ', ' output_parameters += output_var.to_set_description_string() output_callback_parameters += ', ' output_callback_parameters += output_var.to_move_string() output_parameters += ')' impl = string_utils.indent(2) + 'WebApi::Api()->{0}({1}[{3}this, callback]{2} {{\n'.format(api_description.name, input_parameters, output_parameters, capture_parameters) impl += string_utils.indent(4) + 'if (success) {\n' for output_var in api_description.output_var_list: impl += self.__cpp_cache_by_cache_description_name(output_var.cache_desc, output_var.name) for extra in api_description.extra_list: impl += self.__cpp_cache_by_cache_description_name(extra) impl += string_utils.indent(4) + '}\n' impl += string_utils.indent(4) + 'callback(success, error{0});\n'.format(output_callback_parameters) impl += string_utils.indent(2) + '});' return impl
def __constructor_with_variable(self): constructor = indent(4) + 'public {0}('.format(self.__class_name) space = len(indent(4) + 'public {0}('.format(self.__class_name)) space_str = '' for space_index in range(0, space): space_str += ' ' for index in range(0, len(self.__java_var_list)): java_var = self.__java_var_list[index] java_var_type = java_var.var_type if index == 0: if java_var_type == VarType.cpp_enum: constructor += '{0} {1},\n'.format(java_var.java_enum, java_var.name_str) elif java_var_type == VarType.cpp_string_array: constructor += 'String[] {0},\n'.format(java_var.name_str) else: constructor += '{0} {1},\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str) else: if java_var_type == VarType.cpp_enum: constructor += space_str + '{0} {1},\n'.format(java_var.java_enum, java_var.name_str) elif java_var_type == VarType.cpp_string_array: constructor += space_str + 'String[] {0},\n'.format(java_var.name_str) else: constructor += space_str + '{0} {1},\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str) constructor = constructor[:-2] constructor += '){\n' constructor += indent(2) + 'mNativeHandler = nativeCreate{0}('.format(self.__class_name) for java_var in self.__java_var_list: if java_var.var_type == VarType.cpp_enum: constructor += java_var.name_str + '.getValue(), ' else: constructor += java_var.name_str + ', ' constructor = constructor[:-2] constructor += ');\n' constructor += indent(4) + '}' + _JAVA_BR return constructor
def __http_function(self, api): http_function = indent( 4) + 'public void ' + string_utils.first_char_to_lower( api.function_name) input_variable = self.__input_variable_declarations(api.input_var_list) http_function += '({0}{1}response){{\n'\ .format(input_variable, self.__variable_type_from_var_list(api.output_var_list)) http_function += indent(8) + 'm{0}Response'.format( api.function_name) + ' = response;\n' for variable in api.input_var_list: if variable.var_type == VarType.cpp_enum: http_function += indent(8) + 'int {0} = {1}.getValue();\n'\ .format(variable.name_str + "_int", variable.name_str) if variable.var_type == VarType.cpp_object: http_function += indent(8) + 'long {0} = {1}.getNativeHandler();\n'\ .format(variable.name_str + '_handler', variable.name_str) if variable.var_type == VarType.cpp_object_array: http_function += indent(8) + 'long[] {0} = new long[{1}.size()];\n'\ .format(variable.name_str + '_handler', variable.name_str) http_function += indent( 8) + 'for (int i = 0; i < {0}.size(); i++){{\n'.format( variable.name_str) http_function += indent(12) + '{0}[i] = {1}.get(i).getNativeHandler();\n'\ .format(variable.name_str + '_handler', variable.name_str) http_function += indent(8) + '}' input_variable_call = self.__input_variable_call(api.input_var_list) http_function += indent(8) + 'native{0}(mNativeHandler{1});\n'\ .format(api.function_name, input_variable_call) http_function += indent(4) + "}" return http_function
def generate_java(self): """Gets Java with JNI implementation. The class inherits from |CoreObject| which means invoker should release the object himself/herself by calling |CoreObject.dispose()|. New development should use <generate_java_v2> instead. Returns: A string which is the class implementation. """ file_name = self.__class_name + '.java' file_path = 'build/com/lesschat/core/' + self.__group_name + '/' + file_name output_java = open(file_path, 'w') java_package = 'package com.lesschat.core.' + self.__group_name + ';' output_java.write(java_package + _JAVA_BR) java_import = 'import android.os.Parcel;\n' java_import += 'import android.os.Parcelable;' + _JAVA_BR java_import += 'import com.lesschat.core.jni.CoreObject;' + _JAVA_BR java_import += 'import java.util.ArrayList;\n' java_import += 'import java.util.Arrays;\n' if self.__class_name != 'List': java_import += 'import java.util.List;' java_class_start = 'public class ' + self.__class_name + ' extends CoreObject implements Parcelable {' java_class_end = '}' output_java.write(java_import + _JAVA_BR) output_java.write(java_class_start + _JAVA_BR) output_java.write(self.__constructors()) output_java.write(indent(4) + '@Override\n') output_java.write(indent(4) + 'public void dispose() {\n') output_java.write( indent(2) + 'nativeRelease{0}(mNativeHandler);\n'.format(self.__class_name)) output_java.write(indent(4) + '}' + _JAVA_BR) for java_enum in self.__java_enum_list: output_java.write(java_enum.generate_java_enum(_JAVA_SPACE) + '\n') for java_var in self.__java_var_list: output_java.write(java_var.getter() + _JAVA_BR) output_java.write(_JAVA_BR) output_java.write(self.__native_constructors()) output_java.write( indent(4) + 'private native void nativeRelease{0}(long handler);'.format( self.__class_name) + _JAVA_BR) for java_var in self.__java_var_list: output_java.write(java_var.native_getter() + _JAVA_BR) output_java.write(self.__parcelable()) output_java.write(java_class_end)
def getter(self): """Getter method using JNI. New development should use <getter_v2>. Returns: Java getter method using JNI. For example: public int getPosition() { return nativeGetPosition(mNativeHandler); } """ function_str = '' if self.__var_type == VarType.cpp_bool: function_str += indent(1) + 'public {0} is{1}() {{\n'\ .format(self.__var_type.to_java_getter_setter_string(), self.__title_style_name) function_str += indent(2) + 'return nativeIs{0}(mNativeHandler);\n'.format(self.__title_style_name) function_str += indent(1) + '}' elif self.__var_type == VarType.cpp_string_array: function_str += self.__to_get_list_of_string_implementation() elif self.__var_type == VarType.cpp_enum: function_str += indent(1) + 'public {0} get{1}() {{\n'.format(self.__java_enum, self.__title_style_name) function_str += indent(2) + 'return {0}.get{0}ByValue(nativeGet{1}(mNativeHandler));\n'\ .format(self.__java_enum, self.__title_style_name) function_str += indent(1) + '}' else: function_str += indent(1) + 'public {0} get{1}() {{\n'.\ format(self.__var_type.to_java_getter_setter_string(), self.__title_style_name) function_str += indent(2) + 'return nativeGet{0}(mNativeHandler);\n'.format(self.__title_style_name) function_str += indent(1) + '}' return function_str
def generate_manager(self): if self.java_manager_or_none is None: return manager_name = self.java_manager_or_none.manager_name file_name = self.java_manager_or_none.manager_name + '.java' file_path = 'build/com/lesschat/core/' + self.group_name + '/' + file_name output_java = open(file_path, 'w') java_package = 'package com.lesschat.core.' + self.group_name + ';' output_java.write(java_package + _JAVA_BR) java_import = '' if len(self.java_manager_or_none.apis) != 0: java_import += 'import com.lesschat.core.api.*;\n' java_import += "import android.support.annotation.NonNull;" java_import += 'import com.lesschat.core.{0}.{1}.*;\n'.format( self.group_name, self.class_name) java_import += 'import com.lesschat.core.jni.CoreObject;\n' java_import += 'import com.lesschat.core.director.Director;\n' java_import += 'import com.lesschat.core.jni.JniHelper;\n\n' java_import += 'import java.util.ArrayList;\n' java_import += 'import java.util.List;' + _JAVA_BR java_class_start = 'public class ' + manager_name + ' extends CoreObject {' + _JAVA_BR java_class_end = '}' java_manager_constructor = 'public static @NonNull {0} getInstance() ' \ '{{ return Director.getInstance().get{0}();}}' java_override = '@Override\n' java_manager_dispose = 'public void dispose() { }' + _JAVA_BR output_java.write(java_import) output_java.write(java_class_start) output_java.write(self.java_manager_or_none.generate_http_variable()) output_java.write('\n') output_java.write( indent(1) + java_manager_constructor.format(manager_name) + _JAVA_BR) output_java.write(indent(1) + java_override) output_java.write(indent(1) + java_manager_dispose) output_java.write(self.java_manager_or_none.generate_fetch()) output_java.write(self.java_manager_or_none.generate_http_function()) output_java.write(self.java_manager_or_none.generate_fetch_native()) output_java.write( self.java_manager_or_none.generate_http_function_native()) output_java.write(java_class_end)
def generate_constructor_implementation(self): impl = '- (instancetype)init {\n' impl += string_utils.indent(2) impl += 'if (self = [super init]) {\n' impl += string_utils.indent(4) impl += '_coreManagerHandler = lesschat::{0}Manager::DefaultManager();\n'.format(self.object_name) impl += string_utils.indent(2) impl += '}\n' impl += string_utils.indent(2) impl += 'return self;\n' impl += '}' return impl
def __http_listener(self, api): http_listener = indent(4) + '@FunctionalInterface' + '\n' function_name = string_utils.first_char_to_upper(api.function_name) http_listener += indent( 4) + 'public interface On{0}Listener {{'.format( function_name) + '\n' http_listener += indent(8) + 'void on{0}('.format(function_name) http_listener += self.__output_variable_declaration_v2( api.output_var_list) http_listener += ');' + '\n' http_listener += indent(4) + '}' return http_listener
def generate_java(self): """Gets Java with JNI implementation. The class inherits from |CoreObject| which means invoker should release the object himself/herself by calling |CoreObject.dispose()|. New development should use <generate_java_v2> instead. Returns: A string which is the class implementation. """ file_name = self.__class_name + '.java' file_path = 'build/com/lesschat/core/' + self.__group_name + '/' + file_name output_java = open(file_path, 'w') java_package = 'package com.lesschat.core.' + self.__group_name + ';' output_java.write(java_package + _JAVA_BR) java_import = 'import android.os.Parcel;\n' java_import += 'import android.os.Parcelable;' + _JAVA_BR java_import += 'import com.lesschat.core.jni.CoreObject;' + _JAVA_BR java_import += 'import java.util.ArrayList;\n' java_import += 'import java.util.Arrays;\n' if self.__class_name != 'List': java_import += 'import java.util.List;' java_class_start = 'public class ' + self.__class_name + ' extends CoreObject implements Parcelable {' java_class_end = '}' output_java.write(java_import + _JAVA_BR) output_java.write(java_class_start + _JAVA_BR) output_java.write(self.__constructors()) output_java.write(indent(4) + '@Override\n') output_java.write(indent(4) + 'public void dispose() {\n') output_java.write(indent(2) + 'nativeRelease{0}(mNativeHandler);\n'.format(self.__class_name)) output_java.write(indent(4) + '}' + _JAVA_BR) for java_enum in self.__java_enum_list: output_java.write(java_enum.generate_java_enum(_JAVA_SPACE) + '\n') for java_var in self.__java_var_list: output_java.write(java_var.getter() + _JAVA_BR) output_java.write(_JAVA_BR) output_java.write(self.__native_constructors()) output_java.write(indent(4) + 'private native void nativeRelease{0}(long handler);'.format(self.__class_name) + _JAVA_BR) for java_var in self.__java_var_list: output_java.write(java_var.native_getter() + _JAVA_BR) output_java.write(self.__parcelable()) output_java.write(java_class_end)
def generate_constructor_implementation(self): impl = '- (instancetype)init {\n' impl += string_utils.indent(2) impl += 'if (self = [super init]) {\n' impl += string_utils.indent(4) impl += '_coreManagerHandler = lesschat::{0}Manager::DefaultManager();\n'.format( self.object_name) impl += string_utils.indent(2) impl += '}\n' impl += string_utils.indent(2) impl += 'return self;\n' impl += '}' return impl
def __http_function_response_v2(self, api): http_function_response = indent(4) + 'public void on{0}(boolean success, String error{1}){{\n' \ .format(api.function_name, self.__output_variable_declaration_v2(api.output_var_list)) http_function_response += indent(8) + 'if (m{0}Response == null){{\n'.format(api.function_name) http_function_response += indent(12) + 'return;\n' http_function_response += indent(8) + '}\n' http_function_response += indent(8) + 'if (success){\n' http_function_response += indent(12) + 'm{0}Response.onSuccess({1});\n' \ .format(api.function_name, self.__output_variable_call(api.output_var_list)) http_function_response += indent(8) + '} else {\n' http_function_response += indent(12) + 'm{0}Response.onFailure(error);\n'.format(api.function_name) http_function_response += indent(8) + '}\n' http_function_response += indent(4) + '}' return http_function_response
def objc_form_cpp_parameter(self, indent): objc_code = '' if self.var_type == VarType.cpp_object_array: objc_code += string_utils.indent(indent) objc_code += 'NSMutableArray *{0} = [NSMutableArray array];\n'.format(self.__objc_name()) objc_code += string_utils.indent(indent) objc_code += 'for (auto it = core{0}.begin(); it != core{0}.end(); ++it) {{\n'.format(self.to_title_style_name()) objc_code += string_utils.indent(2 + indent) objc_code += '[{0} addObject:[LCC{1} {2}WithCore{1}:**it]];\n'.format(self.__objc_name(), self.var_type.object_class_name, string_utils.first_char_to_lower(self.var_type.object_class_name)) objc_code += string_utils.indent(indent) objc_code += '}' elif self.var_type == VarType.cpp_object: objc_code += string_utils.indent(indent) objc_code += 'LCC{0} *{1} = [LCC{0} {1}WithCore{0}:*core{0}];'.format(self.var_type.object_class_name, self.__objc_name()) return objc_code
def __http_function_response_v2(self, api): http_function_response = indent(4) + 'public void on{0}(boolean success, String error, {1}){{\n' \ .format(api.function_name, self.__output_variable_declaration_v2(api.output_var_list)) http_function_response += indent( 8) + 'if (m{0}Response == null){{\n'.format(api.function_name) http_function_response += indent(12) + 'return;\n' http_function_response += indent(8) + '}\n' http_function_response += indent(8) + 'if (success){\n' http_function_response += indent(12) + 'm{0}Response.onSuccess({1});\n' \ .format(api.function_name, self.__output_variable_call(api.output_var_list)) http_function_response += indent(8) + '} else {\n' http_function_response += indent( 12) + 'm{0}Response.onFailure(error);\n'.format(api.function_name) http_function_response += indent(8) + '}\n' http_function_response += indent(4) + '}' return http_function_response
def __constructors(self): """Java class constructor with native handler as parameter. Returns: A string which is the implementation of the constructor. For example: public Task(long nativeHandler) { mNativeHandler = nativeHandler; } """ constructor = indent(4) + 'public {0}() {{ \n mNativeHandler = nativeCreate{0}(); \n }}'\ .format(self.__class_name) + _JAVA_BR constructor += indent(4) + 'public {0}(long nativeHandler) {{\n'.format(self.__class_name) constructor += indent(2) + 'mNativeHandler = nativeHandler;\n' constructor += indent(4) + '}\n\n' return constructor
def generate_web_api_implementations(self, config): """Generates Objective-C++ web api implementations. Args: config: A <Config> object represents user-defined info. Returns: A string which is Objective-C++ web api implementations. """ impl = '' for api in self.apis: impl += self.__web_api_declaration(api, config) impl += ' {\n' impl += string_utils.indent(2) impl += '_coreManagerHandler->\n' impl += string_utils.indent(2) impl += api.alias + '(' for input_var in api.input_var_list: impl += input_var.cast_to_cpp_parameter() impl += ', ' impl += '[successBlock, failureBlock](bool success, const std::string& errorUTF8String' for output_var in api.output_var_list: impl += ', {0}'.format(output_var.objc_wrapper_from_cpp_parameter(config)) impl += ') {\n' impl += string_utils.indent(4) impl += 'if (success) {\n' for output_var in api.output_var_list: impl += output_var.objc_form_cpp_parameter(6, config) impl += _OBJC_BR impl += string_utils.indent(6) impl += 'successBlock(' for i, output_var in enumerate(api.output_var_list): if i != 0: impl += ', ' impl += string_utils.to_objc_property_name(output_var.name) impl += ');\n' impl += string_utils.indent(4) impl += '} else {\n' impl += string_utils.indent(6) impl += 'NSString *error = [NSString stringWithUTF8String:errorUTF8String.c_str()];\n' impl += string_utils.indent(6) impl += 'failureBlock({0}(error));\n'.format(config.objc_error_method) impl += string_utils.indent(4) impl += '}\n' impl += string_utils.indent(2) impl += '});\n}' impl += _OBJC_BR return impl
def __to_get_list_of_string_implementation(self): function = indent(1) + 'public List<String> get{0}() {{\n'.format(self.__title_style_name) function += indent(2) + 'String[] strs = nativeGet{0}(mNativeHandler);\n'.format(self.__title_style_name) function += indent(2) + 'if (strs == null) {\n' function += indent(3) + 'return new ArrayList<String>();\n' function += indent(2) + '}\n' function += indent(2) + 'List<String> list = new ArrayList<String>(Arrays.asList(strs));\n' function += indent(2) + 'return list;\n' function += indent(1) + "}" return function
def generate_fetch_v2(self): """Gets fetch method implementation code. Paris with <generate_fetch_native_v2>. Returns: A string describes Java fetch method implementation code. """ fetch_function = '' for fetch_command in self.__fetch_commands: by_list = [] if fetch_command.where != '': by_list = re.split(',', fetch_command.where) if fetch_command.alias != '': fetch_fun_name = string_utils.first_char_to_lower( fetch_command.alias) fetch_fun_name_native = fetch_command.alias elif not fetch_command.is_plural: fetch_fun_name = 'fetch{0}FromCache'.format( self.__java_object_name()) fetch_fun_name_native = 'Fetch{0}FromCache'.format( self.__object_name) else: fetch_fun_name = 'fetch{0}FromCache'.format( self.__plural_object_name) fetch_fun_name_native = 'Fetch{0}FromCache'.format( self.__plural_object_name) if not fetch_command.is_plural: # singular implementation if len(by_list) == 0: skr_log_warning( 'Singular often comes with at least one by parameter') fetch_function += indent(4) + '@Nullable\n' fetch_function += indent(4) + 'public {0} '.format( self.__java_object_name()) fetch_function += fetch_fun_name + self.__convert_bys_to_string( by_list, False, False) + '{\n' parameters = self.__convert_bys_to_input_parameters(by_list) parameters_with_type = self.__convert_bys_to_string( by_list, False, False) parameters_for_func = re.sub('\([^]]*\)', parameters, parameters_with_type) fetch_function += indent(8) + 'return native{0}{1};\n'.format( fetch_fun_name_native, parameters_for_func) fetch_function += indent(4) + '}' + _JAVA_BR else: # regular implementation fetch_function += indent(4) + 'public {0}[] '.format( self.__java_object_name()) fetch_function += fetch_fun_name + self.__convert_bys_to_string( by_list, False, False) + ' {\n' parameters = self.__convert_bys_to_input_parameters(by_list) parameters_with_type = self.__convert_bys_to_string( by_list, False, False) parameters_for_func = re.sub('\([^]]*\)', parameters, parameters_with_type) fetch_function += indent(8) + 'return native{0}{1};\n'.format( fetch_fun_name_native, parameters_for_func) fetch_function += indent(4) + '}' + _JAVA_BR return fetch_function
def __constructors(self): """Java class constructor with native handler as parameter. Returns: A string which is the implementation of the constructor. For example: public Task(long nativeHandler) { mNativeHandler = nativeHandler; } """ constructor = indent(4) + 'public {0}() {{ \n mNativeHandler = nativeCreate{0}(); \n }}'\ .format(self.__class_name) + _JAVA_BR constructor += indent( 4) + 'public {0}(long nativeHandler) {{\n'.format( self.__class_name) constructor += indent(2) + 'mNativeHandler = nativeHandler;\n' constructor += indent(4) + '}\n\n' return constructor
def native_getter(self): """Gets Java native getter. Returns: Java native getter. For example: private native String nativeGetTaskId(long handler); """ if self.__var_type == VarType.cpp_bool: return indent(1) + 'private native {0} nativeIs{1}(long handler);'.format( self.__var_type.to_java_getter_setter_string(), self.__title_style_name) elif self.__var_type == VarType.cpp_string_array: return indent(1) + 'private native String[] nativeGet{0}(long handler);'.format(self.__title_style_name) elif self.__var_type == VarType.cpp_enum: return indent(1) + 'private native int nativeGet{0}(long handler);'.format(self.__title_style_name) else: return indent(1) + 'private native {0} nativeGet{1}(long handler);'.format( self.__var_type.to_java_getter_setter_string(),self.__title_style_name)
def __constructors_v2(self): """Java class constructor with all fields as parameters. Returns: A string which is the implementation of the constructor. For example: /*package*/ File(String fileId, @File.Type int type, @File.Visibility int visibility, @File.Belong int belong, @File.FolderPermissionSetting int folderPermissionSetting, String createdBy, long createdAt, String updatedBy, long updatedAt) { mFileId = fileId; ... Remainder omitted... } """ package_class = indent(4) + '/*package*/ {0}'.format(self.__class_name) num_line_indent = len(package_class) + 1 if len(self.__java_var_list) > 1: first_var = self.__java_var_list[0].input_parameter_name() constructor = '{0}({1},\n'.format(package_class, first_var) for var in self.__java_var_list: if first_var == var.input_parameter_name(): continue constructor += indent(num_line_indent) + '{0},'.format( var.input_parameter_name()) + '\n' constructor = constructor[:-2] # remove break line and last comma elif len(self.__java_var_list) == 1: first_var = self.__java_var_list[0].input_parameter_name() constructor = '{0}({1})'.format(package_class, first_var) else: constructor = '{0}()'.format(package_class) constructor += ') {\n' for var in self.__java_var_list: constructor += indent(8) + var.assignment() + '\n' constructor += indent(4) + '}' return constructor
def __constructors_v2(self): """Java class constructor with all fields as parameters. Returns: A string which is the implementation of the constructor. For example: /*package*/ File(String fileId, @File.Type int type, @File.Visibility int visibility, @File.Belong int belong, @File.FolderPermissionSetting int folderPermissionSetting, String createdBy, long createdAt, String updatedBy, long updatedAt) { mFileId = fileId; ... Remainder omitted... } """ package_class = indent(4) + '/*package*/ {0}'.format(self.__class_name) num_line_indent = len(package_class) + 1 if len(self.__java_var_list) > 1: first_var = self.__java_var_list[0].input_parameter_name() constructor = '{0}({1},\n'.format(package_class, first_var) for var in self.__java_var_list: if first_var == var.input_parameter_name(): continue constructor += indent(num_line_indent) + '{0},'.format(var.input_parameter_name()) + '\n' constructor = constructor[:-2] # remove break line and last comma elif len(self.__java_var_list) == 1: first_var = self.__java_var_list[0].input_parameter_name() constructor = '{0}({1})'.format(package_class, first_var) else: constructor = '{0}()'.format(package_class) constructor += ') {\n' for var in self.__java_var_list: constructor += indent(8) + var.assignment() + '\n' constructor += indent(4) + '}' return constructor
def __constructor_with_variable(self): constructor = indent(4) + 'public {0}('.format(self.__class_name) space = len(indent(4) + 'public {0}('.format(self.__class_name)) space_str = '' for space_index in range(0, space): space_str += ' ' for index in range(0, len(self.__java_var_list)): java_var = self.__java_var_list[index] java_var_type = java_var.var_type if index == 0: if java_var_type == VarType.cpp_enum: constructor += '{0} {1},\n'.format(java_var.java_enum, java_var.name_str) elif java_var_type == VarType.cpp_string_array: constructor += 'String[] {0},\n'.format(java_var.name_str) else: constructor += '{0} {1},\n'.format( java_var.var_type.to_java_getter_setter_string(), java_var.name_str) else: if java_var_type == VarType.cpp_enum: constructor += space_str + '{0} {1},\n'.format( java_var.java_enum, java_var.name_str) elif java_var_type == VarType.cpp_string_array: constructor += space_str + 'String[] {0},\n'.format( java_var.name_str) else: constructor += space_str + '{0} {1},\n'.format( java_var.var_type.to_java_getter_setter_string(), java_var.name_str) constructor = constructor[:-2] constructor += '){\n' constructor += indent(2) + 'mNativeHandler = nativeCreate{0}('.format( self.__class_name) for java_var in self.__java_var_list: if java_var.var_type == VarType.cpp_enum: constructor += java_var.name_str + '.getValue(), ' else: constructor += java_var.name_str + ', ' constructor = constructor[:-2] constructor += ');\n' constructor += indent(4) + '}' + _JAVA_BR return constructor
def generate_http_function_native(self): """Gets HTTP request native code. Returns: HTTP request native code. """ http_native_function = '' for api in self.__apis: http_native_function += indent(4) + 'private native void native{0}(long handler{1});\n\n' \ .format(api.function_name, self.__input_variable_declarations_native(api.input_var_list)) return http_native_function
def generate_constructor_implementation(self, config): """Generates Objective-C++ init method. Args: config: A <Config> object represents user-defined info. Returns: Objective-C++ init method. """ impl = '- (instancetype)init {\n' impl += string_utils.indent(2) impl += 'if (self = [super init]) {\n' impl += string_utils.indent(4) impl += '_coreManagerHandler = {1}::{0}Manager::DefaultManager();\n'.format(self.object_name, config.cpp_namespace) impl += string_utils.indent(2) impl += '}\n' impl += string_utils.indent(2) impl += 'return self;\n' impl += '}' return impl
def objc_form_cpp_parameter(self, indent): objc_code = '' if self.var_type == VarType.cpp_object_array: objc_code += string_utils.indent(indent) objc_code += 'NSMutableArray *{0} = [NSMutableArray array];\n'.format( self.__objc_name()) objc_code += string_utils.indent(indent) objc_code += 'for (auto it = core{0}.begin(); it != core{0}.end(); ++it) {{\n'.format( self.to_title_style_name()) objc_code += string_utils.indent(2 + indent) objc_code += '[{0} addObject:[LCC{1} {2}WithCore{1}:**it]];\n'.format( self.__objc_name(), self.var_type.object_class_name, string_utils.first_char_to_lower( self.var_type.object_class_name)) objc_code += string_utils.indent(indent) objc_code += '}' elif self.var_type == VarType.cpp_object: objc_code += string_utils.indent(indent) objc_code += 'LCC{0} *{1} = [LCC{0} {1}WithCore{0}:*core{0}];'.format( self.var_type.object_class_name, self.__objc_name()) return objc_code
def __manager_http_implementation(self, api_description): capture_parameters = '' input_parameters = '' for input_var in api_description.input_var_list: input_parameters += input_var.name + ', ' if input_var.capture: capture_parameters += input_var.name + ', ' output_callback_parameters = '' output_parameters = '(bool success, const std::string &error' if len(api_description.output_var_list) > 0: for output_var in api_description.output_var_list: output_parameters += ', ' output_parameters += output_var.to_set_description_string() output_callback_parameters += ', ' output_callback_parameters += output_var.to_move_string() output_parameters += ')' impl = string_utils.indent( 2) + 'WebApi::Api()->{0}({1}[{3}this, callback]{2} {{\n'.format( api_description.name, input_parameters, output_parameters, capture_parameters) impl += string_utils.indent(4) + 'if (success) {\n' for output_var in api_description.output_var_list: impl += self.__cpp_cache_by_cache_description_name( output_var.cache_desc, output_var.name) for extra in api_description.extra_list: impl += self.__cpp_cache_by_cache_description_name(extra) impl += string_utils.indent(4) + '}\n' impl += string_utils.indent( 4) + 'callback(success, error{0});\n'.format( output_callback_parameters) impl += string_utils.indent(2) + '});' return impl
def __generate_post_or_put_body(self, api_description): if api_description.method == 'POST' or api_description.method == 'PUT': valid_var_list = [] for input_var in api_description.input_var_list: if input_var.json_path is not None and input_var.json_path != '': valid_var_list.append(input_var) if len(valid_var_list) == 0: return '' body = string_utils.indent(2) + 'json11::Json put_or_post_json = json11::Json::object {\n' for var in valid_var_list: json_paths = re.split('/', var.json_path) if len(json_paths) > 2: print 'We do not support ugly json which has more than 2 levels' assert False elif len(json_paths) == 1: body += string_utils.indent(4) + '{{ "{0}", {1} }},\n'.format(var.json_path, var.to_json11_type()) elif len(json_paths) == 2: body += string_utils.indent(4) + '{{ "{0}", json11::Json::object {{{{ "{1}", {2} }}}} }},\n'.format(json_paths[0], json_paths[1], var.to_json11_type()) body += string_utils.indent(2) + '};\n' body += string_utils.indent(2) + 'string put_or_post_json_str = put_or_post_json.dump();' + _CPP_BR body += string_utils.indent(2) + 'request->set_request_data(put_or_post_json_str);' + _CPP_BR return body else: print 'Only PUT or POST method can have request_body' return ''
def generate_web_api_implementations(self): impl = '' for api in self.apis: impl += self.__web_api_declaration(api) impl += ' {\n' impl += string_utils.indent(2) impl += '_coreManagerHandler->\n' impl += string_utils.indent(2) impl += api.alias + '(' for input_var in api.input_var_list: impl += input_var.cast_to_cpp_parameter() impl += ', ' impl += '[successBlock, failureBlock](bool success, const std::string& errorUTF8String' for output_var in api.output_var_list: impl += ', {0}'.format( output_var.objc_wrapper_from_cpp_parameter()) impl += ') {\n' impl += string_utils.indent(4) impl += 'if (success) {\n' for output_var in api.output_var_list: impl += output_var.objc_form_cpp_parameter(6) impl += _OBJC_BR impl += string_utils.indent(6) impl += 'successBlock(' for i, output_var in enumerate(api.output_var_list): if i != 0: impl += ', ' impl += string_utils.to_objc_property_name(output_var.name) impl += ');\n' impl += string_utils.indent(4) impl += '} else {\n' impl += string_utils.indent(6) impl += 'NSString *error = [NSString stringWithUTF8String:errorUTF8String.c_str()];\n' impl += string_utils.indent(6) impl += 'failureBlock(LCCErrorWithNSString(error));\n' impl += string_utils.indent(4) impl += '}\n' impl += string_utils.indent(2) impl += '});\n}' impl += _OBJC_BR return impl
def __native_constructor_with_variable(self): space_str = '' native_constructor = indent( 4) + 'private native long nativeCreate{0}('.format( self.__class_name) for space_index in range( 0, len( indent(4) + 'private native long nativeCreate{0}('.format( self.__class_name))): space_str += ' ' for index in range(0, len(self.__java_var_list)): java_var = self.__java_var_list[index] java_var_type = java_var.var_type if index == 0: if java_var_type == VarType.cpp_enum: native_constructor += 'int {0},\n'.format( java_var.name_str) elif java_var_type == VarType.cpp_string_array: native_constructor += 'String[] {0},\n'.format( java_var.name_str) else: native_constructor += '{0} {1},\n'.format( java_var.var_type.to_java_getter_setter_string(), java_var.name_str) else: if java_var_type == VarType.cpp_enum: native_constructor += space_str + 'int {0},\n'.format( java_var.name_str) elif java_var_type == VarType.cpp_string_array: native_constructor += space_str + 'String[] {0},\n'.format( java_var.name_str) else: native_constructor += space_str + '{0} {1},\n'.format( java_var.var_type.to_java_getter_setter_string(), java_var.name_str) native_constructor = native_constructor[:-2] native_constructor += ');' + _JAVA_BR return native_constructor
def parse_json(self, indent=0): if self.json_path == '': return '' json_paths = re.split('/', self.json_path) cpp_json_paths = '' for json_path in json_paths: cpp_json_paths += '["{0}"]'.format(json_path) if self.var_type == VarType.cpp_enum: # need cast return '{0}_ = static_cast<{3}>(json_obj{1}.{2});'.format(self.name, cpp_json_paths, self.var_type.to_json_value_type(), self.var_type.cpp_enum_type_string()) elif self.var_type == VarType.cpp_string_array: # array_items use another parse style parse = '{0}_.clear();\n'.format(self.name) parse += ' vector<json11::Json> {0}_json = json_obj{1}.array_items();\n'.format(self.name, cpp_json_paths) parse += ' for (auto it = {0}_json.begin(); it != {0}_json.end(); ++it) {{\n'.format(self.name) parse += ' {0}_.push_back((*it){1}.string_value());\n'.format(self.name, self.var_type.cpp_json11_array_it_search_string()) parse += ' }\n' return parse elif self.var_type == VarType.cpp_bool: # bool value should compact with int_value == 1 parse = 'json11::Json {0}_json = json_obj{1};\n'.format(self.name, cpp_json_paths) parse += ' if ({0}_json.type() == json11::Json::Type::BOOL) {{\n'.format(self.name) parse += ' {0}_ = {0}_json.bool_value();\n'.format(self.name) parse += ' } else {\n' parse += ' {0}_ = ({0}_json.int_value() == 1);\n'.format(self.name) parse += ' }\n' return parse elif self.var_type == VarType.cpp_object: # C++ object parse = string_utils.indent(indent) + 'unique_ptr<{0}> {1}(new {0}());\n'.format(self.var_type.object_class_name, self.name) parse += string_utils.indent(indent) + '{0}->InitWithJsonOrDie(json_obj{1}.dump());\n'.format(self.name, cpp_json_paths) return parse elif self.var_type == VarType.cpp_object_array: # C++ objects parse = string_utils.indent(indent) + 'vector<unique_ptr<{0}>> {1};\n'.format(self.var_type.object_class_name, self.name) parse += string_utils.indent(indent) + 'vector<json11::Json> {0}_jsons = json_obj{1}.array_items();\n'.format(self.name, cpp_json_paths) parse += string_utils.indent(indent) + 'for (auto json : {0}_jsons) {{\n'.format(self.name) parse += string_utils.indent(indent + 2) + 'unique_ptr<{0}> obj(new {0}());\n'.format(self.var_type.object_class_name) parse += string_utils.indent(indent + 2) + 'obj->InitWithJsonOrDie(json.dump());\n' parse += string_utils.indent(indent + 2) + '{0}.push_back(std::move(obj));\n'.format(self.name) parse += string_utils.indent(indent) + '}\n' return parse else: return '{0}_ = json_obj{1}.{2};'.format(self.name, cpp_json_paths, self.var_type.to_json_value_type())
def generate_http_function_native(self): """Gets HTTP request native code. Returns: HTTP request native code. """ http_native_function = '' for api in self.__apis: http_response = self.__http_response_listener(api) http_response += ' success, OnFailureListener failure' http_native_function += indent(4) + 'private native void native{0}(long handler{1}, {2});\n\n' \ .format(api.function_name, self.__input_variable_declarations_native(api.input_var_list), http_response) return http_native_function
def generate_web_api_implementations(self): impl = '' for api in self.apis: impl += self.__web_api_declaration(api) impl += ' {\n' impl += string_utils.indent(2) impl += '_coreManagerHandler->\n' impl += string_utils.indent(2) impl += api.alias + '(' for input_var in api.input_var_list: impl += input_var.cast_to_cpp_parameter() impl += ', ' impl += '[successBlock, failureBlock](bool success, const std::string& errorUTF8String' for output_var in api.output_var_list: impl += ', {0}'.format(output_var.objc_wrapper_from_cpp_parameter()) impl += ') {\n' impl += string_utils.indent(4) impl += 'if (success) {\n' for output_var in api.output_var_list: impl += output_var.objc_form_cpp_parameter(6) impl += _OBJC_BR impl += string_utils.indent(6) impl += 'successBlock(' for i, output_var in enumerate(api.output_var_list): if i != 0: impl += ', ' impl += string_utils.to_objc_property_name(output_var.name) impl += ');\n' impl += string_utils.indent(4) impl += '} else {\n' impl += string_utils.indent(6) impl += 'NSString *error = [NSString stringWithUTF8String:errorUTF8String.c_str()];\n' impl += string_utils.indent(6) impl += 'failureBlock(LCCErrorWithNSString(error));\n' impl += string_utils.indent(4) impl += '}\n' impl += string_utils.indent(2) impl += '});\n}' impl += _OBJC_BR return impl
def generate_http_variables(self): """Gets HTTP response fields implementation. Returns: A string that describes HTTP response fields. For example: private WebApiWithListResponse mGetTasksAssignedToMeResponse; """ api_response_variable = '' for api in self.__apis: variable_name = 'm{0}Response'.format(api.function_name) variable_type = self.__variable_type_from_var_list(api.output_var_list) api_response_variable += indent(4) + 'private ' + variable_type + variable_name + ';\n' return api_response_variable
def generate_web_api_implementation(self): impl = '#include "web_api.h"\n\n#include "json11/json11.hpp"\n\n#include "utils/string_utils.h"\n#include "utils/json11_utils.h"\n\n' impl += 'using std::string;\nusing std::vector;\nusing std::unique_ptr;\n\nusing sakura::HttpRequest;\nusing sakura::HttpClient;\nusing sakura::HttpResponse;\n\n' impl += 'NS_LCC_BEGIN\n\n' impl += '////////////////////////////////////////////////////////////////////////////////\n' impl += '// WebApi, public:\n\n' impl += '// {0} --------------------------------------------------------'.format(self.object_name) impl += _CPP_BR for api in self.apis: impl += 'void WebApi::{0}({1}) {{\n'.format(api.name, self.__api_parameters_declaration(api)) impl += string_utils.indent(2) + self.__api_implementation(api) + '\n' impl += '}' impl += _CPP_BR impl += 'NS_LCC_END' return impl
def objc_form_cpp_parameter(self, indent, config): """From coreCalendar to LCCCallendar *calendar = [LCCCalendar calendarWithCoreCalendar:coreCalendar]; (Objc Array also is) """ objc_code = '' if self.var_type == VarType.cpp_object_array: objc_code += string_utils.indent(indent) objc_code += 'NSMutableArray *{0} = [NSMutableArray array];\n'.format(self.__objc_name()) objc_code += string_utils.indent(indent) objc_code += 'for (auto it = core{0}.begin(); it != core{0}.end(); ++it) {{\n'\ .format(self.to_title_style_name()) objc_code += string_utils.indent(2 + indent) objc_code += '[{0} addObject:[{3}{1} {2}WithCore{1}:**it]];\n'\ .format(self.__objc_name(), self.var_type.object_class_name, string_utils.first_char_to_lower(self.var_type.object_class_name), config.objc_prefix) objc_code += string_utils.indent(indent) objc_code += '}' elif self.var_type == VarType.cpp_object: objc_code += string_utils.indent(indent) objc_code += '{2}{0} *{1} = [LCC{0} {1}WithCore{0}:*core{0}];'\ .format(self.var_type.object_class_name, self.__objc_name(), config.objc_prefix) return objc_code
def generate_http_variables(self): """Gets HTTP response fields implementation. Returns: A string that describes HTTP response fields. For example: private WebApiWithListResponse mGetTasksAssignedToMeResponse; """ api_response_variable = '' for api in self.__apis: variable_name = 'm{0}Response'.format(api.function_name) variable_type = self.__variable_type_from_var_list( api.output_var_list) api_response_variable += indent( 4) + 'private ' + variable_type + variable_name + ';\n' return api_response_variable
def generate_web_api_implementation(self): impl = '#include "web_api.h"\n\n#include "json11/json11.hpp"\n\n#include "utils/string_utils.h"\n#include "utils/json11_utils.h"\n\n' impl += 'using std::string;\nusing std::vector;\nusing std::unique_ptr;\n\nusing sakura::HttpRequest;\nusing sakura::HttpClient;\nusing sakura::HttpResponse;\n\n' impl += 'NS_LCC_BEGIN\n\n' impl += '////////////////////////////////////////////////////////////////////////////////\n' impl += '// WebApi, public:\n\n' impl += '// {0} --------------------------------------------------------'.format( self.object_name) impl += _CPP_BR for api in self.apis: impl += 'void WebApi::{0}({1}) {{\n'.format( api.name, self.__api_parameters_declaration(api)) impl += string_utils.indent(2) + self.__api_implementation( api) + '\n' impl += '}' impl += _CPP_BR impl += 'NS_LCC_END' return impl
def generate_fetch_v2(self): """Gets fetch method implementation code. Paris with <generate_fetch_native_v2>. Returns: A string describes Java fetch method implementation code. """ fetch_function = '' for fetch_command in self.__fetch_commands: by_list = [] if fetch_command.where != '': by_list = re.split(',', fetch_command.where) if fetch_command.alias != '': fetch_fun_name = string_utils.first_char_to_lower(fetch_command.alias) fetch_fun_name_native = fetch_command.alias elif not fetch_command.is_plural: fetch_fun_name = 'fetch{0}FromCache'.format(self.__java_object_name()) fetch_fun_name_native = 'Fetch{0}FromCache'.format(self.__object_name) else: fetch_fun_name = 'fetch{0}FromCache'.format(self.__plural_object_name) fetch_fun_name_native = 'Fetch{0}FromCache'.format(self.__plural_object_name) if not fetch_command.is_plural: # singular implementation if len(by_list) == 0: skr_log_warning('Singular often comes with at least one by parameter') fetch_function += indent(4) + '@Nullable\n' fetch_function += indent(4) + 'public {0} '.format(self.__java_object_name()) fetch_function += fetch_fun_name + self.__convert_bys_to_string(by_list, False, False) + '{\n' parameters = self.__convert_bys_to_input_parameters(by_list) parameters_with_type = self.__convert_bys_to_string(by_list, False, False) parameters_for_func = re.sub('\([^]]*\)', parameters, parameters_with_type) fetch_function += indent(8) + 'return native{0}{1};\n'.format(fetch_fun_name_native, parameters_for_func) fetch_function += indent(4) + '}' + _JAVA_BR else: # regular implementation fetch_function += indent(4) + 'public {0}[] '.format(self.__java_object_name()) fetch_function += fetch_fun_name + self.__convert_bys_to_string(by_list, False, False) + ' {\n' parameters = self.__convert_bys_to_input_parameters(by_list) parameters_with_type = self.__convert_bys_to_string(by_list, False, False) parameters_for_func = re.sub('\([^]]*\)', parameters, parameters_with_type) fetch_function += indent(8) + 'return native{0}{1};\n'.format(fetch_fun_name_native, parameters_for_func) fetch_function += indent(4) + '}' + _JAVA_BR return fetch_function
def __generate_post_or_put_body(self, api_description): if api_description.method == 'POST' or api_description.method == 'PUT': valid_var_list = [] for input_var in api_description.input_var_list: if input_var.json_path is not None and input_var.json_path != '': valid_var_list.append(input_var) if len(valid_var_list) == 0: return '' body = string_utils.indent( 2) + 'json11::Json put_or_post_json = json11::Json::object {\n' for var in valid_var_list: json_paths = re.split('/', var.json_path) if len(json_paths) > 2: print 'We do not support ugly json which has more than 2 levels' assert False elif len(json_paths) == 1: body += string_utils.indent( 4) + '{{ "{0}", {1} }},\n'.format( var.json_path, var.to_json11_type()) elif len(json_paths) == 2: body += string_utils.indent( 4 ) + '{{ "{0}", json11::Json::object {{{{ "{1}", {2} }}}} }},\n'.format( json_paths[0], json_paths[1], var.to_json11_type()) body += string_utils.indent(2) + '};\n' body += string_utils.indent( 2 ) + 'string put_or_post_json_str = put_or_post_json.dump();' + _CPP_BR body += string_utils.indent( 2 ) + 'request->set_request_data(put_or_post_json_str);' + _CPP_BR return body else: print 'Only PUT or POST method can have request_body' return ''
def __parcelable(self): parcelable = indent(4) + 'public {0}(Parcel in) {{\n'.format( self.__class_name) parcelable += indent(2) + 'mNativeHandler = in.readLong();\n' parcelable += indent(4) + '}' + _JAVA_BR parcelable += indent(4) + 'public static final Parcelable.Creator<{0}> CREATOR = new Parcelable.Creator<{0}>() {{\n\n'\ .format(self.__class_name) parcelable += indent(2) + 'public {0} createFromParcel(Parcel in) {{ return new {0}(in); }}\n\n'\ .format(self.__class_name) parcelable += indent(2) + 'public {0}[] newArray(int size) {{ return new {0}[size]; }}\n'\ .format(self.__class_name) parcelable += indent(4) + '};' + _JAVA_BR parcelable += indent(4) + '@Override\n' parcelable += indent( 4) + 'public int describeContents() { return 0; }' + _JAVA_BR parcelable += indent(4) + '@Override\n' parcelable += indent( 4 ) + 'public void writeToParcel(Parcel parcel, int i) { parcel.writeLong(mNativeHandler); }\n' parcelable += '\n' return parcelable
def __native_initwith(self): native_initwith = indent( 4 ) + 'private native boolean nativeInitWithJson(long handler, String json);' native_initwith += _JAVA_BR return native_initwith
def __initwith(self): initwith = indent( 4 ) + 'public boolean initWithJson(String json) { return nativeInitWithJson(mNativeHandler, json); }' initwith += _JAVA_BR return initwith
def generate_fetch(self): """Gets fetch method implementation code. Paris with <generate_fetch_native>. New development should use <generate_fetch_v2>. Returns: A string describes Java fetch method implementation code. """ fetch_function = '' for fetch_command in self.__fetch_commands: by_list = [] if fetch_command.where != '': by_list = re.split(',', fetch_command.where) if fetch_command.alias != '': fetch_fun_name = string_utils.first_char_to_lower(fetch_command.alias) fetch_fun_name_native = fetch_command.alias elif not fetch_command.is_plural: fetch_fun_name = 'fetch{0}FromCache'.format(self.__java_object_name()) fetch_fun_name_native = 'Fetch{0}FromCache'.format(self.__object_name) else: fetch_fun_name = 'fetch{0}FromCache'.format(self.__plural_object_name) fetch_fun_name_native = 'Fetch{0}FromCache'.format(self.__plural_object_name) if not fetch_command.is_plural: if len(by_list) == 0: skr_log_warning('Singular often comes with at least one by parameter') fetch_function += indent(4) + 'public {0} '.format(self.__java_object_name()) fetch_function += fetch_fun_name + self.__convert_bys_to_string(by_list, False, False) + '{\n' fetch_function += indent(8) + 'long handler = native' + fetch_fun_name_native fetch_function += self.__convert_bys_to_string(by_list, False, True) + ';\n\n' fetch_function += indent(8) + 'if (handler == JniHelper.sNullPointer) {\n' fetch_function += indent(12) + 'return null;\n' fetch_function += indent(8) + '}\n\n' fetch_function += indent(8) + 'return new {0}(handler);\n'.format(self.__java_object_name()) fetch_function += indent(4) + '}' + _JAVA_BR else: fetch_function += indent(4) + 'public List<{0}> '.format(self.__java_object_name()) fetch_function += fetch_fun_name + self.__convert_bys_to_string(by_list, False, False) + ' {\n' fetch_function += indent(8) + 'long[] handlers = native' + fetch_fun_name_native fetch_function += self.__convert_bys_to_string(by_list, False, True) + ';\n\n' fetch_function += indent(8) + 'List<{0}> {1} = new ArrayList<>();\n'\ .format(self.__java_object_name(), self.__to_object_name_java_style() + 's') fetch_function += indent(8) + 'for (long handler: handlers) {\n' fetch_function += indent(12) + '{0}.add(new {1}(handler));\n'\ .format(self.__to_object_name_java_style() + 's', self.__java_object_name()) fetch_function += indent(8) + '}\n\n' fetch_function += indent(8) + 'return {0};\n'\ .format(self.__to_object_name_java_style() + 's') fetch_function += indent(4) + '}' + _JAVA_BR return fetch_function
def __native_constructors(self): native_constructor = indent( 4) + 'private native long nativeCreate{0}();'.format( self.__class_name) + _JAVA_BR # native_constructor += self.__native_constructor_with_variable() return native_constructor
def __http_function_response(self, api): http_function_response = indent(4) + 'public void on{0}(boolean success, String error{1}){{\n'\ .format(api.function_name, self.__output_variable_declaration(api.output_var_list)) http_function_response += indent(8) + 'if (m{0}Response == null){{\n'.format(api.function_name) http_function_response += indent(12) + 'return;\n' http_function_response += indent(8) + '}\n' http_function_response += indent(8) + 'if (success){\n' for variable in api.output_var_list: if variable.var_type == VarType.cpp_enum: http_function_response += indent(12) + '{0}.{1} {2} = {0}.{1}.get{1}ByValue({3});\n'\ .format(self.__object_name, variable.var_type.to_java_getter_setter_string(), variable.name_str, variable.name_str + '_int') if variable.var_type == VarType.cpp_object: http_function_response += indent(12) + '{0} {1} = new {0}({1}_handler);\n'\ .format(variable.var_type.to_java_getter_setter_string(), variable.name_str) if variable.var_type == VarType.cpp_object_array: http_function_response += indent(12) + 'ArrayList<CoreObject> {0} = new ArrayList<>();\n'\ .format(variable.name_str) http_function_response += indent(12) + 'for (long handler : {0}_handler){{\n'\ .format(variable.name_str) http_function_response += indent(16) + '{0}.add(new {1}(handler));\n'\ .format(variable.name_str, variable.var_type.object_class_name) http_function_response += indent(12) + '}\n' http_function_response += indent(12) + 'm{0}Response.onSuccess({1});\n'\ .format(api.function_name, self.__output_variable_call(api.output_var_list)) http_function_response += indent(8) + '} else {\n' http_function_response += indent(12) + 'm{0}Response.onFailure(error);\n'.format(api.function_name) http_function_response += indent(8) + '}\n' http_function_response += indent(4) + '}' return http_function_response
def __api_implementation(self, api_description): var_names_or_none = string_utils.strings_or_none_in_brackets(api_description.uri) cpp_uri = '' if var_names_or_none is not None: cpp_uri = '"' cpp_uri += api_description.uri for var_name in var_names_or_none: cpp_var = self.__find_cpp_var_by_name(var_name, api_description.input_var_list) cpp_uri = cpp_uri.replace('[{0}]'.format(var_name), '[{0}]'.format(cpp_var.to_convert_to_string_description())) cpp_uri = cpp_uri.replace('[', '" + ') cpp_uri = cpp_uri.replace(']', ' + "') cpp_uri += '"' check_cpp_uri = cpp_uri[-5:] if check_cpp_uri == ' + ""': # parameter is the last component cpp_uri = cpp_uri[:-5] else: cpp_uri = '"{0}"'.format(api_description.uri) impl = 'string api_path = {0};'.format(cpp_uri) impl += '\n' impl += string_utils.indent(2) + 'string url = BaseUrlForCurrentTeam() + api_path;' + _CPP_BR impl += string_utils.indent(2) + 'unique_ptr<HttpRequest> request = GenBaseRequestForCurrentTeam(HttpRequest::Type::{0});\n'.format(api_description.method) impl += string_utils.indent(2) + 'request->set_url(url);' + _CPP_BR impl += self.__generate_post_or_put_body(api_description) impl += string_utils.indent(2) + 'HttpClient::SharedClient()->\n' impl += string_utils.indent(2) + 'Send(std::move(request), [callback](unique_ptr<HttpResponse> response) {\n' impl += string_utils.indent(4) + 'if (response->is_succeed()) {\n' impl += string_utils.indent(6) + 'string error;\n' impl += string_utils.indent(6) + 'json11::Json json_obj = json11::Json::parse(response->response_data_as_string(), error);\n' impl += string_utils.indent(6) + 'int state_code = json_obj[kJsonKeyState].int_value();\n' impl += string_utils.indent(6) + 'if (state_code == 200) {\n' output_success_parameters = '' output_fail_parameters = '' for output_var in api_description.output_var_list: impl += output_var.parse_json(8) impl += '\n' output_success_parameters += ', ' output_success_parameters += output_var.to_move_string() output_fail_parameters += ', ' output_fail_parameters += output_var.to_null_string() impl += string_utils.indent(8) + 'callback(true, ""{0});\n'.format(output_success_parameters) impl += string_utils.indent(6) + '} else {\n' impl += string_utils.indent(8) + 'string ret_error = ErrorMessageFromStateCode(state_code);\n' impl += string_utils.indent(8) + 'callback(false, ret_error{0});\n'.format(output_fail_parameters) impl += string_utils.indent(6) + '}\n' impl += string_utils.indent(4) + '} else {\n' impl += string_utils.indent(6) + 'string ret_error = response->error_buffer();\n' impl += string_utils.indent(6) + 'callback(false, ret_error{0});\n'.format(output_fail_parameters) impl += string_utils.indent(4) + '}\n' impl += string_utils.indent(2) + '});' return impl
def __cpp_cache_by_cache_description_name(self, cache_desc, name=''): cache_attr = cache_desc if cache_attr is None or cache_attr == '': # if no 'cache' return '' impl = '' caches = re.split(',', cache_attr) for cache in caches: if cache[0] == '#': # if define impl += string_utils.indent(6) + self.__find_replace_string_by_name(cache[1:]) + '\n' else: # if by command cpp_class = 'this->' method = '' # command_components[0]: save(s)/delete(s)/update(s) # command_components[1]: (id, project_id) - replace string command_components = re.split('\(', cache) sql_verb = command_components[0] parameters = '' num_parameters = 0 if len(command_components) == 2: parameters = command_components[1] parameters = parameters[:-1] num_parameters = len(re.split(',', parameters)) else: parameters = name num_parameters = 0 if sql_verb == 'saves': method = 'Save{0}ToCache({1});\n'.format(self.plural_object_name, name) elif sql_verb == 'save': method = 'Save{0}ToCache(*{1});\n'.format(self.object_name, name) elif sql_verb == 'deletes': if num_parameters == 0: method = 'Delete{0}FromCache();\n'.format(self.plural_object_name) elif num_parameters == 1: by = 'by_{0}'.format(parameters) by = string_utils.to_title_style_name(by) method = 'Delete{0}FromCache{2}({1});\n'.format(self.plural_object_name, parameters, by) else: method = 'Delete{0}FromCache({1});\n'.format(self.plural_object_name, parameters) elif sql_verb == 'delete': if num_parameters == 0: method = 'Delete{0}FromCache();\n'.format(self.object_name) elif num_parameters == 1: by = 'by_{0}'.format(parameters) by = string_utils.to_title_style_name(by) method = 'Delete{0}FromCache{2}({1});\n'.format(self.object_name, parameters, by) else: method = 'Delete{0}FromCache({1});\n'.format(self.object_name, parameters) elif sql_verb[:7] == 'fupdate': # generate implementation automatically components = re.split(':', sql_verb) fetch_by_id = components[1] impl = string_utils.indent(6) + 'unique_ptr<{0}> {1} = this->Fetch{0}FromCacheBy{2}({3});\n'\ .format(self.object_name, string_utils.cpp_class_name_to_cpp_file_name(self.object_name), string_utils.to_title_style_name(fetch_by_id), fetch_by_id) for parameter in re.split(',', parameters): impl += string_utils.indent(6) + '{0}->set_{1}({1});\n'.format(string_utils.cpp_class_name_to_cpp_file_name(self.object_name), parameter) impl += string_utils.indent(6) + 'this->Save{0}ToCache(*{1});\n'.format(self.object_name, string_utils.cpp_class_name_to_cpp_file_name(self.object_name)) return impl else: print 'Unsupported method' assert False impl += string_utils.indent(6) + cpp_class + method return impl
def __fetch_implementation(self, fetch_command): by_list = [] if fetch_command.where != '': by_list = re.split(',', fetch_command.where) if not fetch_command.is_plural: impl = '- (nullable LCC{0} *)fetch{0}FromCache{1} {{\n'\ .format(self.object_name, self.__convert_bys_to_string(by_list)) impl += string_utils.indent(2) impl += 'std::unique_ptr<lesschat::{0}> core{0} = _coreManagerHandler->{1};\n'.format(self.object_name, self.__cpp_fetch_method_name(fetch_command)) impl += string_utils.indent(2) impl += 'if (core{0}) {{\n'.format(self.object_name) impl += string_utils.indent(4) impl += 'return [LCC{0} {1}WithCore{0}:*core{0}];\n'.format(self.object_name, string_utils.first_char_to_lower(self.object_name)) impl += string_utils.indent(2) impl += '}\n' impl += string_utils.indent(2) impl += 'return nil;\n' impl += '}' return impl else: impl = '- (NSArray<LCC{0} *> *)fetch{1}FromCache{2} {{\n'\ .format(self.object_name, self.plural_object_name, self.__convert_bys_to_string(by_list)) impl += string_utils.indent(2) impl += 'NSMutableArray *{0} = [NSMutableArray array];\n'.format(string_utils.first_char_to_lower(self.plural_object_name)) impl += string_utils.indent(2) impl += 'std::vector<std::unique_ptr<lesschat::{0}>> core{1} = _coreManagerHandler->{2};\n'.format(self.object_name, self.plural_object_name, self.__cpp_fetch_method_name(fetch_command)) impl += string_utils.indent(2) impl += 'for (auto it = core{0}.begin(); it != core{0}.end(); ++it) {{\n'.format(self.plural_object_name) impl += string_utils.indent(4) impl += '[{0} addObject:[LCC{1} {2}WithCore{1}:(**it)]];\n'.format(string_utils.first_char_to_lower(self.plural_object_name), self.object_name, string_utils.first_char_to_lower(self.object_name)) impl += string_utils.indent(2) impl += '}\n' impl += string_utils.indent(2) impl += 'return [{0} copy];\n'.format(string_utils.first_char_to_lower(self.plural_object_name)) impl += '}\n' self.impl = impl return self.impl
def getter_v2(self, num_pre_spaces=4): """Getter method using Android style implementation. Args: num_pre_spaces: A int describes the count spaces in front of the string. Returns: Java getter method. For example: public int getPosition() { return mPosition; } """ function_str = '' if self.__var_type == VarType.cpp_bool: function_str += indent(num_pre_spaces) + 'public {0} is{1}() {{\n' \ .format(self.__var_type.to_java_getter_setter_string(), self.__title_style_name) function_str += indent(num_pre_spaces + 4) + 'return m{0};\n'.format(self.__title_style_name) function_str += indent(num_pre_spaces) + '}' elif self.__var_type == VarType.cpp_string_array: function_str += indent(num_pre_spaces) + 'public String[] get{0}() {{\n'.format(self.__title_style_name) function_str += indent(num_pre_spaces + 4) + 'return m{0};\n'.format(self.__title_style_name) function_str += indent(num_pre_spaces) + "}" elif self.__var_type == VarType.cpp_enum: function_str += indent(num_pre_spaces) + '@{0}\n'.format(self.__java_enum) function_str += indent(num_pre_spaces) + 'public int get{0}() {{\n'.format(self.__title_style_name) function_str += indent(num_pre_spaces + 4) + 'return m{0};\n'.format(self.__title_style_name) function_str += indent(num_pre_spaces) + '}' else: function_str += indent(num_pre_spaces) + 'public {0} get{1}() {{\n'. \ format(self.__var_type.to_java_getter_setter_string(), self.__title_style_name) function_str += indent(num_pre_spaces + 4) + 'return m{0};\n'.format(self.__title_style_name) function_str += indent(num_pre_spaces) + '}' return function_str