[
  {
    "path": ".circleci/config.yml",
    "content": "# Java Maven CircleCI 2.0 configuration file\n#\n# Check https://circleci.com/docs/2.0/language-java/ for more details\n#\nversion: 2\njobs:\n  build:\n    docker:\n      # specify the version you desire here\n      - image: circleci/openjdk:8-jdk\n\n      # Specify service dependencies here if necessary\n      # CircleCI maintains a library of pre-built images\n      # documented at https://circleci.com/docs/2.0/circleci-images/\n      # - image: circleci/postgres:9.4\n\n    working_directory: ~/repo\n\n    environment:\n      # Customize the JVM maximum heap limit\n      MAVEN_OPTS: -Xmx3200m\n\n    steps:\n      - checkout\n\n      # Download and cache dependencies\n      - restore_cache:\n          keys:\n          - v1-dependencies-{{ checksum \"pom.xml\" }}-{{ checksum \"grpc-kotlin-gen/pom.xml\" }}-{{ checksum \"grpc-kotlin-test/pom.xml\" }}\n          # fallback to using the latest cache if no exact match is found\n          - v1-dependencies-\n\n      # run tests!\n      - run: mvn verify\n\n      - save_cache:\n          paths:\n            - ~/.m2\n          key: v1-dependencies-{{ checksum \"pom.xml\" }}-{{ checksum \"grpc-kotlin-gen/pom.xml\" }}-{{ checksum \"grpc-kotlin-test/pom.xml\" }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Build products and artifacts\ntarget/\npom.xml.tag\npom.xml.releaseBackup\npom.xml.versionsBackup\npom.xml.next\nrelease.properties\n\n# Stuff from various IDE's and editors\n*.iml\n*~\n.idea/*\n\n# Mac OS X Finder\n.DS_Store\n\n.classpath\n.project\n"
  },
  {
    "path": ".mvn/wrapper/MavenWrapperDownloader.java",
    "content": "/*\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements.  See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership.  The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License.  You may obtain a copy of the License at\n\n  http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied.  See the License for the\nspecific language governing permissions and limitations\nunder the License.\n*/\n\nimport java.net.*;\nimport java.io.*;\nimport java.nio.channels.*;\nimport java.util.Properties;\n\npublic class MavenWrapperDownloader {\n\n    /**\n     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.\n     */\n    private static final String DEFAULT_DOWNLOAD_URL =\n            \"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar\";\n\n    /**\n     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to\n     * use instead of the default one.\n     */\n    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =\n            \".mvn/wrapper/maven-wrapper.properties\";\n\n    /**\n     * Path where the maven-wrapper.jar will be saved to.\n     */\n    private static final String MAVEN_WRAPPER_JAR_PATH =\n            \".mvn/wrapper/maven-wrapper.jar\";\n\n    /**\n     * Name of the property which should be used to override the default download url for the wrapper.\n     */\n    private static final String PROPERTY_NAME_WRAPPER_URL = \"wrapperUrl\";\n\n    public static void main(String args[]) {\n        System.out.println(\"- Downloader started\");\n        File baseDirectory = new File(args[0]);\n        System.out.println(\"- Using base directory: \" + baseDirectory.getAbsolutePath());\n\n        // If the maven-wrapper.properties exists, read it and check if it contains a custom\n        // wrapperUrl parameter.\n        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);\n        String url = DEFAULT_DOWNLOAD_URL;\n        if(mavenWrapperPropertyFile.exists()) {\n            FileInputStream mavenWrapperPropertyFileInputStream = null;\n            try {\n                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);\n                Properties mavenWrapperProperties = new Properties();\n                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);\n                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);\n            } catch (IOException e) {\n                System.out.println(\"- ERROR loading '\" + MAVEN_WRAPPER_PROPERTIES_PATH + \"'\");\n            } finally {\n                try {\n                    if(mavenWrapperPropertyFileInputStream != null) {\n                        mavenWrapperPropertyFileInputStream.close();\n                    }\n                } catch (IOException e) {\n                    // Ignore ...\n                }\n            }\n        }\n        System.out.println(\"- Downloading from: : \" + url);\n\n        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);\n        if(!outputFile.getParentFile().exists()) {\n            if(!outputFile.getParentFile().mkdirs()) {\n                System.out.println(\n                        \"- ERROR creating output direcrory '\" + outputFile.getParentFile().getAbsolutePath() + \"'\");\n            }\n        }\n        System.out.println(\"- Downloading to: \" + outputFile.getAbsolutePath());\n        try {\n            downloadFileFromURL(url, outputFile);\n            System.out.println(\"Done\");\n            System.exit(0);\n        } catch (Throwable e) {\n            System.out.println(\"- Error downloading\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n\n    private static void downloadFileFromURL(String urlString, File destination) throws Exception {\n        URL website = new URL(urlString);\n        ReadableByteChannel rbc;\n        rbc = Channels.newChannel(website.openStream());\n        FileOutputStream fos = new FileOutputStream(destination);\n        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);\n        fos.close();\n        rbc.close();\n    }\n\n}\n"
  },
  {
    "path": ".mvn/wrapper/maven-wrapper.properties",
    "content": "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "NOTICE",
    "content": "File grpc-kotlin-gen/src/main/java/io/rouz/grpc/kotlin/GrpcKotlinGenerator.java\nModified redistribution of ReactiveGrpcGenerator.java from https://github.com/salesforce/reactive-grpc\nLicensed under the BSD 3-Clause license\n"
  },
  {
    "path": "README.md",
    "content": "# gRPC Kotlin - Coroutine based gRPC for Kotlin\n\n[![CircleCI](https://img.shields.io/circleci/project/github/rouzwawi/grpc-kotlin.svg)](https://circleci.com/gh/rouzwawi/grpc-kotlin)\n[![Maven Central](https://img.shields.io/maven-central/v/io.rouz/grpc-kotlin-gen.svg)](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22io.rouz%22%20grpc-kotlin-gen)\n\ngRPC Kotlin is a [protoc] plugin for generating native Kotlin bindings using [coroutine primitives] for [gRPC] services.\n\n  * [Why?](#why)\n  * [Quick start](#quick-start)\n     * [Server](#server)\n     * [Client](#client)\n  * [gRPC Context propagation](#grpc-context-propagation)\n  * [Exception handling](#exception-handling)\n  * [Maven configuration](#maven-configuration)\n  * [Gradle configuration](#gradle-configuration)\n  * [Examples](#examples)\n  * [RPC method type reference](#rpc-method-type-reference)\n     * [Unary call](#unary-call)\n        * [Service](#service)\n        * [Client](#client-1)\n     * [Client streaming call](#client-streaming-call)\n        * [Service](#service-1)\n        * [Client](#client-2)\n     * [Server streaming call](#server-streaming-call)\n        * [Service](#service-2)\n        * [Client](#client-3)\n     * [Full bidirectional streaming call](#full-bidirectional-streaming-call)\n        * [Service](#service-3)\n        * [Client](#client-4)\n\n---\n\n## Why?\n\nThe asynchronous nature of bidirectional streaming rpc calls in gRPC makes them a bit hard to implement\nand read. Getting your head around the `StreamObserver<T>`'s can be a bit tricky at times. Specially\nwith the method argument being the response observer and the return value being the request observer, it all\nfeels a bit backwards to what a plain old synchronous version of the handler would look like.\n\nIn situations where you'd want to coordinate several request and response messages in one call, you'll and up\nhaving to manage some tricky state and synchronization between the observers. There are [reactive bindings]\nfor gRPC which make this easier. But I think we can do better!\n\nEnter Kotlin Coroutines! By generating native Kotlin stubs that allows us to use [`suspend`] functions and \n[`Channel`], we can write our handler and client code in an idiomatic and easy to read Kotlin style.\n\n## Quick start\n\nNote: This has been tested with `gRPC 1.25.0`, `protobuf 3.10.0`, `kotlin 1.3.61` and `coroutines 1.3.3`.\n\nAdd a gRPC service definition to your project\n\n`greeter.proto`\n\n```proto\nsyntax = \"proto3\";\npackage org.example.greeter;\n\noption java_package = \"org.example.greeter\";\noption java_multiple_files = true;\n\nmessage GreetRequest {\n    string greeting = 1;\n}\n\nmessage GreetReply {\n    string reply = 1;\n}\n\nservice Greeter {\n    rpc Greet (GreetRequest) returns (GreetReply);\n    rpc GreetServerStream (GreetRequest) returns (stream GreetReply);\n    rpc GreetClientStream (stream GreetRequest) returns (GreetReply);\n    rpc GreetBidirectional (stream GreetRequest) returns (stream GreetReply);\n}\n```\n\nRun the protoc plugin to get the generated code, see [build tool configuration](#maven-configuration)\n\n### Server\n\nAfter compilation, you'll find the generated Kotlin code in the same package as the generated Java\ncode. A service base class named `GreeterImplBase` and a file with extension functions for the\nclient stub named `GreeterStubExt.kt`. Both the service base class and client stub extensions will\nuse `suspend` and `Channel<T>` instead of the typical `StreamObserver<T>` interfaces.\n\nAll functions have the [`suspend`] modifier so they can call into any suspending code, including the\n[core coroutine primitives] like `delay` and `async`.\n\nAll the server streaming calls return a `ReceiveChannel<TReply>` and can easily be implemented using\n`produce<TReply>`.\n\nAll client streaming calls receive an argument of `ReceiveChannel<TRequest>` where they can `receive()`\nmessages from the caller.\n\nHere's an example server that demonstrates how each type of endpoint is implemented.\n\n```kotlin\nimport kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\nimport java.util.concurrent.Executors.newFixedThreadPool\n\nclass GreeterImpl : GreeterImplBase(\n  coroutineContext = newFixedThreadPool(4).asCoroutineDispatcher()\n) {\n\n  // unary rpc\n  override suspend fun greet(request: GreetRequest): GreetReply {\n    return GreetReply.newBuilder()\n        .setReply(\"Hello \" + request.greeting)\n        .build()\n  }\n\n  // server streaming rpc\n  override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n    send(GreetReply.newBuilder()\n        .setReply(\"Hello ${request.greeting}!\")\n        .build())\n    send(GreetReply.newBuilder()\n        .setReply(\"Greetings ${request.greeting}!\")\n        .build())\n  }\n\n  // client streaming rpc\n  override suspend fun greetClientStream(requestChannel: ReceiveChannel<GreetRequest>): GreetReply {\n    val greetings = mutableListOf<String>()\n\n    for (request in requestChannel) {\n      greetings.add(request.greeting)\n    }\n\n    return GreetReply.newBuilder()\n        .setReply(\"Hi to all of $greetings!\")\n        .build()\n  }\n\n  // bidirectional rpc\n  override fun greetBidirectional(requestChannel: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n    var count = 0\n\n    for (request in requestChannel) {\n      val n = count++\n      launch {\n        delay(1000)\n        send(GreetReply.newBuilder()\n            .setReply(\"Yo #$n ${request.greeting}\")\n            .build())\n      }\n    }\n  }\n}\n```\n\n### Client\n\nExtensions functions for the original Java stubs are generated that use `suspend` functions, `Deferred<TReply>`\nand `SendChannel<TRequest>`.\n\n```kotlin\nimport io.grpc.ManagedChannelBuilder\nimport kotlinx.coroutines.delay\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.runBlocking\n\nfun main(args: Array<String>) {\n  val localhost = ManagedChannelBuilder.forAddress(\"localhost\", 8080)\n      .usePlaintext()\n      .build()\n  val greeter = GreeterGrpc.newStub(localhost)\n\n  runBlocking {\n    // === Unary call =============================================================================\n\n    val unaryResponse = greeter.greet(req(\"Alice\"))\n    println(\"unary reply = ${unaryResponse.reply}\")\n\n    // === Server streaming call ==================================================================\n\n    val serverResponses = greeter.greetServerStream(req(\"Bob\"))\n    for (serverResponse in serverResponses) {\n      println(\"server response = ${serverResponse.reply}\")\n    }\n\n    // === Client streaming call ==================================================================\n\n    val manyToOneCall = greeter.greetClientStream()\n    manyToOneCall.send(req(\"Caroline\"))\n    manyToOneCall.send(req(\"David\"))\n    manyToOneCall.close()\n    val oneReply = manyToOneCall.await()\n    println(\"single reply = ${oneReply.reply}\")\n\n    // === Bidirectional call =====================================================================\n\n    val bidiCall = greeter.greetBidirectional()\n    launch {\n      var n = 0\n      for (greetReply in bidiCall) {\n        println(\"r$n = ${greetReply.reply}\")\n        n++\n      }\n      println(\"no more replies\")\n    }\n\n    delay(200)\n    bidiCall.send(req(\"Eve\"))\n\n    delay(200)\n    bidiCall.send(req(\"Fred\"))\n\n    delay(200)\n    bidiCall.send(req(\"Gina\"))\n\n    bidiCall.close()\n  }\n}\n```\n\n## gRPC Context propagation\n\ngRPC has a thread-local [`Context`] which is used to carry scoped values across API boundaries. With Kotlin coroutines\npossibly being dispatched on multiple threads, the thread-local nature of `Context` needs some special care. This is\nsolved by two details in the generated Kotlin code.\n\nFirst, all the generated service `*ImplBase` classes implement `CoroutineScope`. This allows you to use any of\nthe top level coroutine primitives such as `launch`, `async` and `produce` in your service implementation while still\nkeeping them within the context of your service code. The actual `CoroutineContext` that is used can be set through the\nbase class constructor, but defaults to `Dispatchers.default`.\n\n```kotlin\nabstract class MyServiceImplBase(\n    coroutineContext: CoroutineContext = Dispatchers.Default\n)\n```\n\nSecond, in the getter for `CoroutineScope.coroutineContext`, an additional context key is added to the\n`CoroutineContext` that manages the gRPC Context `attach()` and `detach()` calls when dispatching coroutine\ncontinuations. This will ensure that the the gRPC context is always propagated across different coroutine boundaries,\nand eliminates the need to manually carry it across in user code.\n\nHere's a simple example that makes calls to other services concurrently and expects an authenticated user to be present\nin the gRPC Context. The two accesses to the context key may execute on different threads in the `CoroutineContext` but\nthe accesses work as expected.\n\n```kotlin\nval authenticatedUser = Context.key<User>(\"authenticatedUser\")\n\noverride suspend fun greet(request: GreetRequest): GreetReply {\n    val motd = async { messageOfTheDay.getMessage() }\n    val weatherReport = async { weather.getWeatherReport(authenticatedUser.get().location) }\n\n    val reply = buildString {\n        append(\"Hello ${authenticatedUser.get().fullName}\")\n        append(\"---\")\n        append(\"Today's weather report: ${weatherReport.await()}\")\n        append(\"---\")\n        append(motd.await())\n    }\n\n    return GreetReply.newBuilder()\n        .setReply(reply)\n        .build()\n}\n```\n\nFor another example of gRPC Context usage, see the code in [ContextBasedGreeterTest](grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ContextBasedGreeterTest.kt)\n\nThanks to [`wfhartford`](https://github.com/wfhartford) for contributing!\n\n## Exception handling\n\nThe generated server code follows the standard exception propagation for Kotlin coroutines as described\nin the [Exception handling] documentation. This means that it's safe to throw exceptions from within\nthe server implementation code. These will propagate up the coroutine scope and be translated to\n`responseObserver.onError(Throwable)` calls. The preferred way to respond with a status code is to\nthrow a `StatusException`.\n\nNote that you should not call `close(Throwable)` or `close()` from within the `ProducerScope<T>`\nblocks you get from `produce` as the producer will automatically be closed when all sub-contexts are\nclosed (or if an exception is thrown).\n\n## Maven configuration\n\nAdd the `grpc-kotlin-gen` plugin to your `protobuf-maven-plugin` configuration (see [compile-custom goal](https://www.xolstice.org/protobuf-maven-plugin/compile-custom-mojo.html))\n\n```xml\n<properties>\n  <kotlin.version>1.3.61</kotlin.version>\n  <kotlinx-coroutines.version>1.3.3</kotlinx-coroutines.version>\n  <grpc.version>1.25.0</grpc.version>\n  <protobuf.version>3.10.0</protobuf.version>\n  <grpc-kotlin.version>0.1.4</grpc-kotlin.version>\n</properties>\n\n<dependencies>\n  <dependency>\n    <groupId>org.jetbrains.kotlin</groupId>\n    <artifactId>kotlin-stdlib</artifactId>\n    <version>${kotlin.version}</version>\n  </dependency>\n  <dependency>\n    <groupId>org.jetbrains.kotlinx</groupId>\n    <artifactId>kotlinx-coroutines-core</artifactId>\n    <version>${kotlinx-coroutines.version}</version>\n  </dependency>\n  <dependency>\n    <groupId>io.grpc</groupId>\n    <artifactId>grpc-netty</artifactId>\n    <version>${grpc.version}</version>\n  </dependency>\n  <dependency>\n    <groupId>io.grpc</groupId>\n    <artifactId>grpc-protobuf</artifactId>\n    <version>${grpc.version}</version>\n  </dependency>\n  <dependency>\n    <groupId>io.grpc</groupId>\n    <artifactId>grpc-stub</artifactId>\n    <version>${grpc.version}</version>\n  </dependency>\n</dependencies>\n\n<build>\n  <extensions>\n    <extension>\n      <groupId>kr.motd.maven</groupId>\n      <artifactId>os-maven-plugin</artifactId>\n      <version>1.5.0.Final</version>\n    </extension>\n  </extensions>\n\n  <plugins>\n    <plugin>\n      <groupId>org.xolstice.maven.plugins</groupId>\n      <artifactId>protobuf-maven-plugin</artifactId>\n      <version>0.6.1</version>\n      <configuration>\n        <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>\n      </configuration>\n      <executions>\n        <execution>\n          <goals><goal>compile</goal></goals>\n        </execution>\n        <execution>\n          <id>grpc-java</id>\n          <goals><goal>compile-custom</goal></goals>\n          <configuration>\n            <pluginId>grpc-java</pluginId>\n            <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>\n          </configuration>\n        </execution>\n        <execution>\n          <id>grpc-kotlin</id>\n          <goals><goal>compile-custom</goal></goals>\n          <configuration>\n            <pluginId>grpc-kotlin</pluginId>\n            <pluginArtifact>io.rouz:grpc-kotlin-gen:${grpc-kotlin.version}:exe:${os.detected.classifier}</pluginArtifact>\n          </configuration>\n        </execution>\n      </executions>\n    </plugin>\n\n    <!-- make sure to add the generated source directories to the kotlin-maven-plugin -->\n    <plugin>\n      <artifactId>kotlin-maven-plugin</artifactId>\n      <groupId>org.jetbrains.kotlin</groupId>\n      <version>${kotlin.version}</version>\n      <executions>\n        <execution>\n          <id>compile</id>\n          <goals><goal>compile</goal></goals>\n          <configuration>\n            <sourceDirs>\n              <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>\n              <sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-kotlin</sourceDir>\n              <sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-java</sourceDir>\n              <sourceDir>${project.basedir}/target/generated-sources/protobuf/java</sourceDir>\n            </sourceDirs>\n          </configuration>\n        </execution>\n      </executions>\n    </plugin>\n  </plugins>\n</build>\n```\n\n## Gradle configuration\n\nAdd the `grpc-kotlin-gen` plugin to the plugins section of `protobuf-gradle-plugin`\n\n```gradle\ndef protobufVersion = '3.10.0'\ndef grpcVersion = '1.25.0'\ndef grpcKotlinVersion = '0.1.4'\n\nprotobuf {\n    protoc {\n        // The artifact spec for the Protobuf Compiler\n        artifact = \"com.google.protobuf:protoc:${protobufVersion}\"\n    }\n    plugins {\n        grpc {\n            artifact = \"io.grpc:protoc-gen-grpc-java:${grpcVersion}\"\n        }\n        grpckotlin {\n            artifact = \"io.rouz:grpc-kotlin-gen:${grpcKotlinVersion}\"\n        }\n    }\n    generateProtoTasks {\n        all()*.plugins {\n            grpc {}\n            grpckotlin {}\n        }\n    }\n}\n```\n\nAdd the kotlin dependencies\n\n```gradle\ndef kotlinVersion = '1.3.61'\ndef kotlinCoroutinesVersion = '1.3.3'\n\ndependencies {\n    compile \"org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion\"\n    compile \"org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutinesVersion\"\n}\n```\n\n## Examples\n\nThis is a list of example gRPC services and clients written using this project\n\n- [`grpc-kotlin-example-chatserver`](grpc-kotlin-example-chatserver)\n- [`kotlin-grpc-sample`](https://github.com/FlavioF/kotlin-grpc-sample)\n- [`grpc-death-star`](https://github.com/leveretka/grpc-death-star)\n\n## RPC method type reference\n\n### Unary call\n\n> `rpc Greet (GreetRequest) returns (GreetReply);`\n\n#### Service\n\nA suspendable function which returns a single message.\n\n```kotlin\noverride suspend fun greet(request: GreetRequest): GreetReply {\n  // return GreetReply message\n}\n```\n\n#### Client\n\nSuspendable call returning a single message.\n\n```kotlin\nval response: GreetReply = stub.greet( /* GreetRequest */ )\n```\n\n### Client streaming call\n\n> `rpc GreetClientStream (stream GreetRequest) returns (GreetReply);`\n\n#### Service\n\nA suspendable function which returns a single message, and receives messages from a `ReceiveChannel<T>`.\n\n```kotlin\noverride suspend fun greetClientStream(requestChannel: ReceiveChannel<GreetRequest>): GreetReply {\n  // receive request messages\n  val firstRequest = requestChannel.receive()\n  \n  // or iterate all request messages\n  for (request in requestChannel) {\n    // ...\n  }\n\n  // return GreetReply message\n}\n```\n\n#### Client\n\nUsing `send()` and `close()` on `SendChannel<T>`.\n\n```kotlin\nval call: ManyToOneCall<GreetRequest, GreetReply> = stub.greetClientStream()\ncall.send( /* GreetRequest */ )\ncall.send( /* GreetRequest */ )\ncall.close() //  don't forget to close the send channel\n\nval responseMessage = call.await()\n```\n\n### Server streaming call\n\n> `rpc GreetServerStream (GreetRequest) returns (stream GreetReply);`\n\n#### Service\n\nUsing `produce` and `send()` to send a stream of messages.\n\n```kotlin\noverride fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n  send( /* GreetReply message */ )\n  send( /* GreetReply message */ )\n  // ...\n}\n```\n\nNote that `close()` or `close(Throwable)` should not be used, see [Exception handling](#exception-handling).\n\nIn `kotlinx-coroutines-core:1.0.0` `produce` is marked with `@ExperimentalCoroutinesApi`. In order\nto use it, mark your server class with `@UseExperimental(ExperimentalCoroutinesApi::class)` and\nadd the `-Xuse-experimental=kotlin.Experimental` compiler flag.\n\n#### Client\n\nUsing `receive()` on `ReceiveChannel<T>` or iterating with a `for` loop.\n\n```kotlin\nval responses: ReceiveChannel<GreetReply> = stub.greetServerStream( /* GreetRequest */ )\n\n// await individual responses\nval responseMessage = serverResponses.receive()\n\n// or iterate all responses\nfor (responseMessage in responses) {\n  // ...\n}\n```\n\n### Full bidirectional streaming call\n\n> `rpc GreetBidirectional (stream GreetRequest) returns (stream GreetReply);`\n\n#### Service\n\nUsing `produce` and `send()` to send a stream of messages. Receiving messages from a `ReceiveChannel<T>`.\n\n```kotlin\noverride fun greetBidirectional(requestChannel: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n  // receive request messages\n  val firstRequest = requestChannel.receive()\n  send( /* GreetReply message */ )\n  \n  val more = requestChannel.receive()\n  send( /* GreetReply message */ )\n  \n  // ...\n}\n```\n\nNote that `close()` or `close(Throwable)` should not be used, see [Exception handling](#exception-handling).\n\nIn `kotlinx-coroutines-core:1.0.0` `produce` is marked with `@ExperimentalCoroutinesApi`. In order\nto use it, mark your server class with `@UseExperimental(ExperimentalCoroutinesApi::class)` and\nadd the `-Xuse-experimental=kotlin.Experimental` compiler flag.\n\n#### Client\n\nUsing both a `SendChannel<T>` and a `ReceiveChannel<T>` to interact with the call.\n\n```kotlin\nval call: ManyToManyCall<GreetRequest, GreetReply> = stub.greetBidirectional()\nlaunch {\n  for (responseMessage in call) {\n    log.info(responseMessage)\n  }\n  log.info(\"no more replies\")\n}\n\ncall.send( /* GreetRequest */ )\ncall.send( /* GreetRequest */ )\ncall.close() //  don't forget to close the send channel\n```\n\n\n[protoc]: https://www.xolstice.org/protobuf-maven-plugin/examples/protoc-plugin.html\n[`suspend`]: https://kotlinlang.org/docs/reference/coroutines-overview.html\n[coroutine primitives]: https://github.com/Kotlin/kotlinx.coroutines\n[core coroutine primitives]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/\n[Exception handling]: https://kotlinlang.org/docs/reference/coroutines/exception-handling.html\n[`Channel`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel/index.html\n[`Deferred`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/index.html\n[`async`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html\n[`produce`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html\n[`Context`]: https://grpc.io/grpc-java/javadoc/io/grpc/Context.html\n[gRPC]: https://grpc.io/\n[reactive bindings]: https://github.com/salesforce/reactive-grpc\n\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/README.md",
    "content": "# grpc-kotlin-example-chatserver\n\nA simple command line chat server written using both bidirectional & server streaming gRPC.\n\nBuild the parent project. From the repo root, run\n\n```sh\n./mvnw clean package\n```\n\nStart the server\n\n```sh\njava -jar grpc-kotlin-example-chatserver/target/grpc-kotlin-example-chatserver.jar server\n```\n\nFrom another shell, start a bidirectional streaming client\n\n```sh\njava -jar grpc-kotlin-example-chatserver/target/grpc-kotlin-example-chatserver.jar client\n```\n\nFrom the third shell, start a server streaming client\n\n```sh\njava -jar grpc-kotlin-example-chatserver/target/grpc-kotlin-example-chatserver.jar clientSS\n```\n\n---\n\nBig thanks to [Björn Hegerfors](https://github.com/Bj0rnen) and [Emilio Del Tessandoro](https://github.com/emmmile)\nfor putting together this example!\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <parent>\n        <groupId>io.rouz</groupId>\n        <artifactId>grpc-kotlin-parent</artifactId>\n        <version>0.1.5-SNAPSHOT</version>\n    </parent>\n\n    <name>grpc-kotlin-example-chatserver</name>\n    <artifactId>grpc-kotlin-example-chatserver</artifactId>\n    <packaging>jar</packaging>\n\n    <properties>\n        <kotlin.version>1.3.61</kotlin.version>\n        <kotlinx-coroutines.version>1.3.3</kotlinx-coroutines.version>\n        <grpc.version>1.25.0</grpc.version>\n        <protobuf.version>3.10.0</protobuf.version>\n    </properties>\n\n    <dependencies>\n        <!-- scope : compile -->\n        <dependency>\n            <groupId>org.jetbrains.kotlin</groupId>\n            <artifactId>kotlin-stdlib</artifactId>\n            <version>${kotlin.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>org.jetbrains.kotlinx</groupId>\n            <artifactId>kotlinx-coroutines-core</artifactId>\n            <version>${kotlinx-coroutines.version}</version>\n        </dependency>\n\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-netty</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-protobuf</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-stub</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-services</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n\n        <dependency>\n            <groupId>javax.annotation</groupId>\n            <artifactId>javax.annotation-api</artifactId>\n            <version>1.3.2</version>\n        </dependency>\n        <dependency>\n            <groupId>org.slf4j</groupId>\n            <artifactId>slf4j-simple</artifactId>\n            <version>1.7.25</version>\n        </dependency>\n\n        <!-- scope : test -->\n        <dependency>\n            <groupId>org.jetbrains.kotlin</groupId>\n            <artifactId>kotlin-test-junit</artifactId>\n            <version>${kotlin.version}</version>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <extensions>\n            <extension>\n                <groupId>kr.motd.maven</groupId>\n                <artifactId>os-maven-plugin</artifactId>\n                <version>1.5.0.Final</version>\n            </extension>\n        </extensions>\n        <plugins>\n            <plugin>\n                <groupId>org.xolstice.maven.plugins</groupId>\n                <artifactId>protobuf-maven-plugin</artifactId>\n                <version>0.6.1</version>\n                <configuration>\n                    <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>\n                </configuration>\n                <executions>\n                    <execution>\n                        <goals>\n                            <goal>compile</goal>\n                        </goals>\n                    </execution>\n                    <execution>\n                        <id>grpc-java</id>\n                        <goals>\n                            <goal>compile-custom</goal>\n                        </goals>\n                        <configuration>\n                            <pluginId>grpc-java</pluginId>\n                            <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}\n                            </pluginArtifact>\n                        </configuration>\n                    </execution>\n                    <execution>\n                        <id>grpc-kotlin</id>\n                        <goals>\n                            <goal>compile-custom</goal>\n                        </goals>\n                        <configuration>\n                            <pluginId>grpc-kotlin</pluginId>\n                            <pluginArtifact>io.rouz:grpc-kotlin-gen:${project.version}:exe:${os.detected.classifier}</pluginArtifact>\n                        </configuration>\n                    </execution>\n                </executions>\n            </plugin>\n            <plugin>\n                <artifactId>kotlin-maven-plugin</artifactId>\n                <groupId>org.jetbrains.kotlin</groupId>\n                <version>${kotlin.version}</version>\n                <configuration>\n                    <jvmTarget>1.8</jvmTarget>\n                    <args>-Xuse-experimental=kotlin.Experimental</args>\n                </configuration>\n                <executions>\n                    <execution>\n                        <id>compile</id>\n                        <phase>compile</phase>\n                        <goals><goal>compile</goal></goals>\n                        <configuration>\n                            <sourceDirs>\n                                <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>\n                                <sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-kotlin</sourceDir>\n                                <sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-java</sourceDir>\n                                <sourceDir>${project.basedir}/target/generated-sources/protobuf/java</sourceDir>\n                            </sourceDirs>\n                        </configuration>\n                    </execution>\n                    <execution>\n                        <id>test-compile</id>\n                        <goals>\n                            <goal>test-compile</goal>\n                        </goals>\n                        <configuration>\n                            <sourceDirs>\n                                <sourceDir>${project.basedir}/src/test/kotlin</sourceDir>\n                            </sourceDirs>\n                        </configuration>\n                    </execution>\n                </executions>\n            </plugin>\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-compiler-plugin</artifactId>\n                <executions>\n                    <!-- Replacing default-compile as it is treated specially by maven -->\n                    <execution>\n                        <id>default-compile</id>\n                        <phase>none</phase>\n                    </execution>\n                    <!-- Replacing default-testCompile as it is treated specially by maven -->\n                    <execution>\n                        <id>default-testCompile</id>\n                        <phase>none</phase>\n                    </execution>\n                    <execution>\n                        <id>java-compile</id>\n                        <phase>compile</phase>\n                        <goals>\n                            <goal>compile</goal>\n                        </goals>\n                    </execution>\n                    <execution>\n                        <id>java-test-compile</id>\n                        <phase>test-compile</phase>\n                        <goals>\n                            <goal>testCompile</goal>\n                        </goals>\n                    </execution>\n                </executions>\n            </plugin>\n\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-jar-plugin</artifactId>\n                <version>3.1.0</version>\n            </plugin>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n                <version>2.1.0.RELEASE</version>\n                <executions>\n                    <execution>\n                        <goals>\n                            <goal>repackage</goal>\n                        </goals>\n                    </execution>\n                </executions>\n                <configuration>\n                    <mainClass>io.rouz.grpc.examples.chat.EntrypointKt</mainClass>\n                    <layout>JAR</layout>\n                    <finalName>${project.name}</finalName>\n                </configuration>\n            </plugin>\n\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-deploy-plugin</artifactId>\n                <version>2.8.2</version>\n                <configuration>\n                    <skip>true</skip>\n                </configuration>\n            </plugin>\n        </plugins>\n    </build>\n\n</project>\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ChatClient.kt",
    "content": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.grpc.examples.chat\n\nimport io.grpc.ManagedChannelBuilder\nimport kotlinx.coroutines.GlobalScope\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.launch\n\nfun main(args: Array<String>) {\n    chatClient()\n}\n\nfun chatClient() {\n    val channel = ManagedChannelBuilder.forAddress(\"localhost\", 15001)\n        .usePlaintext()\n        .build()\n\n    val chatService = ChatServiceGrpc.newStub(channel)\n\n    val chat = chatService.chat()\n\n    println(\"type :q to quit\")\n    print(\"Enter your name: \")\n    val from = readLine()\n    chat.send(\n        ChatMessage.newBuilder()\n            .setFrom(from)\n            .build()\n    )\n\n    startPrintLoop(chat)\n\n    try {\n        while (true) {\n            print(\"Message: \")\n            val message = readLine()\n            if (message == null || message == \":q\") {\n                break\n            }\n            chat.send(\n                ChatMessage.newBuilder()\n                    .setFrom(from)\n                    .setMessage(message)\n                    .build()\n            )\n        }\n    } finally {\n        println(\"closing\")\n        chat.close()\n    }\n}\n\nprivate fun startPrintLoop(chat: ReceiveChannel<ChatMessageFromService>) = GlobalScope.launch {\n    try {\n        for (responseMessage in chat) {\n            val message = responseMessage.message\n            println(\"${message.from}: ${message.message}\")\n        }\n        println(\"Server disconnected\")\n    } catch (e: Throwable) {\n        println(\"Server disconnected badly: $e\")\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ChatService.kt",
    "content": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.grpc.examples.chat\n\nimport com.google.protobuf.Empty\nimport com.google.protobuf.Timestamp\nimport io.grpc.Status\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.GlobalScope\nimport kotlinx.coroutines.channels.Channel\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.SendChannel\nimport kotlinx.coroutines.launch\nimport java.time.Instant\nimport java.util.concurrent.ConcurrentSkipListMap\n\n@UseExperimental(ExperimentalCoroutinesApi::class)\nclass ChatService : ChatServiceImplBase() {\n    private val clientChannels = ConcurrentSkipListMap<String, SendChannel<ChatMessageFromService>>()\n\n    override suspend fun getNames(request: Empty): ChatRoom {\n        return ChatRoom.newBuilder()\n                .addAllNames(clientChannels.keys)\n                .build()\n    }\n\n    private fun createChannel() = Channel<ChatMessageFromService>(100).apply {\n        invokeOnClose {\n            it?.printStackTrace()\n        }\n    }\n\n    private fun subscribe(name: String, ch: SendChannel<ChatMessageFromService>) {\n        println(\"New client connected: $name\")\n        clientChannels.put(name, ch)\n                ?.apply {\n                    println(\"Close duplicate channel of user: $name\")\n                    close()\n                }\n    }\n\n    private suspend fun broadcast(message: ChatMessage) = createMessage(message)\n            .let { broadcastMessage ->\n                println(\"Broadcast ${message.from}: ${message.message}\")\n\n                clientChannels.asSequence()\n                        .filterNot { (name, _) -> name == message.from }\n                        .forEach { (other, ch) ->\n                            launch {\n                                try {\n                                    println(\"Sending to $other\")\n                                    ch.send(broadcastMessage)\n                                } catch (e: Throwable) {\n                                    println(\"$other hung up: ${e.message}. Removing client channel\")\n                                    clientChannels.remove(other)?.close(e)\n                                }\n                            }\n                        }\n            }\n\n\n    override fun chat(requests: ReceiveChannel<ChatMessage>): ReceiveChannel<ChatMessageFromService> =\n            createChannel().also {\n                GlobalScope.launch {\n                    doChat(requests, it)\n                }\n            }\n\n    private suspend fun doChat(req: ReceiveChannel<ChatMessage>, resp: SendChannel<ChatMessageFromService>) {\n        val hello = req.receive()\n        subscribe(hello.from, resp)\n        broadcast(hello)\n\n        try {\n            for (chatMessage in req) {\n                println(\"Got request from $req:\")\n                println(chatMessage)\n                broadcast(chatMessage)\n            }\n        } catch (t: Throwable) {\n            println(\"Threw $t\")\n            if (Status.fromThrowable(t).code != Status.Code.CANCELLED) {\n                println(\"An actual error occurred\")\n                t.printStackTrace()\n            }\n        } finally {\n            println(\"${hello.from} hung up. Removing client channel\")\n            clientChannels.remove(hello.from)\n            if (!resp.isClosedForSend) {\n                resp.close()\n            }\n        }\n    }\n\n    override suspend fun say(request: ChatMessage): Empty = Empty.getDefaultInstance().also {\n        broadcast(request)\n    }\n\n    override fun listen(request: WhoAmI): ReceiveChannel<ChatMessageFromService> = createChannel().also {\n        subscribe(request.name, it)\n    }\n\n    fun shutdown() {\n        println(\"Shutting down Chat service\")\n        clientChannels.forEach { (client, channel) ->\n            println(\"Closing client channel $client\")\n            channel.close()\n        }\n        clientChannels.clear()\n    }\n\n    private fun createMessage(request: ChatMessage) = ChatMessageFromService.newBuilder()\n            .run {\n                timestamp = Instant.now().run {\n                    Timestamp.newBuilder().run {\n                        seconds = epochSecond\n                        nanos = nano\n                        build()\n                    }\n                }\n                message = request\n                build()\n            }\n\n}\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/Entrypoint.kt",
    "content": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.grpc.examples.chat\n\nfun main(args: Array<String>) {\n    when(args[0]) {\n        \"server\" -> grpcServer()\n        \"client\" -> chatClient()\n        \"clientSS\" -> serverStreamingChatClient()\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/GrpcServer.kt",
    "content": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.grpc.examples.chat\n\nimport io.grpc.ServerBuilder\nimport io.grpc.protobuf.services.ProtoReflectionService\n\nfun main(args: Array<String>) {\n    grpcServer()\n}\n\nfun grpcServer() {\n    val chatService = ChatService()\n    val server = ServerBuilder\n        .forPort(15001)\n        .addService(ProtoReflectionService.newInstance())\n        .addService(chatService)\n        .build()\n\n    Runtime.getRuntime().addShutdownHook(Thread {\n        println(\"Ups, JVM shutdown\")\n\n        chatService.shutdown()\n        server.shutdown()\n        server.awaitTermination()\n\n        println(\"Chat service stopped\")\n    })\n\n    server.start()\n    println(\"Chat service started\")\n    server.awaitTermination()\n}\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ServerStreaminChatClient.kt",
    "content": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.grpc.examples.chat\n\nimport io.grpc.ManagedChannelBuilder\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.runBlocking\nimport java.util.concurrent.TimeUnit\n\nfun main() =    serverStreamingChatClient()\n\nfun serverStreamingChatClient() {\n    val channel = ManagedChannelBuilder.forAddress(\"localhost\", 15001)\n        .usePlaintext()\n        .build()\n\n    val chatService = ChatServiceGrpc.newStub(channel)\n\n    println(\"type :q to quit\")\n    print(\"Enter your name: \")\n    val from = readLine()\n\n    val listen = chatService.listen(WhoAmI.newBuilder().setName(from).build())\n\n    runBlocking(Dispatchers.IO) {\n        launch {\n            startPrintLoop(listen)\n        }\n\n        try {\n            while (true) {\n                print(\"Message: \")\n                val message = readLine()\n                if (message == null || message == \":q\") {\n                    break\n                }\n                chatService.say(\n                        ChatMessage.newBuilder()\n                                .setFrom(from)\n                                .setMessage(message)\n                                .build()\n                )\n            }\n        } finally {\n            println(\"closing\")\n            channel.shutdownNow().awaitTermination(1, TimeUnit.SECONDS)\n            println(\"closed\")\n        }\n    }\n}\n\nprivate suspend fun startPrintLoop(chat: ReceiveChannel<ChatMessageFromService>) =\n    try {\n        for (responseMessage in chat) {\n            val message = responseMessage.message\n            println(\"${message.from}: ${message.message}\")\n        }\n        println(\"Server disconnected\")\n    } catch (e: Throwable) {\n        println(\"Server disconnected badly: $e\")\n    }\n"
  },
  {
    "path": "grpc-kotlin-example-chatserver/src/main/proto/chat.proto",
    "content": "syntax = \"proto3\";\n\npackage io.rouz.grpc.examples.chat;\n\nimport \"google/protobuf/timestamp.proto\";\nimport \"google/protobuf/empty.proto\";\n\noption java_multiple_files = true;\noption java_package = \"io.rouz.grpc.examples.chat\";\n\n\nservice ChatService {\n    rpc Chat (stream ChatMessage) returns (stream ChatMessageFromService);\n    rpc GetNames (google.protobuf.Empty) returns (ChatRoom);\n\n    rpc Say(ChatMessage) returns (google.protobuf.Empty);\n    rpc Listen(WhoAmI) returns (stream ChatMessageFromService);\n}\n\nmessage ChatRoom {\n    repeated string names = 1;\n}\n\nmessage WhoAmI {\n    string name = 1;\n}\n\nmessage ChatMessage {\n    string from = 1;\n    string message = 2;\n}\n\nmessage ChatMessageFromService {\n    google.protobuf.Timestamp timestamp = 1;\n    ChatMessage message = 2;\n}\n"
  },
  {
    "path": "grpc-kotlin-gen/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <parent>\n        <groupId>io.rouz</groupId>\n        <artifactId>grpc-kotlin-parent</artifactId>\n        <version>0.1.5-SNAPSHOT</version>\n    </parent>\n\n    <artifactId>grpc-kotlin-gen</artifactId>\n    <packaging>jar</packaging>\n\n    <name>grpc-kotlin-gen</name>\n    <properties>\n        <grpc.version>1.25.0</grpc.version>\n    </properties>\n    <dependencies>\n        <!-- scope : compile -->\n        <dependency>\n            <groupId>com.salesforce.servicelibs</groupId>\n            <artifactId>jprotoc</artifactId>\n            <version>0.9.1</version>\n        </dependency>\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-protobuf</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n        <!-- scope : test -->\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n                <version>1.5.8.RELEASE</version>\n                <executions>\n                    <execution>\n                        <goals>\n                            <goal>repackage</goal>\n                        </goals>\n                    </execution>\n                </executions>\n                <configuration>\n                    <mainClass>io.rouz.grpc.kotlin.GrpcKotlinGenerator</mainClass>\n                    <layout>JAR</layout>\n                </configuration>\n            </plugin>\n            <plugin>\n                <groupId>com.salesforce.servicelibs</groupId>\n                <artifactId>canteen-maven-plugin</artifactId>\n                <version>1.0.0</version>\n                <executions>\n                    <execution>\n                        <goals>\n                            <goal>bootstrap</goal>\n                        </goals>\n                    </execution>\n                </executions>\n            </plugin>\n        </plugins>\n    </build>\n</project>\n"
  },
  {
    "path": "grpc-kotlin-gen/src/main/java/io/rouz/grpc/kotlin/GrpcKotlinGenerator.java",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-gen\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\n/*\n *  Copyright (c) 2017, salesforce.com, inc.\n *  All rights reserved.\n *  Licensed under the BSD 3-Clause license.\n *  For full license text, see https://opensource.org/licenses/BSD-3-Clause\n */\n\npackage io.rouz.grpc.kotlin;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.google.common.html.HtmlEscapers;\nimport com.google.protobuf.DescriptorProtos.FileDescriptorProto;\nimport com.google.protobuf.DescriptorProtos.FileOptions;\nimport com.google.protobuf.DescriptorProtos.MethodDescriptorProto;\nimport com.google.protobuf.DescriptorProtos.ServiceDescriptorProto;\nimport com.google.protobuf.DescriptorProtos.SourceCodeInfo.Location;\nimport com.google.protobuf.compiler.PluginProtos;\nimport com.salesforce.jprotoc.Generator;\nimport com.salesforce.jprotoc.GeneratorException;\nimport com.salesforce.jprotoc.ProtoTypeMap;\nimport com.salesforce.jprotoc.ProtocPlugin;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\nimport static com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest;\nimport static com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse;\n\npublic class GrpcKotlinGenerator extends Generator {\n\n  private static final int SERVICE_NUMBER_OF_PATHS = 2;\n  private static final int METHOD_NUMBER_OF_PATHS = 4;\n  private static final String CLASS_SUFFIX = \"ImplBase\";\n  private static final String STUB_SUFFIX = \"StubExt\";\n  private static final String ADAPTERS_FILE_PATH = \"io/rouz/grpc/Adapters.kt\";\n  private static final String SERVICE_JAVA_DOC_PREFIX = \"    \";\n  private static final String METHOD_JAVA_DOC_PREFIX = \"        \";\n\n  public static void main(String[] args) {\n    ProtocPlugin.generate(new GrpcKotlinGenerator());\n  }\n\n  @Override\n  public List<CodeGeneratorResponse.File> generateFiles(CodeGeneratorRequest request)\n      throws GeneratorException {\n    final ProtoTypeMap typeMap = ProtoTypeMap.of(request.getProtoFileList());\n\n    List<FileDescriptorProto> protosToGenerate = request.getProtoFileList().stream()\n        .filter(protoFile -> request.getFileToGenerateList().contains(protoFile.getName()))\n        .collect(Collectors.toList());\n\n    List<Context> services = findServices(protosToGenerate, typeMap);\n    return generateFiles(services);\n  }\n\n  private List<Context> findServices(List<FileDescriptorProto> protos, ProtoTypeMap typeMap) {\n    List<Context> contexts = new ArrayList<>();\n\n    protos.forEach(fileProto -> {\n      List<Location> locations = fileProto.getSourceCodeInfo().getLocationList();\n      locations.stream()\n          .filter(location -> location.getPathCount() == SERVICE_NUMBER_OF_PATHS\n              && location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER)\n          .forEach(location -> {\n            int serviceNumber = location.getPath(SERVICE_NUMBER_OF_PATHS - 1);\n            Context context = context(\n                fileProto.getService(serviceNumber), typeMap, locations, serviceNumber);\n            context.javaDoc = getJavaDoc(getComments(location), SERVICE_JAVA_DOC_PREFIX);\n            context.protoName = fileProto.getName();\n            context.packageName = extractPackageName(fileProto);\n            contexts.add(context);\n          });\n    });\n\n    return contexts;\n  }\n\n  private String extractPackageName(FileDescriptorProto proto) {\n    FileOptions options = proto.getOptions();\n    if (options != null) {\n      String javaPackage = options.getJavaPackage();\n      if (!Strings.isNullOrEmpty(javaPackage)) {\n        return javaPackage;\n      }\n    }\n\n    return Strings.nullToEmpty(proto.getPackage());\n  }\n\n  private Context context(\n      ServiceDescriptorProto serviceProto,\n      ProtoTypeMap protoTypeMap,\n      List<Location> locations,\n      int serviceNumber) {\n\n    Context context = new Context();\n    context.serviceName = serviceProto.getName();\n    context.deprecated = serviceProto.getOptions() != null\n        && serviceProto.getOptions().getDeprecated();\n\n    locations.stream()\n        .filter(location -> location.getPathCount() == METHOD_NUMBER_OF_PATHS\n                            && location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER\n                            && location.getPath(1) == serviceNumber\n                            && location.getPath(2) == ServiceDescriptorProto.METHOD_FIELD_NUMBER)\n        .forEach(location -> {\n          int methodNumber = location.getPath(METHOD_NUMBER_OF_PATHS - 1);\n          MethodContext methodContext = methodContext(\n              serviceProto.getMethod(methodNumber), protoTypeMap);\n          methodContext.methodNumber = methodNumber;\n          methodContext.javaDoc = getJavaDoc(getComments(location), METHOD_JAVA_DOC_PREFIX);\n          context.methods.add(methodContext);\n        });\n    return context;\n  }\n\n  private MethodContext methodContext(MethodDescriptorProto methodProto, ProtoTypeMap typeMap) {\n    MethodContext methodContext = new MethodContext();\n    methodContext.methodName = lowerCaseFirst(methodProto.getName());\n    methodContext.inputType = typeMap.toJavaTypeName(methodProto.getInputType());\n    methodContext.outputType = typeMap.toJavaTypeName(methodProto.getOutputType());\n    methodContext.deprecated = methodProto.getOptions() != null\n        && methodProto.getOptions().getDeprecated();\n    methodContext.isManyInput = methodProto.getClientStreaming();\n    methodContext.isManyOutput = methodProto.getServerStreaming();\n    if (!methodProto.getClientStreaming() && !methodProto.getServerStreaming()) {\n      methodContext.grpcCallsMethodName = \"asyncUnaryCall\";\n    }\n    if (!methodProto.getClientStreaming() && methodProto.getServerStreaming()) {\n      methodContext.grpcCallsMethodName = \"asyncServerStreamingCall\";\n    }\n    if (methodProto.getClientStreaming() && !methodProto.getServerStreaming()) {\n      methodContext.grpcCallsMethodName = \"asyncClientStreamingCall\";\n    }\n    if (methodProto.getClientStreaming() && methodProto.getServerStreaming()) {\n      methodContext.grpcCallsMethodName = \"asyncBidiStreamingCall\";\n    }\n    return methodContext;\n  }\n\n  private String lowerCaseFirst(String s) {\n    return Character.toLowerCase(s.charAt(0)) + s.substring(1);\n  }\n\n  private List<PluginProtos.CodeGeneratorResponse.File> generateFiles(List<Context> services) {\n    List<PluginProtos.CodeGeneratorResponse.File> files = new ArrayList<>();\n\n    files.add(buildUtilFile());\n    for (Context service : services) {\n      files.add(buildServiceBaseImpl(service));\n      files.add(buildStubExtensions(service));\n    }\n\n    return files;\n  }\n\n  private PluginProtos.CodeGeneratorResponse.File buildUtilFile() {\n    UtilContext utilContext = new UtilContext();\n    String content = applyTemplate(\"Adapters.mustache\", utilContext);\n\n    return PluginProtos.CodeGeneratorResponse.File\n        .newBuilder()\n        .setName(ADAPTERS_FILE_PATH)\n        .setContent(content)\n        .build();\n  }\n\n  private PluginProtos.CodeGeneratorResponse.File buildServiceBaseImpl(Context context) {\n    String content = applyTemplate(\"ImplBase.mustache\", context);\n    String fileName = context.serviceName + CLASS_SUFFIX + \".kt\";\n    return PluginProtos.CodeGeneratorResponse.File\n        .newBuilder()\n        .setName(absoluteFileName(context.packageName, fileName))\n        .setContent(content)\n        .build();\n  }\n\n    PluginProtos.CodeGeneratorResponse.File buildStubExtensions(Context context) {\n    String content = applyTemplate(\"StubExtensions.mustache\", context);\n    String fileName = context.serviceName + STUB_SUFFIX + \".kt\";\n    return PluginProtos.CodeGeneratorResponse.File\n        .newBuilder()\n        .setName(absoluteFileName(context.packageName, fileName))\n        .setContent(content)\n        .build();\n  }\n\n    private static String absoluteFileName(String packageName, String fileName) {\n        Preconditions.checkNotNull(packageName, \"packageName\");\n    String dir = packageName.replace('.', '/');\n    if (Strings.isNullOrEmpty(dir)) {\n      return fileName;\n    } else {\n      return dir + \"/\" + fileName;\n    }\n  }\n\n  private String getComments(Location location) {\n    return location.getLeadingComments().isEmpty()\n        ? location.getTrailingComments()\n        : location.getLeadingComments();\n  }\n\n  private String getJavaDoc(String comments, String prefix) {\n    if (!comments.isEmpty()) {\n      StringBuilder builder = new StringBuilder(\"/**\\n\")\n          .append(prefix).append(\" * <pre>\\n\");\n      Arrays.stream(HtmlEscapers.htmlEscaper().escape(comments).split(\"\\n\"))\n          // Kotlin allows nested block comments, so any occurrence of '/*' would begin\n          // a nested block, breaking the generated code.\n          .map(line -> line.replace(\"/*\", \"/&#42;\"))\n          .map(line -> line.replace(\"*/\", \"*&#47;\"))\n          .forEach(line -> builder.append(prefix).append(\" * \").append(line).append(\"\\n\"));\n      builder\n          .append(prefix).append(\" * <pre>\\n\")\n          .append(prefix).append(\" */\");\n      return builder.toString();\n    }\n    return null;\n  }\n\n  /**\n   * Template class for proto Service objects.\n   */\n  protected final class Context {\n    // CHECKSTYLE DISABLE VisibilityModifier FOR 6 LINES\n    public String protoName;\n    public String packageName;\n    public String serviceName;\n    public boolean deprecated;\n    public String javaDoc;\n    public List<MethodContext> methods = new ArrayList<>();\n  }\n\n  /**\n   * Template class for proto RPC objects.\n   */\n  private class MethodContext {\n    // CHECKSTYLE DISABLE VisibilityModifier FOR 10 LINES\n    public String methodName;\n    public String inputType;\n    public String outputType;\n    public boolean deprecated;\n    public boolean isManyInput;\n    public boolean isManyOutput;\n    public String grpcCallsMethodName;\n    public int methodNumber;\n    public String javaDoc;\n\n    // This method mimics the upper-casing method ogf gRPC to ensure compatibility\n    // See https://github.com/grpc/grpc-java/blob/v1.8.0/compiler/src/java_plugin/cpp/java_generator.cpp#L58\n    public String methodNameUpperUnderscore() {\n      StringBuilder s = new StringBuilder();\n      for (int i = 0; i < methodName.length(); i++) {\n        char c = methodName.charAt(i);\n        s.append(Character.toUpperCase(c));\n        if ((i < methodName.length() - 1)\n            && Character.isLowerCase(c)\n            && Character.isUpperCase(methodName.charAt(i + 1))) {\n          s.append('_');\n        }\n      }\n      return s.toString();\n    }\n\n    public String methodNamePascalCase() {\n      return String.valueOf(Character.toUpperCase(methodName.charAt(0))) + methodName.substring(1);\n    }\n  }\n\n  /**\n   * Template class for adapters file.\n   */\n  private class UtilContext {\n  }\n}\n"
  },
  {
    "path": "grpc-kotlin-gen/src/main/resources/Adapters.mustache",
    "content": "package io.rouz.grpc\n\nimport io.grpc.Context\nimport io.grpc.stub.StreamObserver\nimport kotlin.coroutines.*\nimport kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.*\n\nclass ManyToOneCall<in TRequest, out TResponse>(\n    private val request: StreamObserver<TRequest>,\n    private val response: Deferred<TResponse>\n) : StreamObserverSendAdapter<TRequest>(request),\n    Deferred<TResponse> by response\n\nclass ManyToManyCall<in TRequest, out TResponse>(\n    private val request: StreamObserver<TRequest>,\n    private val response: ReceiveChannel<TResponse>\n) : StreamObserverSendAdapter<TRequest>(request),\n    ReceiveChannel<TResponse> by response\n\nopen class StreamObserverSendAdapter<in E>(private val streamObserver: StreamObserver<E>) {\n\n    fun close(cause: Throwable? = null): Boolean {\n        if (cause != null) {\n            streamObserver.onError(cause)\n        } else {\n            streamObserver.onCompleted()\n        }\n\n        return true\n    }\n\n    fun send(element: E) {\n        streamObserver.onNext(element)\n    }\n}\n\nclass ContinuationStreamObserver<E>(\n    private val continuation: Continuation<E>\n) : StreamObserver<E> {\n\n    override fun onNext(value: E) {\n        continuation.resume(value)\n    }\n\n    override fun onError(t: Throwable) {\n        continuation.resumeWithException(t)\n    }\n\n    override fun onCompleted() {}\n}\n\nclass StreamObserverDeferred<E>(\n    private val deferred: CompletableDeferred<E> = CompletableDeferred()\n) : StreamObserver<E>, Deferred<E> by deferred {\n\n    override fun onNext(value: E) {\n        deferred.complete(value)\n    }\n\n    override fun onError(t: Throwable) {\n        deferred.completeExceptionally(t)\n    }\n\n    override fun onCompleted() { /* nothing */\n    }\n}\n\nclass StreamObserverChannel<E>(\n    private val channel: Channel<E> = Channel<E>(Channel.UNLIMITED)\n) : StreamObserver<E>, ReceiveChannel<E> by channel {\n\n    override fun onNext(value: E) {\n        channel.offer(value)\n    }\n\n    override fun onError(t: Throwable?) {\n        channel.close(cause = t)\n    }\n\n    override fun onCompleted() {\n        channel.close(cause = null)\n    }\n}\n\nclass ContextCoroutineContextElement : ThreadContextElement<Context> {\n\n    companion object Key : CoroutineContext.Key<ContextCoroutineContextElement>\n\n    private val grpcContext: Context = Context.current()\n\n    override val key: CoroutineContext.Key<ContextCoroutineContextElement>\n        get() = Key\n\n    override fun updateThreadContext(context: CoroutineContext): Context =\n        grpcContext.attach()\n\n    override fun restoreThreadContext(context: CoroutineContext, oldState: Context) =\n        grpcContext.detach(oldState)\n}\n"
  },
  {
    "path": "grpc-kotlin-gen/src/main/resources/ImplBase.mustache",
    "content": "{{#packageName}}\npackage {{packageName}}\n{{/packageName}}\n\nimport {{packageName}}.{{serviceName}}Grpc.*\n\nimport io.grpc.*\nimport io.grpc.stub.*\nimport io.rouz.grpc.*\n\nimport kotlin.coroutines.*\nimport kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.*\n\n{{#javaDoc}}{{{javaDoc}}}{{/javaDoc}}\n{{#deprecated}}@Deprecated(\"deprecated\"){{/deprecated}}\n@javax.annotation.Generated(\n    value = [\"by gRPC Kotlin generator\"],\n    comments = \"Source: {{protoName}}\"\n)\nabstract class {{serviceName}}ImplBase(\n    coroutineContext: CoroutineContext = Dispatchers.Default\n) : BindableService, CoroutineScope {\n\n    private val _coroutineContext: CoroutineContext = coroutineContext\n\n    override val coroutineContext: CoroutineContext\n        get() = ContextCoroutineContextElement() + _coroutineContext\n\n    {{#methods}}\n    {{#javaDoc}}{{{javaDoc}}}{{/javaDoc}}\n    {{#deprecated}}@Deprecated(\"deprecated\"){{/deprecated}}\n    {{^isManyInput}}\n    {{^isManyOutput}}\n    {{! == unary req, unary resp == }}\n    open suspend fun {{methodName}}(request: {{inputType}}): {{outputType}} {\n        throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()\n    }\n\n    internal fun {{methodName}}Internal(\n        request: {{inputType}},\n        responseObserver: StreamObserver<{{outputType}}>\n    ) {\n        launch {\n            tryCatchingStatus(responseObserver) {\n                val response = {{methodName}}(request)\n                onNext(response)\n            }\n        }\n    }\n    {{/isManyOutput}}\n    {{#isManyOutput}}\n    {{! == unary req, streaming resp == }}\n    open fun {{methodName}}(request: {{inputType}}): ReceiveChannel<{{outputType}}> {\n        throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()\n    }\n\n    internal fun {{methodName}}Internal(\n        request: {{inputType}},\n        responseObserver: StreamObserver<{{outputType}}>\n    ) {\n        launch {\n            tryCatchingStatus(responseObserver) {\n                val responses = {{methodName}}(request)\n                for (response in responses) {\n                    try {\n                        onNext(response)\n                    } catch (e: Throwable) {\n                        responses.cancel()\n                        throw e\n                    }\n                }\n            }\n        }\n    }\n    {{/isManyOutput}}\n    {{/isManyInput}}\n    {{#isManyInput}}\n    {{^isManyOutput}}\n    {{! == streaming req, unary resp == }}\n    open suspend fun {{methodName}}(requests: ReceiveChannel<{{inputType}}>): {{outputType}} {\n        throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()\n    }\n\n    internal fun {{methodName}}Internal(\n        responseObserver: StreamObserver<{{outputType}}>\n    ): StreamObserver<{{inputType}}> {\n        val requests = StreamObserverChannel<{{inputType}}>()\n        launch {\n            tryCatchingStatus(responseObserver) {\n                val response = {{methodName}}(requests)\n                onNext(response)\n            }\n        }\n        return requests\n    }\n    {{/isManyOutput}}\n    {{#isManyOutput}}\n    {{! == streaming req, streaming resp == }}\n    open fun {{methodName}}(requests: ReceiveChannel<{{inputType}}>): ReceiveChannel<{{outputType}}> {\n        throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()\n    }\n\n    internal fun {{methodName}}Internal(\n        responseObserver: StreamObserver<{{outputType}}>\n    ): StreamObserver<{{inputType}}> {\n        val requests = StreamObserverChannel<{{inputType}}>()\n        launch {\n            tryCatchingStatus(responseObserver) {\n                val responses = {{methodName}}(requests)\n                for (response in responses) {\n                    try {\n                        onNext(response)\n                    } catch (e: Throwable) {\n                        responses.cancel()\n                        throw e\n                    }\n                }\n            }\n        }\n        return requests\n    }\n    {{/isManyOutput}}\n    {{/isManyInput}}\n    {{/methods}}\n\n    override fun bindService(): ServerServiceDefinition {\n        return ServerServiceDefinition.builder(getServiceDescriptor())\n            {{#methods}}\n            .addMethod(\n                get{{methodNamePascalCase}}Method(),\n                ServerCalls.{{grpcCallsMethodName}}(\n                    MethodHandlers(METHODID_{{methodNameUpperUnderscore}})\n                )\n            )\n            {{/methods}}\n            .build()\n    }\n\n    private fun unimplemented(methodDescriptor: MethodDescriptor<*, *>): Status {\n        return Status.UNIMPLEMENTED\n            .withDescription(\"Method ${methodDescriptor.fullMethodName} is unimplemented\")\n    }\n\n    private fun <E> handleException(t: Throwable?, responseObserver: StreamObserver<E>) {\n        when (t) {\n            null -> return\n            is CancellationException -> handleException(t.cause, responseObserver)\n            is StatusException, is StatusRuntimeException -> responseObserver.onError(t)\n            is RuntimeException -> {\n                responseObserver.onError(Status.UNKNOWN.asRuntimeException())\n                throw t\n            }\n            is Exception -> {\n                responseObserver.onError(Status.UNKNOWN.asException())\n                throw t\n            }\n            else -> {\n                responseObserver.onError(Status.INTERNAL.asException())\n                throw t\n            }\n        }\n    }\n\n    private suspend fun <E> tryCatchingStatus(responseObserver: StreamObserver<E>, body: suspend StreamObserver<E>.() -> Unit) {\n        try {\n            responseObserver.body()\n            responseObserver.onCompleted()\n        } catch (t: Throwable) {\n            handleException(t, responseObserver)\n        }\n    }\n\n    {{#methods}}\n    private val METHODID_{{methodNameUpperUnderscore}} = {{methodNumber}}\n    {{/methods}}\n\n    private inner class MethodHandlers<Req, Resp> internal constructor(\n        private val methodId: Int\n    ) : ServerCalls.UnaryMethod<Req, Resp>,\n        ServerCalls.ServerStreamingMethod<Req, Resp>,\n        ServerCalls.ClientStreamingMethod<Req, Resp>,\n        ServerCalls.BidiStreamingMethod<Req, Resp> {\n\n        @Suppress(\"UNCHECKED_CAST\")\n        override fun invoke(request: Req, responseObserver: StreamObserver<Resp>) {\n            when (methodId) {\n                {{#methods}}\n                {{^isManyInput}}\n                METHODID_{{methodNameUpperUnderscore}} ->\n                    this@{{serviceName}}ImplBase.{{methodName}}Internal(\n                        request as {{inputType}},\n                        responseObserver as StreamObserver<{{outputType}}>\n                    )\n                {{/isManyInput}}\n                {{/methods}}\n                else -> throw AssertionError()\n            }\n        }\n\n        @Suppress(\"UNCHECKED_CAST\")\n        override fun invoke(responseObserver: StreamObserver<Resp>): StreamObserver<Req> {\n            when (methodId) {\n                {{#methods}}\n                {{#isManyInput}}\n                METHODID_{{methodNameUpperUnderscore}} ->\n                    return this@{{serviceName}}ImplBase.{{methodName}}Internal(\n                        responseObserver as StreamObserver<{{outputType}}>\n                    ) as StreamObserver<Req>\n                {{/isManyInput}}\n                {{/methods}}\n                else -> throw AssertionError()\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-gen/src/main/resources/StubExtensions.mustache",
    "content": "{{#packageName}}\npackage {{packageName}}\n{{/packageName}}\n\nimport io.rouz.grpc.*\nimport {{packageName}}.{{serviceName}}Grpc.{{serviceName}}Stub\n\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlin.coroutines.suspendCoroutine\n\nimport io.grpc.Metadata\nimport io.grpc.stub.MetadataUtils\n\n/**\n * Kotlin extension functions for [{{packageName}}.{{serviceName}}Grpc.{{serviceName}}Stub]\n *\n * Generated by gRPC Kotlin generator\n * Source: {{protoName}}\n */\n\n{{#methods}}\n{{#javaDoc}}{{{javaDoc}}}{{/javaDoc}}\n{{#deprecated}}@Deprecated(\"deprecated\"){{/deprecated}}\n{{^isManyInput}}\n{{^isManyOutput}}\n{{! == unary req, unary resp == }}\nsuspend inline fun {{serviceName}}Stub.{{methodName}}(request: {{inputType}}): {{outputType}} {\n    return suspendCoroutine {\n        {{methodName}}(request, ContinuationStreamObserver(it))\n    }\n}\n{{/isManyOutput}}\n{{#isManyOutput}}\n{{! == unary req, streaming resp == }}\nfun {{serviceName}}Stub.{{methodName}}(request: {{inputType}}): ReceiveChannel<{{outputType}}> {\n    val responseChannel = StreamObserverChannel<{{outputType}}>()\n    {{methodName}}(request, responseChannel)\n    return responseChannel\n}\n{{/isManyOutput}}\n{{/isManyInput}}\n{{#isManyInput}}\n{{^isManyOutput}}\n{{! == streaming req, unary resp == }}\nfun {{serviceName}}Stub.{{methodName}}(): ManyToOneCall<{{inputType}}, {{outputType}}> {\n    val responseDeferred = StreamObserverDeferred<{{outputType}}>()\n    val requestObserver = {{methodName}}(responseDeferred)\n    return ManyToOneCall(requestObserver, responseDeferred)\n}\n{{/isManyOutput}}\n{{#isManyOutput}}\n{{! == streaming req, streaming resp == }}\nfun {{serviceName}}Stub.{{methodName}}(): ManyToManyCall<{{inputType}}, {{outputType}}> {\n    val responseChannel = StreamObserverChannel<{{outputType}}>()\n    val requestObserver = {{methodName}}(responseChannel)\n    return ManyToManyCall(requestObserver, responseChannel)\n}\n{{/isManyOutput}}\n{{/isManyInput}}\n{{/methods}}\n\n/**\n* Adds new binary header and returns the client\n*/\nfun {{serviceName}}Stub.addBinaryHeader(\n    header: String,\n    bytes: ByteArray\n): {{serviceName}}Stub {\n    val headers = Metadata()\n    val key = Metadata.Key.of(header, Metadata.BINARY_BYTE_MARSHALLER)\n    headers.put(key, bytes)\n\n    return MetadataUtils.attachHeaders(this, headers)\n}\n"
  },
  {
    "path": "grpc-kotlin-gen/src/test/java/io/rouz/grpc/kotlin/GrpcKotlinGeneratorTest.java",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-gen\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.grpc.kotlin;\n\n\nimport com.google.protobuf.compiler.PluginProtos;\nimport org.junit.Test;\n\nimport static org.junit.Assert.assertTrue;\n\npublic class GrpcKotlinGeneratorTest extends GrpcKotlinGenerator {\n\n  @Test\n  public void buildStubExtensionsTest() {\n    Context ctx = new Context();\n    ctx.packageName = \"some.package\";\n    ctx.serviceName = \"SomeService\";\n    PluginProtos.CodeGeneratorResponse.File result = this.buildStubExtensions(ctx);\n\n    String expected = \"fun SomeServiceStub.addBinaryHeader(\\n\" +\n            \"    header: String,\\n\" +\n            \"    bytes: ByteArray\\n\" +\n            \"): SomeServiceStub {\\n\" +\n            \"    val headers = Metadata()\\n\" +\n            \"    val key = Metadata.Key.of(header, Metadata.BINARY_BYTE_MARSHALLER)\\n\" +\n            \"    headers.put(key, bytes)\\n\" +\n            \"\\n\" +\n            \"    return MetadataUtils.attachHeaders(this, headers)\\n\" +\n            \"}\";\n\n    String resultContent = result.getContent().replaceAll(\"\\\\r\", \"\");\n    assertTrue(resultContent.contains(expected));\n  }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <parent>\n        <groupId>io.rouz</groupId>\n        <artifactId>grpc-kotlin-parent</artifactId>\n        <version>0.1.5-SNAPSHOT</version>\n    </parent>\n\n    <name>grpc-kotlin-test</name>\n    <artifactId>grpc-kotlin-test</artifactId>\n    <packaging>jar</packaging>\n\n    <properties>\n        <kotlin.version>1.3.61</kotlin.version>\n        <kotlinx-coroutines.version>1.3.3</kotlinx-coroutines.version>\n        <grpc.version>1.25.0</grpc.version>\n        <protobuf.version>3.10.0</protobuf.version>\n    </properties>\n\n    <dependencies>\n        <!-- scope : compile -->\n        <dependency>\n            <groupId>org.jetbrains.kotlin</groupId>\n            <artifactId>kotlin-stdlib</artifactId>\n            <version>${kotlin.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>org.jetbrains.kotlinx</groupId>\n            <artifactId>kotlinx-coroutines-core</artifactId>\n            <version>${kotlinx-coroutines.version}</version>\n        </dependency>\n\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-netty</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-protobuf</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-stub</artifactId>\n            <version>${grpc.version}</version>\n        </dependency>\n\n        <dependency>\n            <groupId>io.github.microutils</groupId>\n            <artifactId>kotlin-logging</artifactId>\n            <version>1.4.9</version>\n        </dependency>\n        <dependency>\n            <groupId>org.slf4j</groupId>\n            <artifactId>slf4j-simple</artifactId>\n            <version>1.7.25</version>\n        </dependency>\n        <dependency>\n            <groupId>javax.annotation</groupId>\n            <artifactId>javax.annotation-api</artifactId>\n            <version>1.3.2</version>\n        </dependency>\n\n        <!-- scope : test -->\n        <dependency>\n            <groupId>io.grpc</groupId>\n            <artifactId>grpc-testing</artifactId>\n            <version>${grpc.version}</version>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <extensions>\n            <extension>\n                <groupId>kr.motd.maven</groupId>\n                <artifactId>os-maven-plugin</artifactId>\n                <version>1.5.0.Final</version>\n            </extension>\n        </extensions>\n\n        <plugins>\n            <plugin>\n                <groupId>org.xolstice.maven.plugins</groupId>\n                <artifactId>protobuf-maven-plugin</artifactId>\n                <version>0.6.1</version>\n                <configuration>\n                    <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}\n                    </protocArtifact>\n                </configuration>\n                <executions>\n                    <execution>\n                        <goals>\n                            <goal>compile</goal>\n                        </goals>\n                    </execution>\n                    <execution>\n                        <id>grpc-java</id>\n                        <goals>\n                            <goal>compile-custom</goal>\n                        </goals>\n                        <configuration>\n                            <pluginId>grpc-java</pluginId>\n                            <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}\n                            </pluginArtifact>\n                        </configuration>\n                    </execution>\n                    <execution>\n                        <id>grpc-kotlin</id>\n                        <goals>\n                            <goal>compile-custom</goal>\n                        </goals>\n                        <configuration>\n                            <pluginId>grpc-kotlin</pluginId>\n                            <pluginArtifact>io.rouz:grpc-kotlin-gen:${project.version}:exe:${os.detected.classifier}</pluginArtifact>\n                        </configuration>\n                    </execution>\n                </executions>\n            </plugin>\n            <plugin>\n                <artifactId>kotlin-maven-plugin</artifactId>\n                <groupId>org.jetbrains.kotlin</groupId>\n                <version>${kotlin.version}</version>\n                <configuration>\n                    <jvmTarget>1.8</jvmTarget>\n                    <args>-Xuse-experimental=kotlin.Experimental</args>\n                </configuration>\n                <executions>\n                    <execution>\n                        <id>compile</id>\n                        <phase>compile</phase>\n                        <goals>\n                            <goal>compile</goal>\n                        </goals>\n                        <configuration>\n                            <sourceDirs>\n                                <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>\n                                <sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-kotlin</sourceDir>\n                                <sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-java</sourceDir>\n                                <sourceDir>${project.basedir}/target/generated-sources/protobuf/java</sourceDir>\n                            </sourceDirs>\n                        </configuration>\n                    </execution>\n                    <execution>\n                        <id>test-compile</id>\n                        <goals>\n                            <goal>test-compile</goal>\n                        </goals>\n                        <configuration>\n                            <sourceDirs>\n                                <sourceDir>${project.basedir}/src/test/kotlin</sourceDir>\n                            </sourceDirs>\n                        </configuration>\n                    </execution>\n                </executions>\n            </plugin>\n\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-compiler-plugin</artifactId>\n                <executions>\n                    <!-- Replacing default-compile as it is treated specially by maven -->\n                    <execution>\n                        <id>default-compile</id>\n                        <phase>none</phase>\n                    </execution>\n                    <!-- Replacing default-testCompile as it is treated specially by maven -->\n                    <execution>\n                        <id>default-testCompile</id>\n                        <phase>none</phase>\n                    </execution>\n                    <execution>\n                        <id>java-compile</id>\n                        <phase>compile</phase>\n                        <goals>\n                            <goal>compile</goal>\n                        </goals>\n                    </execution>\n                    <execution>\n                        <id>java-test-compile</id>\n                        <phase>test-compile</phase>\n                        <goals>\n                            <goal>testCompile</goal>\n                        </goals>\n                    </execution>\n                </executions>\n            </plugin>\n\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-deploy-plugin</artifactId>\n                <version>2.8.2</version>\n                <configuration>\n                    <skip>true</skip>\n                </configuration>\n            </plugin>\n        </plugins>\n    </build>\n</project>\n"
  },
  {
    "path": "grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/GreeterImpl.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.asCoroutineDispatcher\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\nimport kotlinx.coroutines.delay\nimport kotlinx.coroutines.launch\nimport mu.KotlinLogging\nimport java.util.concurrent.Executors.newFixedThreadPool\n\n/**\n * Implementation of coroutine-based gRPC service defined in greeter.proto\n */\n@UseExperimental(ExperimentalCoroutinesApi::class)\nopen class GreeterImpl : GreeterImplBase(\n    coroutineContext = newFixedThreadPool(4, threadFactory(\"server-worker-%d\")).asCoroutineDispatcher()\n) {\n\n    protected val log = KotlinLogging.logger(\"server\")\n\n    override suspend fun greet(request: GreetRequest): GreetReply {\n        log.info(request.greeting)\n\n        return GreetReply.newBuilder()\n            .setReply(\"Hello \" + request.greeting)\n            .build()\n    }\n\n    override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n        log.info(request.greeting)\n\n        send(\n            GreetReply.newBuilder()\n                .setReply(\"Hello ${request.greeting}!\")\n                .build()\n        )\n        send(\n            GreetReply.newBuilder()\n                .setReply(\"Greetings ${request.greeting}!\")\n                .build()\n        )\n    }\n\n    override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {\n        val greetings = mutableListOf<String>()\n\n        for (request in requests) {\n            log.info(request.greeting)\n            greetings.add(request.greeting)\n        }\n\n        return GreetReply.newBuilder()\n            .setReply(\"Hi to all of $greetings!\")\n            .build()\n    }\n\n    override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n        var count = 0\n\n        for (request in requests) {\n            val n = count++\n            log.info(\"$n ${request.greeting}\")\n            launch {\n                delay(100)\n                send(\n                    GreetReply.newBuilder()\n                        .setReply(\"Yo #$n ${request.greeting}\")\n                        .build()\n                )\n                log.info(\"dispatched $n\")\n            }\n        }\n\n        log.info(\"completing\")\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/GreeterMain.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport com.google.common.util.concurrent.ThreadFactoryBuilder\nimport io.grpc.ManagedChannelBuilder\nimport io.grpc.ServerBuilder\nimport kotlinx.coroutines.delay\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.runBlocking\nimport mu.KotlinLogging\nimport java.util.concurrent.ThreadFactory\n\nfun main(args: Array<String>) {\n    val log = KotlinLogging.logger(\"client\")\n    ServerBuilder.forPort(8080)\n        .addService(GreeterImpl())\n        .build()\n        .start()\n    val localhost = ManagedChannelBuilder.forAddress(\"localhost\", 8080)\n        .usePlaintext()\n        .build()\n\n    val greeter = GreeterGrpc.newStub(localhost)\n\n    runBlocking {\n        // === Unary call =============================================================================\n\n        val unaryResponse = greeter.greet(req(\"Alice\"))\n        log.info(\"unary reply = ${unaryResponse.reply}\")\n\n        // === Server streaming call ==================================================================\n\n        val serverResponses = greeter.greetServerStream(req(\"Bob\"))\n        for (serverResponse in serverResponses) {\n            log.info(\"server response = ${serverResponse.reply}\")\n        }\n\n        // === Client streaming call ==================================================================\n\n        val manyToOneCall = greeter.greetClientStream()\n        manyToOneCall.send(req(\"Caroline\"))\n        manyToOneCall.send(req(\"David\"))\n        manyToOneCall.close()\n        val oneReply = manyToOneCall.await()\n        log.info(\"single reply = ${oneReply.reply}\")\n\n        // === Bidirectional call =====================================================================\n\n        val bidiCall = greeter.greetBidirectional()\n        launch {\n            var n = 0\n            for (greetReply in bidiCall) {\n                log.info(\"reply $n = ${greetReply.reply}\")\n                n++\n            }\n            log.info(\"no more replies\")\n        }\n\n        delay(200)\n        bidiCall.send(req(\"Eve\"))\n\n        delay(200)\n        bidiCall.send(req(\"Fred\"))\n\n        delay(200)\n        bidiCall.send(req(\"Gina\"))\n        bidiCall.close()\n    }\n}\n\nfun req(greeting: String): GreetRequest {\n    return GreetRequest.newBuilder().setGreeting(greeting).build()\n}\n\nfun threadFactory(threadNameFormat: String): ThreadFactory = ThreadFactoryBuilder()\n    .setDaemon(true)\n    .setNameFormat(threadNameFormat)\n    .build()\n"
  },
  {
    "path": "grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/InfiniteStreamGreeterImpl.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.channels.Channel\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.withContext\nimport java.util.concurrent.ConcurrentHashMap\nimport java.util.concurrent.Semaphore\n\nclass InfiniteStreamGreeterImpl : GreeterImpl() {\n\n    val subscribers = ConcurrentHashMap<String, Channel<GreetReply>>()\n    val startupSync = Semaphore(0)\n\n    override fun greetServerStream(request: GreetRequest): ReceiveChannel<GreetReply> =\n            Channel<GreetReply>(100).also {\n                val name = request.greeting\n                subscribers[name] = it\n                log.info(\"Subscribed: {}\", name)\n                startupSync.release()\n            }\n\n    suspend fun greetAllSubscribers(word: String) {\n        withContext(Dispatchers.IO) {\n            subscribers.forEach { (subs, ch) ->\n                GreetReply.newBuilder().run {\n                    reply = \"$word $subs\"\n                    build()\n                }.also {\n                    launch {\n                        try {\n                            ch.send(it)\n                            log.info(\"Message to client: {}\", it.reply)\n                        } catch (e: Throwable) {\n                            log.info(\"Unsubscribe client: {}\", subs)\n                            subscribers.remove(subs)\n                            ch.close()\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/main/proto/io/rouz/greeter.proto",
    "content": "syntax = \"proto3\";\npackage io.rouz.greeter;\n\noption java_package = \"io.rouz.greeter\";\noption java_multiple_files = true;\n\nmessage GreetRequest {\n    string greeting = 1;\n}\n\nmessage GreetReply {\n    string reply = 1;\n}\n\nservice Greeter {\n    // Adding some comments to ensure correct parsing with respect to kotlin nested block comments\n    // /* That should get escaped so that it doesn't start a block comment\n    // */ That should also get escaped so that it doesn't terminate a javadoc comment block\n    rpc Greet (GreetRequest) returns (GreetReply);\n    rpc GreetServerStream (GreetRequest) returns (stream GreetReply);\n    rpc GreetClientStream (stream GreetRequest) returns (GreetReply);\n    rpc GreetBidirectional (stream GreetRequest) returns (stream GreetReply);\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/main/proto/io/rouz/kvs.proto",
    "content": "syntax = \"proto3\";\npackage io.rouz.kvs;\n\nimport \"io/rouz/greeter.proto\";\n\noption java_package = \"io.rouz.kvs\";\n\nmessage KvsMessage {\n    string msg = 1;\n}\n\nservice KeyValueStore {\n    rpc GetKeyForGreeting (io.rouz.greeter.GreetRequest) returns (io.rouz.greeter.GreetReply);\n    rpc Dummy (KvsMessage) returns (KvsMessage);\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ClientAbandonTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport io.grpc.ManagedChannel\nimport io.grpc.ManagedChannelBuilder\nimport io.grpc.netty.NettyServerBuilder\nimport kotlinx.coroutines.joinAll\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.runBlocking\nimport kotlinx.coroutines.yield\nimport mu.KotlinLogging\nimport org.junit.After\nimport org.junit.Assert.assertEquals\nimport org.junit.Assert.assertTrue\nimport org.junit.Test\nimport org.junit.runner.RunWith\nimport org.junit.runners.JUnit4\nimport java.util.concurrent.TimeUnit.SECONDS\nimport kotlin.coroutines.resume\nimport kotlin.coroutines.suspendCoroutine\n\n\n@RunWith(JUnit4::class)\nclass ClientAbandonTest {\n    private val log = KotlinLogging.logger {}\n\n    private val svc = InfiniteStreamGreeterImpl()\n\n    private fun server() =\n            NettyServerBuilder.forPort(16565)\n                    .addService(svc)\n                    .build()\n                    .start()\n\n    private fun getChannel() = ManagedChannelBuilder\n            .forAddress(\"localhost\", 16565)\n            .usePlaintext()\n            .build().also {\n                channels.add(it)\n            }\n\n\n    private fun dumpSubscribers() =\n            log.info(\"Current subscribers: {}\", svc.subscribers.keys)\n\n    private val serv = server()\n    private val channels: MutableList<ManagedChannel> = mutableListOf()\n\n    @After\n    fun tearDown() {\n        channels.forEach { ch ->\n            if (!ch.shutdownNow().awaitTermination(1, SECONDS)) {\n                error(\"Failed to shutdown channel\")\n            }\n        }\n        if (!serv.shutdownNow().awaitTermination(1, SECONDS)) {\n            error(\"Failed to shutdown server\")\n        }\n    }\n\n    @Test\n    fun infiniteServerStreamingToSubscribers() {\n        // Create two subscribers & subscribe them\n        val rouzStub = GreeterGrpc.newStub(getChannel())\n        val igorStub = GreeterGrpc.newStub(getChannel())\n\n        val rouzCh = rouzStub.greetServerStream(req(\"rouz\"))\n        val igorCh = igorStub.greetServerStream(req(\"igor\"))\n        svc.startupSync.acquire(2)\n\n        runBlocking {\n            dumpSubscribers()\n            assertEquals(setOf(\"rouz\", \"igor\"), svc.subscribers.keys)\n\n            // Publish greeting to all\n            val rouzJob = launch {\n                rouzCh.receive().also {\n                    assertEquals(\"Hello rouz\", it.reply)\n                }\n            }\n\n            val igorJob = launch {\n                igorCh.receive().also {\n                    assertEquals(\"Hello igor\", it.reply)\n                }\n            }\n\n            val sendJob = launch {\n                svc.greetAllSubscribers(\"Hello\")\n            }\n\n            joinAll(rouzJob, igorJob, sendJob)\n            assertEquals(setOf(\"rouz\", \"igor\"), svc.subscribers.keys)\n\n            // One client disconnects\n            suspendCoroutine<Unit> {\n                val ch = igorStub.channel as ManagedChannel\n                ch.shutdownNow()\n                it.resume(assertTrue(ch.awaitTermination(1, SECONDS)))\n            }\n\n            // Continue publishing of new greetings\n            val rouzJob2 = launch {\n                repeat(4) {\n                    assertEquals(\"Hola $it rouz\", rouzCh.receive().reply)\n                }\n            }\n\n            // One of the first invocations should close the channel of Igor, the next one should remove subscription.\n            val senderJob2 = launch {\n                repeat(4) {\n                    svc.greetAllSubscribers(\"Hola $it\")\n                    yield()\n                }\n            }\n\n            joinAll(rouzJob2, senderJob2)\n\n            // Check that subscription of Igor has gone\n            dumpSubscribers()\n            assertEquals(setOf(\"rouz\"), svc.subscribers.keys)\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ClosingStatusExceptionTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\n\nclass ClosingStatusExceptionTest : StatusExceptionTestBase() {\n\n    override val service: GreeterImplBase\n        get() = StatusThrowingGreeter()\n\n    @UseExperimental(ExperimentalCoroutinesApi::class)\n    private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {\n\n        override suspend fun greet(request: GreetRequest): GreetReply {\n            throw notFound(\"uni\")\n        }\n\n        override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n            close(notFound(\"sstream\"))\n        }\n\n        override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {\n            throw notFound(\"cstream\")\n        }\n\n        override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n            close(notFound(\"bidi\"))\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ContextBasedGreeterTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport io.grpc.Context\nimport io.grpc.Contexts\nimport io.grpc.Metadata\nimport io.grpc.ServerCall\nimport io.grpc.ServerCallHandler\nimport io.grpc.ServerInterceptor\nimport io.grpc.stub.MetadataUtils\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\nimport kotlinx.coroutines.channels.toList\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.runBlocking\nimport org.junit.Assert\nimport org.junit.Test\n\nclass ContextBasedGreeterTest : GrpcTestBase() {\n\n    companion object {\n        private val userContextKey = Context.key<String>(\"user name\")\n        private val userMetadataKey = Metadata.Key.of(\"User-Name\", Metadata.ASCII_STRING_MARSHALLER)\n    }\n\n    @Test\n    fun contextValueMissing() {\n        val stub = startServer(ContextGreeter())\n\n        runBlocking {\n            val reply = stub.greet(req(\"rouz\"))\n\n            Assert.assertEquals(\"Hello anonymous\", reply.reply)\n        }\n    }\n\n    @Test\n    fun contextValuePresent() {\n        val stub = MetadataUtils.attachHeaders(\n            startServer(ContextGreeter()),\n            Metadata().apply { put(userMetadataKey, \"Chad\") }\n        )\n\n        runBlocking {\n            val reply = stub.greet(req(\"rouz\"))\n\n            Assert.assertEquals(\"Hello Chad\", reply.reply)\n        }\n    }\n\n    @Test\n    fun contextTransferredAcrossThreads() {\n        /*\n         * This test is intended to ensure that the context gets transferred as expected to child coroutines and multiple\n         * threads. We ensure this by having the service include the thread ID in the reply and verifying that more than\n         * one thread issued replies.\n         */\n        val stub = MetadataUtils.attachHeaders(\n            startServer(ContextGreeter()),\n            Metadata().apply { put(userMetadataKey, \"Jordan\") }\n        )\n\n        runBlocking {\n            val replies = stub.greetServerStream(req(\"rouz\")).toList()\n\n            val regex = Regex(\"Hi #\\\\d{1,3} Jordan from (\\\\d+)\")\n            val threadIds = replies\n                .map { regex.matchEntire(it.reply) }\n                .onEach { Assert.assertNotNull(\"Reply did not match '${regex.pattern}'\", it) }.filterNotNull()\n                .map { it.groups[1]?.value }\n                .onEach { Assert.assertNotNull(it) }.filterNotNull()\n                .toSet()\n            Assert.assertNotEquals(\"All messages were dispatched by a single thread\", 1, threadIds.size)\n        }\n    }\n\n    override fun serverInterceptor(): ServerInterceptor = ServerNameInterceptor\n\n    inner class ContextGreeter : GreeterImplBase() {\n        override suspend fun greet(request: GreetRequest): GreetReply =\n            repl(\"Hello ${userContextKey.get() ?: \"anonymous\"}\")\n\n        @ExperimentalCoroutinesApi\n        override fun greetServerStream(request: GreetRequest): ReceiveChannel<GreetReply> = produce {\n            for (i in 0..99) {\n                launch {\n                    send(repl(\"Hi #$i ${userContextKey.get()} from ${Thread.currentThread().id}\"))\n                }\n            }\n        }\n    }\n\n    object ServerNameInterceptor : ServerInterceptor {\n        override fun <ReqT : Any?, RespT : Any?> interceptCall(\n            call: ServerCall<ReqT, RespT>,\n            headers: Metadata,\n            next: ServerCallHandler<ReqT, RespT>\n        ): ServerCall.Listener<ReqT> = headers[userMetadataKey]\n            ?.let {\n                Contexts.interceptCall(\n                    Context.current().withValue(userContextKey, it),\n                    call,\n                    headers,\n                    next\n                )\n            } ?: next.startCall(call, headers)\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/DelayedClosingStatusExceptionTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.async\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.SendChannel\nimport kotlinx.coroutines.channels.produce\nimport kotlinx.coroutines.delay\nimport kotlinx.coroutines.launch\n\nclass DelayedClosingStatusExceptionTest : StatusExceptionTestBase() {\n\n    override val service: GreeterImplBase\n        get() = StatusThrowingGreeter()\n\n    @UseExperimental(ExperimentalCoroutinesApi::class)\n    private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {\n\n        override suspend fun greet(request: GreetRequest): GreetReply {\n            async {\n                delay(10)\n                throw notFound(\"uni\")\n            }.await()\n        }\n\n        override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n            launch {\n                delay(10)\n                close(notFound(\"sstream\"))\n            }\n        }\n\n        override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {\n            async {\n                delay(10)\n                throw notFound(\"cstream\")\n            }.await()\n        }\n\n        override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n            launch {\n                delay(10)\n                close(notFound(\"bidi\"))\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/DelayedThrowingStatusExceptionTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.async\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\nimport kotlinx.coroutines.delay\nimport kotlinx.coroutines.launch\n\n@UseExperimental(ExperimentalCoroutinesApi::class)\nclass DelayedThrowingStatusExceptionTest : StatusExceptionTestBase() {\n\n    override val service: GreeterImplBase\n        get() = StatusThrowingGreeter()\n\n    @UseExperimental(ExperimentalCoroutinesApi::class)\n    private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {\n\n        override suspend fun greet(request: GreetRequest): GreetReply {\n            async {\n                delay(10)\n                throw notFound(\"uni\")\n            }.await()\n        }\n\n        override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n            launch {\n                delay(10)\n                throw notFound(\"sstream\")\n            }\n        }\n\n        override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {\n            async {\n                delay(10)\n                throw notFound(\"cstream\")\n            }.await()\n        }\n\n        override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n            launch {\n                delay(10)\n                throw notFound(\"bidi\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ExceptionPropagationTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport io.grpc.StatusRuntimeException\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\nimport kotlinx.coroutines.runBlocking\nimport org.junit.Rule\nimport org.junit.Test\nimport org.junit.rules.ExpectedException\nimport org.junit.runner.RunWith\nimport org.junit.runners.JUnit4\nimport java.lang.Thread.sleep\n\n@RunWith(JUnit4::class)\nclass ExceptionPropagationTest : GrpcTestBase() {\n\n    @Rule\n    @JvmField\n    val expect = ExpectedException.none()\n\n    @Test\n    fun unaryException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNKNOWN\")\n\n        runBlocking {\n            stub.greet(req(\"joe\"))\n        }\n    }\n\n    @Test\n    fun serverStreamingException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNKNOWN\")\n\n        runBlocking {\n            stub.greetServerStream(req(\"joe\")).receive()\n        }\n    }\n\n    @Test\n    fun clientStreamingException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNKNOWN\")\n\n        runBlocking {\n            stub.greetClientStream().await()\n        }\n    }\n\n    @Test\n    fun bidirectionalException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNKNOWN\")\n\n        runBlocking {\n            stub.greetBidirectional().receive()\n        }\n    }\n\n    @Test\n    fun unaryPropagateCustomException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(CustomThrowingGreeter.CustomException::class.java)\n        expect.expectMessage(\"my app broke uni\")\n\n        try {\n            runBlocking {\n                stub.greet(req(\"joe\"))\n            }\n        } catch (t: Throwable) { // silence\n        }\n\n        sleep(100) // wait for worker threads to invoke exception handler\n        throw seenExceptions[0]\n    }\n\n    @Test\n    fun serverStreamingPropagateCustomException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(CustomThrowingGreeter.CustomException::class.java)\n        expect.expectMessage(\"my app broke sstream\")\n\n        try {\n            runBlocking {\n                stub.greetServerStream(req(\"jow\")).receive()\n            }\n        } catch (t: Throwable) { // silence\n        }\n\n        sleep(100) // wait for worker threads to invoke exception handler\n        throw seenExceptions[0]\n    }\n\n    @Test\n    fun clientStreamingPropagateCustomException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(CustomThrowingGreeter.CustomException::class.java)\n        expect.expectMessage(\"my app broke cstream\")\n\n        try {\n            runBlocking {\n                stub.greetClientStream().await()\n            }\n        } catch (t: Throwable) { // silence\n        }\n\n        sleep(100) // wait for worker threads to invoke exception handler\n        throw seenExceptions[0]\n    }\n\n    @Test\n    fun bidirectionalPropagateCustomException() {\n        val stub = startServer(CustomThrowingGreeter())\n\n        expect.expect(CustomThrowingGreeter.CustomException::class.java)\n        expect.expectMessage(\"my app broke bidi\")\n\n        try {\n            runBlocking {\n                stub.greetBidirectional().receive()\n            }\n        } catch (t: Throwable) { // silence\n        }\n\n        sleep(100) // wait for worker threads to invoke exception handler\n        throw seenExceptions[0]\n    }\n\n    @UseExperimental(ExperimentalCoroutinesApi::class)\n    private inner class CustomThrowingGreeter : GreeterImplBase(collectExceptions) {\n\n        override suspend fun greet(request: GreetRequest): GreetReply {\n            throw broke(\"uni\")\n        }\n\n        override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n            throw broke(\"sstream\")\n        }\n\n        override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {\n            throw broke(\"cstream\")\n        }\n\n        override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n            throw broke(\"bidi\")\n        }\n\n        private fun broke(description: String): Exception {\n            return CustomException(\"my app broke $description\")\n        }\n\n        inner class CustomException(message: String) : Exception(message)\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/GrpcTestBase.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport io.grpc.ClientInterceptor\nimport io.grpc.ClientInterceptors\nimport io.grpc.ServerInterceptor\nimport io.grpc.ServerInterceptors\nimport io.grpc.testing.GrpcServerRule\nimport io.rouz.greeter.GreeterGrpc.GreeterStub\nimport kotlinx.coroutines.CoroutineExceptionHandler\nimport mu.KotlinLogging\nimport org.junit.Rule\n\nopen class GrpcTestBase {\n\n    val log = KotlinLogging.logger(\"GreeterImplBase\")\n\n    @Rule\n    @JvmField\n    val grpcServer: GrpcServerRule = GrpcServerRule().directExecutor()\n\n    protected val seenExceptions = mutableListOf<Throwable>()\n    protected val collectExceptions = CoroutineExceptionHandler { _, t ->\n        seenExceptions += t\n        log.info(\"Caught exception in exception handler: $t\")\n    }\n\n    protected fun startServer(service: GreeterImplBase): GreeterStub {\n        val serviceDefinition = serverInterceptor()?.let {\n            ServerInterceptors.intercept(service, it)\n        } ?: service.bindService()\n        grpcServer.serviceRegistry.addService(serviceDefinition)\n\n        val channel = clientInterceptor()?.let {\n            ClientInterceptors.intercept(grpcServer.channel, it)\n        } ?: grpcServer.channel\n\n        return GreeterGrpc.newStub(channel)\n    }\n\n    protected open fun serverInterceptor(): ServerInterceptor? = null\n\n    protected open fun clientInterceptor(): ClientInterceptor? = null\n\n    fun req(greeting: String): GreetRequest {\n        return GreetRequest.newBuilder().setGreeting(greeting).build()\n    }\n\n    fun repl(reply: String): GreetReply {\n        return GreetReply.newBuilder().setReply(reply).build()\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/NoStatusExceptionPropagationTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\nimport org.junit.After\n\nclass NoStatusExceptionPropagationTest : StatusExceptionTestBase() {\n\n    override val service: GreeterImplBase\n        get() = StatusThrowingGreeter()\n\n    @After\n    fun tearDown() {\n        assert(seenExceptions.isEmpty()) {\n            \"Status exceptions should not reach context handler\"\n        }\n    }\n\n    @UseExperimental(ExperimentalCoroutinesApi::class)\n    private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {\n\n        override suspend fun greet(request: GreetRequest): GreetReply {\n            throw notFound(\"uni\")\n        }\n\n        override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n            throw notFound(\"sstream\")\n        }\n\n        override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {\n            throw notFound(\"cstream\")\n        }\n\n        override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n            throw notFound(\"bidi\")\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ServiceCallsTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.runBlocking\nimport org.junit.Assert.assertEquals\nimport org.junit.Test\nimport org.junit.runner.RunWith\nimport org.junit.runners.JUnit4\n\n@RunWith(JUnit4::class)\nclass ServiceCallsTest : GrpcTestBase() {\n\n    @Test\n    fun unaryGreet() {\n        val stub = startServer(GreeterImpl())\n\n        runBlocking {\n            val reply = stub.greet(req(\"rouz\"))\n\n            assertEquals(\"Hello rouz\", reply.reply)\n        }\n    }\n\n    @Test\n    fun serverStreamingGreet() {\n        val stub = startServer(GreeterImpl())\n\n        runBlocking {\n            val replies = stub.greetServerStream(req(\"rouz\"))\n\n            assertEquals(\"Hello rouz!\", replies.receive().reply)\n            assertEquals(\"Greetings rouz!\", replies.receive().reply)\n        }\n    }\n\n    @Test\n    fun clientStreamingGreet() {\n        val stub = startServer(GreeterImpl())\n\n        runBlocking {\n            val call = stub.greetClientStream()\n\n            call.send(req(\"rouz\"))\n            call.send(req(\"delavari\"))\n            call.close()\n\n            val reply = call.await()\n\n            assertEquals(\"Hi to all of [rouz, delavari]!\", reply.reply)\n        }\n    }\n\n    @Test\n    fun bidirectionalGreet() {\n        val stub = startServer(GreeterImpl())\n\n        runBlocking {\n            val call = stub.greetBidirectional()\n\n            call.send(req(\"rouz\"))\n            val reply1 = call.receive()\n            assertEquals(\"Yo #0 rouz\", reply1.reply)\n\n            call.send(req(\"delavari\"))\n            val reply2 = call.receive()\n            assertEquals(\"Yo #1 delavari\", reply2.reply)\n\n            call.close()\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/StatusExceptionTestBase.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport io.grpc.Status\nimport io.grpc.StatusRuntimeException\nimport kotlinx.coroutines.runBlocking\nimport org.junit.Rule\nimport org.junit.Test\nimport org.junit.rules.ExpectedException\n\nabstract class StatusExceptionTestBase : GrpcTestBase() {\n\n    @Rule\n    @JvmField\n    val expect = ExpectedException.none()\n\n    abstract val service: GreeterImplBase\n\n    @Test\n    fun unaryStatus() {\n        val stub = startServer(service)\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"NOT_FOUND: uni\")\n\n        runBlocking {\n            stub.greet(req(\"joe\"))\n        }\n    }\n\n    @Test\n    fun serverStreamingStatus() {\n        val stub = startServer(service)\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"NOT_FOUND: sstream\")\n\n        runBlocking {\n            stub.greetServerStream(req(\"joe\")).receive()\n        }\n    }\n\n    @Test\n    fun clientStreamingStatus() {\n        val stub = startServer(service)\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"NOT_FOUND: cstream\")\n\n        runBlocking {\n            stub.greetClientStream().await()\n        }\n    }\n\n    @Test\n    fun bidirectionalStatus() {\n        val stub = startServer(service)\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"NOT_FOUND: bidi\")\n\n        runBlocking {\n            stub.greetBidirectional().receive()\n        }\n    }\n\n    protected fun notFound(description: String): StatusRuntimeException {\n        return Status.NOT_FOUND.withDescription(description).asRuntimeException()\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ThrowingStatusExceptionTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.channels.ReceiveChannel\nimport kotlinx.coroutines.channels.produce\n\nclass ThrowingStatusExceptionTest : StatusExceptionTestBase() {\n\n    override val service: GreeterImplBase\n        get() = StatusThrowingGreeter()\n\n    @UseExperimental(ExperimentalCoroutinesApi::class)\n    private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {\n\n        override suspend fun greet(request: GreetRequest): GreetReply {\n            throw notFound(\"uni\")\n        }\n\n        override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {\n            throw notFound(\"sstream\")\n        }\n\n        override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {\n            throw notFound(\"cstream\")\n        }\n\n        override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {\n            throw notFound(\"bidi\")\n        }\n    }\n}\n"
  },
  {
    "path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/UnimplementedStatusTest.kt",
    "content": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * -/-/-\n */\n\npackage io.rouz.greeter\n\nimport io.grpc.StatusRuntimeException\nimport kotlinx.coroutines.runBlocking\nimport org.junit.Rule\nimport org.junit.Test\nimport org.junit.rules.ExpectedException\n\nclass UnimplementedStatusTest : GrpcTestBase() {\n\n    @Rule\n    @JvmField\n    val expect = ExpectedException.none()\n\n    @Test\n    fun unaryUnimplemented() {\n        val stub = startServer(UnimplementedGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNIMPLEMENTED: Method io.rouz.greeter.Greeter/Greet is unimplemented\")\n\n        runBlocking {\n            stub.greet(req(\"anyone there?\"))\n        }\n    }\n\n    @Test\n    fun clientStreamingUnimplemented() {\n        val stub = startServer(UnimplementedGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNIMPLEMENTED: Method io.rouz.greeter.Greeter/GreetClientStream is unimplemented\")\n\n        runBlocking {\n            stub.greetClientStream().await()\n        }\n    }\n\n    @Test\n    fun serverStreamingUnimplemented() {\n        val stub = startServer(UnimplementedGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNIMPLEMENTED: Method io.rouz.greeter.Greeter/GreetServerStream is unimplemented\")\n\n        runBlocking {\n            stub.greetServerStream(req(\"anyone there?\")).receive()\n        }\n    }\n\n    @Test\n    fun bidirectionalUnimplemented() {\n        val stub = startServer(UnimplementedGreeter())\n\n        expect.expect(StatusRuntimeException::class.java)\n        expect.expectMessage(\"UNIMPLEMENTED: Method io.rouz.greeter.Greeter/GreetBidirectional is unimplemented\")\n\n        runBlocking {\n            stub.greetBidirectional().receive()\n        }\n    }\n\n    inner class UnimplementedGreeter : GreeterImplBase(collectExceptions)\n}\n"
  },
  {
    "path": "mvnw",
    "content": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# ----------------------------------------------------------------------------\n\n# ----------------------------------------------------------------------------\n# Maven2 Start Up Batch script\n#\n# Required ENV vars:\n# ------------------\n#   JAVA_HOME - location of a JDK home dir\n#\n# Optional ENV vars\n# -----------------\n#   M2_HOME - location of maven2's installed home dir\n#   MAVEN_OPTS - parameters passed to the Java VM when running Maven\n#     e.g. to debug Maven itself, use\n#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000\n#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files\n# ----------------------------------------------------------------------------\n\nif [ -z \"$MAVEN_SKIP_RC\" ] ; then\n\n  if [ -f /etc/mavenrc ] ; then\n    . /etc/mavenrc\n  fi\n\n  if [ -f \"$HOME/.mavenrc\" ] ; then\n    . \"$HOME/.mavenrc\"\n  fi\n\nfi\n\n# OS specific support.  $var _must_ be set to either true or false.\ncygwin=false;\ndarwin=false;\nmingw=false\ncase \"`uname`\" in\n  CYGWIN*) cygwin=true ;;\n  MINGW*) mingw=true;;\n  Darwin*) darwin=true\n    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home\n    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html\n    if [ -z \"$JAVA_HOME\" ]; then\n      if [ -x \"/usr/libexec/java_home\" ]; then\n        export JAVA_HOME=\"`/usr/libexec/java_home`\"\n      else\n        export JAVA_HOME=\"/Library/Java/Home\"\n      fi\n    fi\n    ;;\nesac\n\nif [ -z \"$JAVA_HOME\" ] ; then\n  if [ -r /etc/gentoo-release ] ; then\n    JAVA_HOME=`java-config --jre-home`\n  fi\nfi\n\nif [ -z \"$M2_HOME\" ] ; then\n  ## resolve links - $0 may be a link to maven's home\n  PRG=\"$0\"\n\n  # need this for relative symlinks\n  while [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n      PRG=\"$link\"\n    else\n      PRG=\"`dirname \"$PRG\"`/$link\"\n    fi\n  done\n\n  saveddir=`pwd`\n\n  M2_HOME=`dirname \"$PRG\"`/..\n\n  # make it fully qualified\n  M2_HOME=`cd \"$M2_HOME\" && pwd`\n\n  cd \"$saveddir\"\n  # echo Using m2 at $M2_HOME\nfi\n\n# For Cygwin, ensure paths are in UNIX format before anything is touched\nif $cygwin ; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=`cygpath --unix \"$M2_HOME\"`\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=`cygpath --unix \"$JAVA_HOME\"`\n  [ -n \"$CLASSPATH\" ] &&\n    CLASSPATH=`cygpath --path --unix \"$CLASSPATH\"`\nfi\n\n# For Mingw, ensure paths are in UNIX format before anything is touched\nif $mingw ; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=\"`(cd \"$M2_HOME\"; pwd)`\"\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=\"`(cd \"$JAVA_HOME\"; pwd)`\"\n  # TODO classpath?\nfi\n\nif [ -z \"$JAVA_HOME\" ]; then\n  javaExecutable=\"`which javac`\"\n  if [ -n \"$javaExecutable\" ] && ! [ \"`expr \\\"$javaExecutable\\\" : '\\([^ ]*\\)'`\" = \"no\" ]; then\n    # readlink(1) is not available as standard on Solaris 10.\n    readLink=`which readlink`\n    if [ ! `expr \"$readLink\" : '\\([^ ]*\\)'` = \"no\" ]; then\n      if $darwin ; then\n        javaHome=\"`dirname \\\"$javaExecutable\\\"`\"\n        javaExecutable=\"`cd \\\"$javaHome\\\" && pwd -P`/javac\"\n      else\n        javaExecutable=\"`readlink -f \\\"$javaExecutable\\\"`\"\n      fi\n      javaHome=\"`dirname \\\"$javaExecutable\\\"`\"\n      javaHome=`expr \"$javaHome\" : '\\(.*\\)/bin'`\n      JAVA_HOME=\"$javaHome\"\n      export JAVA_HOME\n    fi\n  fi\nfi\n\nif [ -z \"$JAVACMD\" ] ; then\n  if [ -n \"$JAVA_HOME\"  ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n      # IBM's JDK on AIX uses strange locations for the executables\n      JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n      JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n  else\n    JAVACMD=\"`which java`\"\n  fi\nfi\n\nif [ ! -x \"$JAVACMD\" ] ; then\n  echo \"Error: JAVA_HOME is not defined correctly.\" >&2\n  echo \"  We cannot execute $JAVACMD\" >&2\n  exit 1\nfi\n\nif [ -z \"$JAVA_HOME\" ] ; then\n  echo \"Warning: JAVA_HOME environment variable is not set.\"\nfi\n\nCLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher\n\n# traverses directory structure from process work directory to filesystem root\n# first directory with .mvn subdirectory is considered project base directory\nfind_maven_basedir() {\n\n  if [ -z \"$1\" ]\n  then\n    echo \"Path not specified to find_maven_basedir\"\n    return 1\n  fi\n\n  basedir=\"$1\"\n  wdir=\"$1\"\n  while [ \"$wdir\" != '/' ] ; do\n    if [ -d \"$wdir\"/.mvn ] ; then\n      basedir=$wdir\n      break\n    fi\n    # workaround for JBEAP-8937 (on Solaris 10/Sparc)\n    if [ -d \"${wdir}\" ]; then\n      wdir=`cd \"$wdir/..\"; pwd`\n    fi\n    # end of workaround\n  done\n  echo \"${basedir}\"\n}\n\n# concatenates all lines of a file\nconcat_lines() {\n  if [ -f \"$1\" ]; then\n    echo \"$(tr -s '\\n' ' ' < \"$1\")\"\n  fi\n}\n\nBASE_DIR=`find_maven_basedir \"$(pwd)\"`\nif [ -z \"$BASE_DIR\" ]; then\n  exit 1;\nfi\n\n##########################################################################################\n# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central\n# This allows using the maven wrapper in projects that prohibit checking in binary data.\n##########################################################################################\nif [ -r \"$BASE_DIR/.mvn/wrapper/maven-wrapper.jar\" ]; then\n    if [ \"$MVNW_VERBOSE\" = true ]; then\n      echo \"Found .mvn/wrapper/maven-wrapper.jar\"\n    fi\nelse\n    if [ \"$MVNW_VERBOSE\" = true ]; then\n      echo \"Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ...\"\n    fi\n    jarUrl=\"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar\"\n    while IFS=\"=\" read key value; do\n      case \"$key\" in (wrapperUrl) jarUrl=\"$value\"; break ;;\n      esac\n    done < \"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties\"\n    if [ \"$MVNW_VERBOSE\" = true ]; then\n      echo \"Downloading from: $jarUrl\"\n    fi\n    wrapperJarPath=\"$BASE_DIR/.mvn/wrapper/maven-wrapper.jar\"\n\n    if command -v wget > /dev/null; then\n        if [ \"$MVNW_VERBOSE\" = true ]; then\n          echo \"Found wget ... using wget\"\n        fi\n        wget \"$jarUrl\" -O \"$wrapperJarPath\"\n    elif command -v curl > /dev/null; then\n        if [ \"$MVNW_VERBOSE\" = true ]; then\n          echo \"Found curl ... using curl\"\n        fi\n        curl -o \"$wrapperJarPath\" \"$jarUrl\"\n    else\n        if [ \"$MVNW_VERBOSE\" = true ]; then\n          echo \"Falling back to using Java to download\"\n        fi\n        javaClass=\"$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java\"\n        if [ -e \"$javaClass\" ]; then\n            if [ ! -e \"$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class\" ]; then\n                if [ \"$MVNW_VERBOSE\" = true ]; then\n                  echo \" - Compiling MavenWrapperDownloader.java ...\"\n                fi\n                # Compiling the Java class\n                (\"$JAVA_HOME/bin/javac\" \"$javaClass\")\n            fi\n            if [ -e \"$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class\" ]; then\n                # Running the downloader\n                if [ \"$MVNW_VERBOSE\" = true ]; then\n                  echo \" - Running MavenWrapperDownloader.java ...\"\n                fi\n                (\"$JAVA_HOME/bin/java\" -cp .mvn/wrapper MavenWrapperDownloader \"$MAVEN_PROJECTBASEDIR\")\n            fi\n        fi\n    fi\nfi\n##########################################################################################\n# End of extension\n##########################################################################################\n\nexport MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-\"$BASE_DIR\"}\nif [ \"$MVNW_VERBOSE\" = true ]; then\n  echo $MAVEN_PROJECTBASEDIR\nfi\nMAVEN_OPTS=\"$(concat_lines \"$MAVEN_PROJECTBASEDIR/.mvn/jvm.config\") $MAVEN_OPTS\"\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=`cygpath --path --windows \"$M2_HOME\"`\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=`cygpath --path --windows \"$JAVA_HOME\"`\n  [ -n \"$CLASSPATH\" ] &&\n    CLASSPATH=`cygpath --path --windows \"$CLASSPATH\"`\n  [ -n \"$MAVEN_PROJECTBASEDIR\" ] &&\n    MAVEN_PROJECTBASEDIR=`cygpath --path --windows \"$MAVEN_PROJECTBASEDIR\"`\nfi\n\nWRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain\n\nexec \"$JAVACMD\" \\\n  $MAVEN_OPTS \\\n  -classpath \"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar\" \\\n  \"-Dmaven.home=${M2_HOME}\" \"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}\" \\\n  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG \"$@\"\n"
  },
  {
    "path": "mvnw.cmd",
    "content": "@REM ----------------------------------------------------------------------------\r\n@REM Licensed to the Apache Software Foundation (ASF) under one\r\n@REM or more contributor license agreements.  See the NOTICE file\r\n@REM distributed with this work for additional information\r\n@REM regarding copyright ownership.  The ASF licenses this file\r\n@REM to you under the Apache License, Version 2.0 (the\r\n@REM \"License\"); you may not use this file except in compliance\r\n@REM with the License.  You may obtain a copy of the License at\r\n@REM\r\n@REM    http://www.apache.org/licenses/LICENSE-2.0\r\n@REM\r\n@REM Unless required by applicable law or agreed to in writing,\r\n@REM software distributed under the License is distributed on an\r\n@REM \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n@REM KIND, either express or implied.  See the License for the\r\n@REM specific language governing permissions and limitations\r\n@REM under the License.\r\n@REM ----------------------------------------------------------------------------\r\n\r\n@REM ----------------------------------------------------------------------------\r\n@REM Maven2 Start Up Batch script\r\n@REM\r\n@REM Required ENV vars:\r\n@REM JAVA_HOME - location of a JDK home dir\r\n@REM\r\n@REM Optional ENV vars\r\n@REM M2_HOME - location of maven2's installed home dir\r\n@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands\r\n@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending\r\n@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven\r\n@REM     e.g. to debug Maven itself, use\r\n@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000\r\n@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files\r\n@REM ----------------------------------------------------------------------------\r\n\r\n@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'\r\n@echo off\r\n@REM set title of command window\r\ntitle %0\r\n@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'\r\n@if \"%MAVEN_BATCH_ECHO%\" == \"on\"  echo %MAVEN_BATCH_ECHO%\r\n\r\n@REM set %HOME% to equivalent of $HOME\r\nif \"%HOME%\" == \"\" (set \"HOME=%HOMEDRIVE%%HOMEPATH%\")\r\n\r\n@REM Execute a user defined script before this one\r\nif not \"%MAVEN_SKIP_RC%\" == \"\" goto skipRcPre\r\n@REM check for pre script, once with legacy .bat ending and once with .cmd ending\r\nif exist \"%HOME%\\mavenrc_pre.bat\" call \"%HOME%\\mavenrc_pre.bat\"\r\nif exist \"%HOME%\\mavenrc_pre.cmd\" call \"%HOME%\\mavenrc_pre.cmd\"\r\n:skipRcPre\r\n\r\n@setlocal\r\n\r\nset ERROR_CODE=0\r\n\r\n@REM To isolate internal variables from possible post scripts, we use another setlocal\r\n@setlocal\r\n\r\n@REM ==== START VALIDATION ====\r\nif not \"%JAVA_HOME%\" == \"\" goto OkJHome\r\n\r\necho.\r\necho Error: JAVA_HOME not found in your environment. >&2\r\necho Please set the JAVA_HOME variable in your environment to match the >&2\r\necho location of your Java installation. >&2\r\necho.\r\ngoto error\r\n\r\n:OkJHome\r\nif exist \"%JAVA_HOME%\\bin\\java.exe\" goto init\r\n\r\necho.\r\necho Error: JAVA_HOME is set to an invalid directory. >&2\r\necho JAVA_HOME = \"%JAVA_HOME%\" >&2\r\necho Please set the JAVA_HOME variable in your environment to match the >&2\r\necho location of your Java installation. >&2\r\necho.\r\ngoto error\r\n\r\n@REM ==== END VALIDATION ====\r\n\r\n:init\r\n\r\n@REM Find the project base dir, i.e. the directory that contains the folder \".mvn\".\r\n@REM Fallback to current working directory if not found.\r\n\r\nset MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%\r\nIF NOT \"%MAVEN_PROJECTBASEDIR%\"==\"\" goto endDetectBaseDir\r\n\r\nset EXEC_DIR=%CD%\r\nset WDIR=%EXEC_DIR%\r\n:findBaseDir\r\nIF EXIST \"%WDIR%\"\\.mvn goto baseDirFound\r\ncd ..\r\nIF \"%WDIR%\"==\"%CD%\" goto baseDirNotFound\r\nset WDIR=%CD%\r\ngoto findBaseDir\r\n\r\n:baseDirFound\r\nset MAVEN_PROJECTBASEDIR=%WDIR%\r\ncd \"%EXEC_DIR%\"\r\ngoto endDetectBaseDir\r\n\r\n:baseDirNotFound\r\nset MAVEN_PROJECTBASEDIR=%EXEC_DIR%\r\ncd \"%EXEC_DIR%\"\r\n\r\n:endDetectBaseDir\r\n\r\nIF NOT EXIST \"%MAVEN_PROJECTBASEDIR%\\.mvn\\jvm.config\" goto endReadAdditionalConfig\r\n\r\n@setlocal EnableExtensions EnableDelayedExpansion\r\nfor /F \"usebackq delims=\" %%a in (\"%MAVEN_PROJECTBASEDIR%\\.mvn\\jvm.config\") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a\r\n@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%\r\n\r\n:endReadAdditionalConfig\r\n\r\nSET MAVEN_JAVA_EXE=\"%JAVA_HOME%\\bin\\java.exe\"\r\nset WRAPPER_JAR=\"%MAVEN_PROJECTBASEDIR%\\.mvn\\wrapper\\maven-wrapper.jar\"\r\nset WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain\r\n\r\nset DOWNLOAD_URL=\"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar\"\r\nFOR /F \"tokens=1,2 delims==\" %%A IN (%MAVEN_PROJECTBASEDIR%\\.mvn\\wrapper\\maven-wrapper.properties) DO (\r\n\tIF \"%%A\"==\"wrapperUrl\" SET DOWNLOAD_URL=%%B \r\n)\r\n\r\n@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central\r\n@REM This allows using the maven wrapper in projects that prohibit checking in binary data.\r\nif exist %WRAPPER_JAR% (\r\n    echo Found %WRAPPER_JAR%\r\n) else (\r\n    echo Couldn't find %WRAPPER_JAR%, downloading it ...\r\n\techo Downloading from: %DOWNLOAD_URL%\r\n    powershell -Command \"(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')\"\r\n    echo Finished downloading %WRAPPER_JAR%\r\n)\r\n@REM End of extension\r\n\r\n%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% \"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%\" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*\r\nif ERRORLEVEL 1 goto error\r\ngoto end\r\n\r\n:error\r\nset ERROR_CODE=1\r\n\r\n:end\r\n@endlocal & set ERROR_CODE=%ERROR_CODE%\r\n\r\nif not \"%MAVEN_SKIP_RC%\" == \"\" goto skipRcPost\r\n@REM check for post script, once with legacy .bat ending and once with .cmd ending\r\nif exist \"%HOME%\\mavenrc_post.bat\" call \"%HOME%\\mavenrc_post.bat\"\r\nif exist \"%HOME%\\mavenrc_post.cmd\" call \"%HOME%\\mavenrc_post.cmd\"\r\n:skipRcPost\r\n\r\n@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'\r\nif \"%MAVEN_BATCH_PAUSE%\" == \"on\" pause\r\n\r\nif \"%MAVEN_TERMINATE_CMD%\" == \"on\" exit %ERROR_CODE%\r\n\r\nexit /B %ERROR_CODE%\r\n"
  },
  {
    "path": "pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <parent>\n        <groupId>io.rouz</groupId>\n        <artifactId>root</artifactId>\n        <version>2</version>\n    </parent>\n\n    <artifactId>grpc-kotlin-parent</artifactId>\n    <version>0.1.5-SNAPSHOT</version>\n    <packaging>pom</packaging>\n\n    <name>grpc-kotlin</name>\n    <url>https://github.com/rouzwawi/grpc-kotlin</url>\n\n    <licenses>\n        <license>\n            <name>The Apache Software License, Version 2.0</name>\n            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n            <distribution>repo</distribution>\n        </license>\n    </licenses>\n\n    <developers>\n        <developer>\n            <id>rouz</id>\n            <email>me@rouz.io</email>\n            <name>Rouzbeh Delavari</name>\n        </developer>\n    </developers>\n\n    <scm>\n        <url>https://github.com/rouzwawi/grpc-kotlin</url>\n        <connection>scm:git:git@github.com:rouzwawi/grpc-kotlin.git</connection>\n        <developerConnection>scm:git:git@github.com:rouzwawi/grpc-kotlin.git</developerConnection>\n        <tag>HEAD</tag>\n    </scm>\n\n    <properties>\n    </properties>\n\n    <modules>\n        <module>grpc-kotlin-gen</module>\n        <module>grpc-kotlin-test</module>\n        <module>grpc-kotlin-example-chatserver</module>\n    </modules>\n\n    <dependencies>\n        <!-- scope : compile -->\n\n        <!-- scope : test -->\n        <dependency>\n            <groupId>junit</groupId>\n            <artifactId>junit</artifactId>\n            <version>4.12</version>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <artifactId>maven-enforcer-plugin</artifactId>\n            </plugin>\n            <plugin>\n                <artifactId>maven-failsafe-plugin</artifactId>\n            </plugin>\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-jar-plugin</artifactId>\n                <version>3.1.0</version>\n            </plugin>\n            <plugin>\n                <artifactId>maven-surefire-plugin</artifactId>\n                <configuration>\n                    <forkCount>0</forkCount>\n                </configuration>\n            </plugin>\n        </plugins>\n    </build>\n</project>\n"
  }
]