diff --git a/CMakeLists.txt b/CMakeLists.txt index 09306d4df60..303a2f465f8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,6 +37,7 @@ set(gRPC_INSTALL_CMAKEDIR "lib/cmake/${PACKAGE_NAME}" CACHE STRING "Installation # Options option(gRPC_BUILD_TESTS "Build tests" OFF) +option(gRPC_BUILD_CODEGEN "Build codegen" ON) set(gRPC_INSTALL_default ON) if (NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) @@ -78,6 +79,8 @@ if(UNIX) set(_gRPC_PLATFORM_LINUX ON) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(_gRPC_PLATFORM_MAC ON) + elseif(${CMAKE_SYSTEM_NAME} MATCHES "Android") + set(_gRPC_PLATFORM_ANDROID ON) else() set(_gRPC_PLATFORM_POSIX ON) endif() @@ -120,6 +123,8 @@ endif() if(_gRPC_PLATFORM_MAC) set(_gRPC_ALLTARGETS_LIBRARIES ${CMAKE_DL_LIBS} m pthread) +elseif(_gRPC_PLATFORM_ANDROID) + set(_gRPC_ALLTARGETS_LIBRARIES ${CMAKE_DL_LIBS} m) elseif(UNIX) set(_gRPC_ALLTARGETS_LIBRARIES ${CMAKE_DL_LIBS} rt m pthread) endif() @@ -696,6 +701,12 @@ target_include_directories(gpr target_link_libraries(gpr ${_gRPC_ALLTARGETS_LIBRARIES} ) +if (_gRPC_PLATFORM_ANDROID) + target_link_libraries(gpr + android + log + ) +endif (_gRPC_PLATFORM_ANDROID) foreach(_hdr include/grpc/support/alloc.h @@ -2700,6 +2711,7 @@ endif() if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(grpc++_core_stats ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/core/stats.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/core/stats.grpc.pb.cc @@ -2745,6 +2757,7 @@ target_link_libraries(grpc++_core_stats grpc++ ) +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) @@ -3239,6 +3252,7 @@ if (gRPC_INSTALL) endif() +if (gRPC_BUILD_CODEGEN) add_library(grpc++_error_details ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/status/status.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/status/status.grpc.pb.cc @@ -3291,6 +3305,7 @@ foreach(_hdr DESTINATION "${gRPC_INSTALL_INCLUDEDIR}/${_path}" ) endforeach() +endif (gRPC_BUILD_CODEGEN) if (gRPC_INSTALL) @@ -3303,6 +3318,7 @@ endif() if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(grpc++_proto_reflection_desc_db test/cpp/util/proto_reflection_descriptor_database.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/reflection/v1alpha/reflection.pb.cc @@ -3359,9 +3375,11 @@ foreach(_hdr DESTINATION "${gRPC_INSTALL_INCLUDEDIR}/${_path}" ) endforeach() +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(grpc++_reflection src/cpp/ext/proto_server_reflection.cc src/cpp/ext/proto_server_reflection_plugin.cc @@ -3415,6 +3433,7 @@ foreach(_hdr DESTINATION "${gRPC_INSTALL_INCLUDEDIR}/${_path}" ) endforeach() +endif (gRPC_BUILD_CODEGEN) if (gRPC_INSTALL) @@ -3468,6 +3487,7 @@ target_link_libraries(grpc++_test_config endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(grpc++_test_util ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/health/v1/health.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/health/v1/health.grpc.pb.cc @@ -3636,10 +3656,12 @@ foreach(_hdr DESTINATION "${gRPC_INSTALL_INCLUDEDIR}/${_path}" ) endforeach() +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(grpc++_test_util_unsecure ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/health/v1/health.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/health/v1/health.grpc.pb.cc @@ -3806,6 +3828,7 @@ foreach(_hdr DESTINATION "${gRPC_INSTALL_INCLUDEDIR}/${_path}" ) endforeach() +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) @@ -4148,6 +4171,7 @@ target_link_libraries(grpc_benchmark endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(grpc_cli_libs test/cpp/util/cli_call.cc test/cpp/util/cli_credentials.cc @@ -4209,6 +4233,7 @@ foreach(_hdr DESTINATION "${gRPC_INSTALL_INCLUDEDIR}/${_path}" ) endforeach() +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) @@ -4274,6 +4299,7 @@ endif() if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(http2_client_main ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/empty.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/empty.grpc.pb.cc @@ -4337,10 +4363,12 @@ target_link_libraries(http2_client_main grpc++_test_config ) +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(interop_client_helper ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/messages.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/messages.grpc.pb.cc @@ -4390,10 +4418,12 @@ target_link_libraries(interop_client_helper gpr ) +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(interop_client_main ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/empty.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/empty.grpc.pb.cc @@ -4461,6 +4491,7 @@ target_link_libraries(interop_client_main grpc++_test_config ) +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) @@ -4511,6 +4542,7 @@ target_link_libraries(interop_server_helper endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(interop_server_lib ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/empty.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/empty.grpc.pb.cc @@ -4577,6 +4609,7 @@ target_link_libraries(interop_server_lib grpc++_test_config ) +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) @@ -4623,6 +4656,7 @@ target_link_libraries(interop_server_main endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_library(qps ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/messages.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/messages.grpc.pb.cc @@ -4709,6 +4743,7 @@ target_link_libraries(qps grpc ) +endif (gRPC_BUILD_CODEGEN) endif (gRPC_BUILD_TESTS) @@ -10265,6 +10300,7 @@ target_link_libraries(grpc_cli ) endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_CODEGEN) add_executable(grpc_cpp_plugin src/compiler/cpp_plugin.cc @@ -10299,6 +10335,8 @@ if (gRPC_INSTALL) ) endif() +endif (gRPC_BUILD_CODEGEN) +if (gRPC_BUILD_CODEGEN) add_executable(grpc_csharp_plugin src/compiler/csharp_plugin.cc @@ -10333,6 +10371,8 @@ if (gRPC_INSTALL) ) endif() +endif (gRPC_BUILD_CODEGEN) +if (gRPC_BUILD_CODEGEN) add_executable(grpc_node_plugin src/compiler/node_plugin.cc @@ -10367,6 +10407,8 @@ if (gRPC_INSTALL) ) endif() +endif (gRPC_BUILD_CODEGEN) +if (gRPC_BUILD_CODEGEN) add_executable(grpc_objective_c_plugin src/compiler/objective_c_plugin.cc @@ -10401,6 +10443,8 @@ if (gRPC_INSTALL) ) endif() +endif (gRPC_BUILD_CODEGEN) +if (gRPC_BUILD_CODEGEN) add_executable(grpc_php_plugin src/compiler/php_plugin.cc @@ -10435,6 +10479,8 @@ if (gRPC_INSTALL) ) endif() +endif (gRPC_BUILD_CODEGEN) +if (gRPC_BUILD_CODEGEN) add_executable(grpc_python_plugin src/compiler/python_plugin.cc @@ -10469,6 +10515,8 @@ if (gRPC_INSTALL) ) endif() +endif (gRPC_BUILD_CODEGEN) +if (gRPC_BUILD_CODEGEN) add_executable(grpc_ruby_plugin src/compiler/ruby_plugin.cc @@ -10503,6 +10551,7 @@ if (gRPC_INSTALL) ) endif() +endif (gRPC_BUILD_CODEGEN) if (gRPC_BUILD_TESTS) add_executable(grpc_tool_test diff --git a/examples/android/helloworld/.gitignore b/examples/android/helloworld/.gitignore new file mode 100644 index 00000000000..39fb081a42a --- /dev/null +++ b/examples/android/helloworld/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/examples/android/helloworld/README.md b/examples/android/helloworld/README.md new file mode 100644 index 00000000000..ebb16d136bc --- /dev/null +++ b/examples/android/helloworld/README.md @@ -0,0 +1,24 @@ +gRPC on Android +============== + +Note: Building the protobuf dependency for Android requires +https://github.com/google/protobuf/pull/3878. This fix will be in the next +protobuf release, but until then must be manually patched in to +`third_party/protobuf` to build gRPC for Android. + +PREREQUISITES +------------- + +- Android SDK +- Android NDK +- `protoc` and `grpc_cpp_plugin` binaries on the host system + +INSTALL +------- + +The example application can be built via Android Studio or on the command line +using `gradle`: + + ```sh + $ ./gradlew installDebug + ``` diff --git a/examples/android/helloworld/app/.gitignore b/examples/android/helloworld/app/.gitignore new file mode 100644 index 00000000000..796b96d1c40 --- /dev/null +++ b/examples/android/helloworld/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/examples/android/helloworld/app/CMakeLists.txt b/examples/android/helloworld/app/CMakeLists.txt new file mode 100644 index 00000000000..6ee18daaabc --- /dev/null +++ b/examples/android/helloworld/app/CMakeLists.txt @@ -0,0 +1,123 @@ +cmake_minimum_required(VERSION 3.4.1) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(helloworld_PROTOBUF_PROTOC_EXECUTABLE "/usr/local/bin/protoc" CACHE STRING "Protoc binary on host") +set(helloworld_GRPC_CPP_PLUGIN_EXECUTABLE "/usr/local/bin/grpc_cpp_plugin" CACHE STRING "gRPC CPP plugin binary on host") + +set(GRPC_SRC_DIR ../../../../) + +set(GRPC_BUILD_DIR ../grpc/outputs/${ANDROID_ABI}) +file(MAKE_DIRECTORY ${GRPC_BUILD_DIR}) + +add_subdirectory(${GRPC_SRC_DIR} ${GRPC_BUILD_DIR}) + +include_directories(${GRPC_SRC_DIR}/include) + +add_library(libgrpc STATIC IMPORTED) +set_target_properties(libgrpc PROPERTIES IMPORTED_LOCATION + ${GRPC_BUILD_DIR}/libgrpc.a) + +add_library(libgrpc++ STATIC IMPORTED) +set_target_properties(libgrpc++ PROPERTIES IMPORTED_LOCATION + ${GRPC_BUILD_DIR}/libgrpc++.a) + +add_library(libgpr STATIC IMPORTED) +set_target_properties(libgpr PROPERTIES IMPORTED_LOCATION + ${GRPC_BUILD_DIR}/libgpr.a) + +add_library(libcares STATIC IMPORTED) +set_target_properties(libcares PROPERTIES IMPORTED_LOCATION + ${GRPC_BUILD_DIR}/third_party/cares/cares/lib/libcares.a) + +add_library(libzlib STATIC IMPORTED) +set_target_properties(libzlib PROPERTIES IMPORTED_LOCATION + ${GRPC_BUILD_DIR}/third_party/zlib/libz.a) + +add_library(libcrypto STATIC IMPORTED) +set_target_properties(libcrypto PROPERTIES IMPORTED_LOCATION + ${GRPC_BUILD_DIR}/third_party/boringssl/crypto/libcrypto.a) + +add_library(libssl STATIC IMPORTED) +set_target_properties(libssl PROPERTIES IMPORTED_LOCATION + ${GRPC_BUILD_DIR}/third_party/boringssl/ssl/libssl.a) + +set(GRPC_PROTO_GENS_DIR ${CMAKE_BINARY_DIR}/gens) +file(MAKE_DIRECTORY ${GRPC_PROTO_GENS_DIR}) +include_directories(${GRPC_PROTO_GENS_DIR}) + +function(android_protobuf_grpc_generate_cpp SRC_FILES HDR_FILES INCLUDE_ROOT) + if(NOT ARGN) + message(SEND_ERROR "Error: android_protobuf_grpc_generate_cpp() called without any proto files") + return() + endif() + + set(${SRC_FILES}) + set(${HDR_FILES}) + set(PROTOBUF_INCLUDE_PATH -I ${INCLUDE_ROOT}) + foreach(FIL ${ARGN}) + get_filename_component(ABS_FIL ${FIL} ABSOLUTE) + get_filename_component(FIL_WE ${FIL} NAME_WE) + file(RELATIVE_PATH REL_FIL ${CMAKE_CURRENT_SOURCE_DIR}/${INCLUDE_ROOT} ${ABS_FIL}) + get_filename_component(REL_DIR ${REL_FIL} DIRECTORY) + set(RELFIL_WE "${REL_DIR}/${FIL_WE}") + + list(APPEND ${SRC_FILES} "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.pb.cc") + list(APPEND ${HDR_FILES} "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.pb.h") + list(APPEND ${SRC_FILES} "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.grpc.pb.cc") + list(APPEND ${HDR_FILES} "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.grpc.pb.h") + + add_custom_command( + OUTPUT "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.grpc.pb.cc" + "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.grpc.pb.h" + "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.pb.cc" + "${GRPC_PROTO_GENS_DIR}/${RELFIL_WE}.pb.h" + COMMAND ${helloworld_PROTOBUF_PROTOC_EXECUTABLE} + ARGS --grpc_out=${GRPC_PROTO_GENS_DIR} + --cpp_out=${GRPC_PROTO_GENS_DIR} + --plugin=protoc-gen-grpc=${helloworld_GRPC_CPP_PLUGIN_EXECUTABLE} + ${PROTOBUF_INCLUDE_PATH} + ${REL_FIL} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + DEPENDS ${helloworld_PROTOBUF_PROTOC_EXECUTABLE} ${helloworld_GRPC_CPP_PLUGIN_EXECUTABLE} ${ABS_FIL} ) + endforeach() + + set_source_files_properties(${${SRC_FILES}} ${${HDR_FILES}} PROPERTIES GENERATED TRUE) + set(${SRC_FILES} ${${SRC_FILES}} PARENT_SCOPE) + set(${HDR_FILES} ${${HDR_FILES}} PARENT_SCOPE) +endfunction() + +set(PROTO_BASE_DIR ${GRPC_SRC_DIR}/examples/protos) + +android_protobuf_grpc_generate_cpp( + HELLOWORLD_PROTO_SRCS HELLOWORLD_PROTO_HDRS ${PROTO_BASE_DIR} ${PROTO_BASE_DIR}/helloworld.proto) + +add_library(helloworld_proto_lib + SHARED ${HELLOWORLD_PROTO_HDRS} ${HELLOWORLD_PROTO_SRCS}) + +target_link_libraries(helloworld_proto_lib + libprotobuf + libgrpc++ + android + log) + +find_library(log-lib + log) + +add_library(grpc-helloworld + SHARED src/main/cpp/grpc-helloworld.cc) + +target_include_directories(grpc-helloworld + PRIVATE ${HELLOWORLD_PROTO_HEADERS}) + +target_link_libraries(grpc-helloworld + libgrpc++ + libgrpc + libzlib + libcares + libssl + libcrypto + helloworld_proto_lib + libgpr + android + ${log-lib}) diff --git a/examples/android/helloworld/app/build.gradle b/examples/android/helloworld/app/build.gradle new file mode 100644 index 00000000000..c6ab7308aeb --- /dev/null +++ b/examples/android/helloworld/app/build.gradle @@ -0,0 +1,53 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 26 + defaultConfig { + applicationId "io.grpc.android.cpp.helloworldexample" + minSdkVersion 14 + targetSdkVersion 26 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + externalNativeBuild { + cmake { + cppFlags "-std=c++14 -frtti -fexceptions" + arguments '-DANDROID_STL=c++_static' + arguments '-DRUN_HAVE_POSIX_REGEX=0' + arguments '-DRUN_HAVE_STD_REGEX=0' + arguments '-DRUN_HAVE_STEADY_CLOCK=0' + arguments '-Dprotobuf_BUILD_PROTOC_BINARIES=off' + arguments '-DgRPC_BUILD_CODEGEN=off' + // Set this to the path to the protoc binary on the host system (codegen is not + // cross-compiled to Android) + arguments '-Dhelloworld_PROTOBUF_PROTOC_EXECUTABLE=/usr/local/bin/protoc' + // Set this to the path to the gRPC C++ protoc plugin binary on the host system + // (codegen is not cross-compiled to Android) + arguments '-Dhelloworld_GRPC_CPP_PLUGIN_EXECUTABLE=/usr/local/bin/grpc_cpp_plugin' + } + } + ndk.abiFilters 'x86' + } + buildTypes { + debug { + minifyEnabled false + } + release { + minifyEnabled true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + externalNativeBuild { + cmake { + path "CMakeLists.txt" + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'com.android.support:appcompat-v7:26.1.0' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.1' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' +} diff --git a/examples/android/helloworld/app/proguard-rules.pro b/examples/android/helloworld/app/proguard-rules.pro new file mode 100644 index 00000000000..f1b424510da --- /dev/null +++ b/examples/android/helloworld/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/examples/android/helloworld/app/src/main/AndroidManifest.xml b/examples/android/helloworld/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..8109da9e961 --- /dev/null +++ b/examples/android/helloworld/app/src/main/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + diff --git a/examples/android/helloworld/app/src/main/cpp/grpc-helloworld.cc b/examples/android/helloworld/app/src/main/cpp/grpc-helloworld.cc new file mode 100644 index 00000000000..7a31b783c4f --- /dev/null +++ b/examples/android/helloworld/app/src/main/cpp/grpc-helloworld.cc @@ -0,0 +1,142 @@ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include + +#include +#include + +#include "helloworld.grpc.pb.h" + +using grpc::Channel; +using grpc::ClientContext; +using grpc::Server; +using grpc::ServerBuilder; +using grpc::ServerContext; +using grpc::Status; +using helloworld::Greeter; +using helloworld::HelloReply; +using helloworld::HelloRequest; + +std::atomic stop_server(false); + +// Logic and data behind the server's behavior. +class GreeterServiceImpl final : public Greeter::Service { + Status SayHello(ServerContext* context, const HelloRequest* request, + HelloReply* reply) override { + std::string prefix("Hello "); + reply->set_message(prefix + request->name()); + return Status::OK; + } +}; + +void StartServer(JNIEnv* env, jobject obj, jmethodID is_cancelled_mid, + int port) { + const int host_port_buf_size = 1024; + char host_port[host_port_buf_size]; + snprintf(host_port, host_port_buf_size, "0.0.0.0:%d", port); + + GreeterServiceImpl service; + ServerBuilder builder; + // Listen on the given address without any authentication mechanism. + builder.AddListeningPort(host_port, grpc::InsecureServerCredentials()); + // Register "service" as the instance through which we'll communicate with + // clients. In this case it corresponds to an *synchronous* service. + builder.RegisterService(&service); + // Finally assemble the server. + std::unique_ptr server(builder.BuildAndStart()); + while (!stop_server.load()) { + // Check with the Java code to see if the user has requested the server stop or the app is no + // longer in the foreground. + jboolean is_cancelled = env->CallBooleanMethod(obj, is_cancelled_mid); + if (is_cancelled == JNI_TRUE) { + stop_server = true; + } + } +} + +class GreeterClient { + public: + GreeterClient(std::shared_ptr channel) + : stub_(Greeter::NewStub(channel)) {} + + // Assembles the client's payload, sends it and presents the response back + // from the server. + std::string SayHello(const std::string& user) { + // Data we are sending to the server. + HelloRequest request; + request.set_name(user); + + // Container for the data we expect from the server. + HelloReply reply; + + // Context for the client. It could be used to convey extra information to + // the server and/or tweak certain RPC behaviors. + ClientContext context; + // The actual RPC. + Status status = stub_->SayHello(&context, request, &reply); + + if (status.ok()) { + return reply.message(); + } else { + return status.error_message(); + } + } + + private: + std::unique_ptr stub_; +}; + +// Send an RPC and return the response. Invoked from Java code. +extern "C" JNIEXPORT jstring JNICALL +Java_io_grpc_helloworldexample_cpp_HelloworldActivity_sayHello( + JNIEnv* env, jobject obj_unused, jstring host_raw, jint port_raw, + jstring message_raw) { + const char* host_chars = env->GetStringUTFChars(host_raw, (jboolean*)0); + std::string host(host_chars, env->GetStringUTFLength(host_raw)); + + int port = static_cast(port_raw); + + const char* message_chars = env->GetStringUTFChars(message_raw, (jboolean*)0); + std::string message(message_chars, env->GetStringUTFLength(message_raw)); + + const int host_port_buf_size = 1024; + char host_port[host_port_buf_size]; + snprintf(host_port, host_port_buf_size, "%s:%d", host.c_str(), port); + + GreeterClient greeter( + grpc::CreateChannel(host_port, grpc::InsecureChannelCredentials())); + std::string reply = greeter.SayHello(message); + + return env->NewStringUTF(reply.c_str()); +} + +// Start the server. Invoked from Java code. +extern "C" JNIEXPORT void JNICALL +Java_io_grpc_helloworldexample_cpp_HelloworldActivity_startServer( + JNIEnv* env, jobject obj_this, jint port_raw) { + int port = static_cast(port_raw); + + jclass cls = env->GetObjectClass(obj_this); + jmethodID is_cancelled_mid = + env->GetMethodID(cls, "isRunServerTaskCancelled", "()Z"); + + stop_server = false; + + StartServer(env, obj_this, is_cancelled_mid, port); +} diff --git a/examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/cpp/HelloworldActivity.java b/examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/cpp/HelloworldActivity.java new file mode 100644 index 00000000000..ae5c88b2085 --- /dev/null +++ b/examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/cpp/HelloworldActivity.java @@ -0,0 +1,167 @@ +/* + * Copyright 2018, gRPC Authors All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.helloworldexample.cpp; + +import android.content.Context; +import android.os.AsyncTask; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.text.TextUtils; +import android.text.method.ScrollingMovementMethod; +import android.view.View; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; +import java.lang.ref.WeakReference; + +public class HelloworldActivity extends AppCompatActivity { + + static { + System.loadLibrary("grpc-helloworld"); + } + + private Button sendButton; + private Button serverButton; + private EditText hostEdit; + private EditText portEdit; + private EditText messageEdit; + private EditText serverPortEdit; + private TextView resultText; + private GrpcTask grpcTask; + private RunServerTask runServerTask; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_helloworld); + sendButton = (Button) findViewById(R.id.send_button); + serverButton = (Button) findViewById(R.id.server_button); + hostEdit = (EditText) findViewById(R.id.host_edit_text); + portEdit = (EditText) findViewById(R.id.port_edit_text); + messageEdit = (EditText) findViewById(R.id.message_edit_text); + serverPortEdit = (EditText) findViewById(R.id.server_port_edit_text); + resultText = (TextView) findViewById(R.id.grpc_response_text); + resultText.setMovementMethod(new ScrollingMovementMethod()); + } + + @Override + protected void onPause() { + super.onPause(); + if (runServerTask != null) { + runServerTask.cancel(true); + runServerTask = null; + serverButton.setText("Start gRPC Server"); + } + if (grpcTask != null) { + grpcTask.cancel(true); + grpcTask = null; + } + } + + public void sendMessage(View view) { + ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) + .hideSoftInputFromWindow(hostEdit.getWindowToken(), 0); + sendButton.setEnabled(false); + resultText.setText(""); + grpcTask = new GrpcTask(this); + grpcTask.executeOnExecutor( + AsyncTask.THREAD_POOL_EXECUTOR, + hostEdit.getText().toString(), + messageEdit.getText().toString(), + portEdit.getText().toString()); + } + + public void startOrStopServer(View view) { + if (runServerTask != null) { + runServerTask.cancel(true); + runServerTask = null; + serverButton.setText("Start gRPC Server"); + Toast.makeText(this, "Server stopped", Toast.LENGTH_SHORT).show(); + } else { + runServerTask = new RunServerTask(this); + String portStr = serverPortEdit.getText().toString(); + int port = TextUtils.isEmpty(portStr) ? 50051 : Integer.valueOf(portStr); + runServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, port); + serverButton.setText("Stop gRPC Server"); + Toast.makeText(this, "Server started on port " + port, Toast.LENGTH_SHORT).show(); + } + } + + private static class RunServerTask extends AsyncTask { + private final WeakReference activityReference; + + private RunServerTask(HelloworldActivity activity) { + this.activityReference = new WeakReference(activity); + } + + @Override + protected Void doInBackground(Integer... params) { + int port = params[0]; + HelloworldActivity activity = activityReference.get(); + if (activity != null) { + activity.startServer(port); + } + return null; + } + } + + private static class GrpcTask extends AsyncTask { + private final WeakReference activityReference; + + private GrpcTask(HelloworldActivity activity) { + this.activityReference = new WeakReference(activity); + } + + @Override + protected String doInBackground(String... params) { + String host = params[0]; + String message = params[1]; + String portStr = params[2]; + int port = TextUtils.isEmpty(portStr) ? 50051 : Integer.valueOf(portStr); + return sayHello(host, port, message); + } + + @Override + protected void onPostExecute(String result) { + HelloworldActivity activity = activityReference.get(); + if (activity == null || isCancelled()) { + return; + } + TextView resultText = (TextView) activity.findViewById(R.id.grpc_response_text); + Button sendButton = (Button) activity.findViewById(R.id.send_button); + resultText.setText(result); + sendButton.setEnabled(true); + } + } + + /** + * Invoked by native code to stop server when RunServerTask has been canceled, either by user + * request or upon app moving to background. + */ + public boolean isRunServerTaskCancelled() { + if (runServerTask != null) { + return runServerTask.isCancelled(); + } + return false; + } + + public static native String sayHello(String host, int port, String message); + + public native void startServer(int port); +} diff --git a/examples/android/helloworld/app/src/main/res/layout/activity_helloworld.xml b/examples/android/helloworld/app/src/main/res/layout/activity_helloworld.xml new file mode 100644 index 00000000000..52804697a3b --- /dev/null +++ b/examples/android/helloworld/app/src/main/res/layout/activity_helloworld.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + +