From c58f88392a9d5d221d89676e8fd76e711181d941 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 23 Jan 2015 15:26:48 -0800 Subject: [PATCH 001/576] Initial README.md --- README.md | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000000..8b7bca010f7 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# gRPC Helloworld Tutorial + +A great way to get introduced to gRPC is to work through this tutorial, which +walks you through the construction of simple client and server that introduces +various features of gRPC. + +When you finish the tutorial, you will be able to + +- Create an protobuf schema that defines a simple RPC service +- Create a Java server that implements the schema interface +- Create a Java client that accesses the server +- Create a Go client that accesses the Java server +- Update the service with advanced features like RPC streaming + +# Get Started + +The rest of this page explains how you can set up your local machine for development. +If you just want to read the tutorial, you can go straight to the next step: [Step - 0](Step_0.md) + +# Working with the code + +You can follow along with this tutorial and hack on the code in the comfort of +your own computer. In this way you can get hands-on practice of really writing +gRPC code. + +The tutorial relies on the use of the Git versioning system for source code +management. You don't need to know anything about Git to follow the tutorial +other than how to install and run a few git commands. + +# Install Git + +You can download and install Git from http://git-scm.com/download. Once +installed you should have access to the git command line tool. The main +commands that you will need to use are: + +- git clone ... : clone a remote repository onto your local machine +- git checkout ... : check out a particular branch or a tagged version of the code to hack on + +# Download grpc-helloworld + +Clone the grpc-helloword repository located at GitHub by running the following command: + +``` +git clone https://github.com/google/grpc-helloworld.git +``` + +Change your current directory to grpc-helloworld + +``` +cd grpc-helloworld +``` + +# Install Java 8 + +Java gRPC works on both Java 7 and Java 8. To keep this example simple, will +assume that you've installed Java 8. Instructions for +[installing Java 8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) +are available online. + +# Install Go 1.4 + +Go gRPC requires Go 1.4. It's available for [download](https://golang.org/dl/) and install online. + +# (optional) Install protoc + +gRPC uses the latest version of the protocol buffer compiler, protoc. + +For following this tutorial, the protoc is not strictly necessary, as all the +generated code is checked into the Git repository. If you want to experiment +with generating the code yourself, download and install protoc from its +[Git repo](https://github.com/google/protobuf) From 8536e0767e936895c2f38c5d77d582621bafd22a Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 23 Jan 2015 17:12:39 -0800 Subject: [PATCH 002/576] Step-0: define a service --- Step_0.md | 40 ++++++++++++++++++++++++++++++++++++++++ helloworld.proto | 20 ++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 Step_0.md create mode 100644 helloworld.proto diff --git a/Step_0.md b/Step_0.md new file mode 100644 index 00000000000..695fb1a4323 --- /dev/null +++ b/Step_0.md @@ -0,0 +1,40 @@ +# Step-0: define a service + +This section presents an example of a very simple service definition that +receives a message from a remote client. The messages contains the users's +name and sends's back a greeting for that person. + +Here it is in full; to be used to generate gRPC code it's defined in it's own +file [helloworld.proto](helloworld.proto). + +``` +syntax = "proto3"; + +package helloworld; + +// The request message containing the user's name. +message HelloRequest { + optional string name = 1; +} + +// The response message containing the greetings +message HelloReply { + optional string message = 1; +} + +// The greeting service definition. +service Greeting { + + // Sends a greeting + rpc hello (HelloRequest) returns (HelloReply) { + } +} + +``` + +The service stanza of the messages is an example of protobuf service IDL +(Interface Defintion Language). Here, it defines a very simple service that +receives a request and returns a response. + +Next in [Step-1](Step-1.md), we'll use protoc to generate code this simple +definition. diff --git a/helloworld.proto b/helloworld.proto new file mode 100644 index 00000000000..a7f5bfbb4d1 --- /dev/null +++ b/helloworld.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +package helloworld; + +// The request message containing the user's name. +message HelloRequest { + optional string name = 1; +} + +// The response message containing the greetings +message HelloReply { + optional string message = 1; +} + +// The greeting service definition. +service Greeting { + // Sends a greeting + rpc hello (HelloRequest) returns (HelloReply) { + } +} From 5c72361ee17583a4de5d5e4a482e0b74c06acb0c Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 23 Jan 2015 17:15:03 -0800 Subject: [PATCH 003/576] Step-0: define a service --- Step_0.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Step_0.md b/Step_0.md index 695fb1a4323..2e5483c028e 100644 --- a/Step_0.md +++ b/Step_0.md @@ -1,8 +1,8 @@ # Step-0: define a service This section presents an example of a very simple service definition that -receives a message from a remote client. The messages contains the users's -name and sends's back a greeting for that person. +receives a message from a remote client. The message contains the users's +name and sends back a greeting to that person. Here it is in full; to be used to generate gRPC code it's defined in it's own file [helloworld.proto](helloworld.proto). From 33208208fe4f9dde7c2dff2e2db9ce66d7537b60 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 23 Jan 2015 18:25:27 -0800 Subject: [PATCH 004/576] Step-0: define a service --- Step_0.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/Step_0.md b/Step_0.md index 2e5483c028e..3fec8376d1a 100644 --- a/Step_0.md +++ b/Step_0.md @@ -1,11 +1,11 @@ # Step-0: define a service -This section presents an example of a very simple service definition that -receives a message from a remote client. The message contains the users's -name and sends back a greeting to that person. +This section presents an example of a simple service definition that receives +a message from a remote client. The message contains the users's name and +sends back a greeting to that person. -Here it is in full; to be used to generate gRPC code it's defined in it's own -file [helloworld.proto](helloworld.proto). +It's shown below in full; it's actually contained in separate file +[helloworld.proto](helloworld.proto). ``` syntax = "proto3"; @@ -32,9 +32,10 @@ service Greeting { ``` -The service stanza of the messages is an example of protobuf service IDL -(Interface Defintion Language). Here, it defines a very simple service that -receives a request and returns a response. +The service stanza of the message is an example of protobuf service IDL +(Interface Defintion Language). Here, it defines a simple service that +receives a request containing a name and returns a response containing a +message. -Next in [Step-1](Step-1.md), we'll use protoc to generate code this simple -definition. +Next, in [Step-1](Step-1.md), we'll use protoc to generate client code from +this IDL. From 448d4fcfb9126a032536ff377dc1dcc5a04ee9db Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 09:52:57 -0800 Subject: [PATCH 005/576] Updates the README.md to make maven a prequisite --- README.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8b7bca010f7..a5406ae2171 100644 --- a/README.md +++ b/README.md @@ -52,14 +52,22 @@ cd grpc-helloworld # Install Java 8 -Java gRPC works on both Java 7 and Java 8. To keep this example simple, will -assume that you've installed Java 8. Instructions for -[installing Java 8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) -are available online. +Java gRPC is designed to work with both Java 7 and Java 8. For simplicity, +the example assumes that Java 8 is installed. See +[Install Java 8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) +for instructions. + +# Install Maven + +To simplify building and the managing of gRPC's dependencies, the java client +are server are structured as a standard [Maven](http://maven.apache.org/guides/getting-started/) +project. See [Install Maven](http://maven.apache.org/users/index.html) for instructions. + # Install Go 1.4 -Go gRPC requires Go 1.4. It's available for [download](https://golang.org/dl/) and install online. +Go gRPC requires Go 1.4, the latest version of Go. See +[Install Go](https://golang.org/doc/install) for instructions. # (optional) Install protoc From fb52c2abafd7b6202f781472c6841e2ccb8b2028 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 09:53:43 -0800 Subject: [PATCH 006/576] Moves the proto to the location within the maven repo --- helloworld.proto => src/main/proto/helloworld.proto | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename helloworld.proto => src/main/proto/helloworld.proto (87%) diff --git a/helloworld.proto b/src/main/proto/helloworld.proto similarity index 87% rename from helloworld.proto rename to src/main/proto/helloworld.proto index a7f5bfbb4d1..da5c3a1d85d 100644 --- a/helloworld.proto +++ b/src/main/proto/helloworld.proto @@ -1,5 +1,7 @@ syntax = "proto3"; +option java_package = "ex.grpc"; + package helloworld; // The request message containing the user's name. @@ -13,7 +15,7 @@ message HelloReply { } // The greeting service definition. -service Greeting { +service Greetings { // Sends a greeting rpc hello (HelloRequest) returns (HelloReply) { } From fc216a9b56b4735c626420717f44dfed07293cd0 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 09:54:11 -0800 Subject: [PATCH 007/576] Adds .gitignore to ignore maven generated files --- .gitignore | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..1a49c132b53 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +*~ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties \ No newline at end of file From d0eb1f903775264fe6dcb83e69a53d0eedbd8f54 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 09:54:31 -0800 Subject: [PATCH 008/576] Adds the maven project file --- pom.xml | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 pom.xml diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000000..da0ee205f77 --- /dev/null +++ b/pom.xml @@ -0,0 +1,105 @@ + + 4.0.0 + + + com.google.net.stubby + stubby-parent + 0.1.0-SNAPSHOT + + + grpc-hello-world + jar + + Hello gRPC World + + + + ${project.groupId} + stubby-core + ${project.version} + + + ${project.groupId} + stubby-netty + ${project.version} + + + ${project.groupId} + stubby-okhttp + ${project.version} + + + ${project.groupId} + stubby-stub + ${project.version} + + + ${project.groupId} + stubby-testing + ${project.version} + + + junit + junit + compile + + + org.mockito + mockito-core + compile + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + assemble-all + package + + single + + + + + + jar-with-dependencies + + + + + + com.internetitem + write-properties-file-maven-plugin + + + bootclasspath + prepare-package + + write-properties-file + + + bootclasspath.properties + ${project.build.directory} + + + bootclasspath + ${argLine.bootcp} + + + jar + ${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar + + + + + + + + + From 783a8613d54eba8f4bfe907a7a863336eee6b2cd Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 09:58:49 -0800 Subject: [PATCH 009/576] Adds: Step_1 - generate the service client --- Step_1.md | 33 + src/main/java/ex/grpc/GreetingsGrpc.java | 172 ++++ src/main/java/ex/grpc/Helloworld.java | 951 +++++++++++++++++++++++ 3 files changed, 1156 insertions(+) create mode 100644 Step_1.md create mode 100644 src/main/java/ex/grpc/GreetingsGrpc.java create mode 100644 src/main/java/ex/grpc/Helloworld.java diff --git a/Step_1.md b/Step_1.md new file mode 100644 index 00000000000..4ac68aba5df --- /dev/null +++ b/Step_1.md @@ -0,0 +1,33 @@ +# Step-1: Generate a service client. + +In this step, we use protoc to generate the java Stub classes. A Stub is the +name gRPC uses for the code that initiates contact with a gRPC service running +remotely via the internet. + +If you did not install protoc on your system, you can skip this step and move +onto the next one where we examine the generated code. + +First, you'll need to build the protobuf plugin that generates the rpc +classes. `protoc` uses other tools called plugins to add additional features +to generated code. + +The grpc Java Stub classes are created using a grpc java plugin, but first the +plugin must be built and installed. + +To build the plugin: +``` +$ pushd external/grpc_java +$ make java_plugin +$ popd +``` + +To use it to generate the code: +``` +$ mkdir -p src/main/java +$ protoc -I . helloworld.proto --plugin=protoc-gen-grpc=external/grpc_java/bins/opt/java_plugin \ + --grpc_out=src/main/java \ + --java_out=src/main/java +``` + +Next, in [Step-2](Step-2.md), we'll use the generated Stub implementation to +write a client that uses the generated code to make a call to a service. diff --git a/src/main/java/ex/grpc/GreetingsGrpc.java b/src/main/java/ex/grpc/GreetingsGrpc.java new file mode 100644 index 00000000000..97c2f00a1e0 --- /dev/null +++ b/src/main/java/ex/grpc/GreetingsGrpc.java @@ -0,0 +1,172 @@ +package ex.grpc; + +import static com.google.net.stubby.stub.Calls.createMethodDescriptor; +import static com.google.net.stubby.stub.Calls.asyncUnaryCall; +import static com.google.net.stubby.stub.Calls.asyncServerStreamingCall; +import static com.google.net.stubby.stub.Calls.asyncClientStreamingCall; +import static com.google.net.stubby.stub.Calls.duplexStreamingCall; +import static com.google.net.stubby.stub.Calls.blockingUnaryCall; +import static com.google.net.stubby.stub.Calls.blockingServerStreamingCall; +import static com.google.net.stubby.stub.Calls.unaryFutureCall; +import static com.google.net.stubby.stub.ServerCalls.createMethodDefinition; +import static com.google.net.stubby.stub.ServerCalls.asyncUnaryRequestCall; +import static com.google.net.stubby.stub.ServerCalls.asyncStreamingRequestCall; + +@javax.annotation.Generated("by gRPC proto compiler") +public class GreetingsGrpc { + + private static final com.google.net.stubby.stub.Method METHOD_HELLO = + com.google.net.stubby.stub.Method.create( + com.google.net.stubby.MethodType.UNARY, "hello", + com.google.net.stubby.proto.ProtoUtils.marshaller(ex.grpc.Helloworld.HelloRequest.PARSER), + com.google.net.stubby.proto.ProtoUtils.marshaller(ex.grpc.Helloworld.HelloReply.PARSER)); + + public static GreetingsStub newStub(com.google.net.stubby.Channel channel) { + return new GreetingsStub(channel, CONFIG); + } + + public static GreetingsBlockingStub newBlockingStub( + com.google.net.stubby.Channel channel) { + return new GreetingsBlockingStub(channel, CONFIG); + } + + public static GreetingsFutureStub newFutureStub( + com.google.net.stubby.Channel channel) { + return new GreetingsFutureStub(channel, CONFIG); + } + + public static final GreetingsServiceDescriptor CONFIG = + new GreetingsServiceDescriptor(); + + @javax.annotation.concurrent.Immutable + public static class GreetingsServiceDescriptor extends + com.google.net.stubby.stub.AbstractServiceDescriptor { + public final com.google.net.stubby.MethodDescriptor hello; + + private GreetingsServiceDescriptor() { + hello = createMethodDescriptor( + "helloworld.Greetings", METHOD_HELLO); + } + + private GreetingsServiceDescriptor( + java.util.Map> methodMap) { + hello = (com.google.net.stubby.MethodDescriptor) methodMap.get( + CONFIG.hello.getName()); + } + + @java.lang.Override + protected GreetingsServiceDescriptor build( + java.util.Map> methodMap) { + return new GreetingsServiceDescriptor(methodMap); + } + + @java.lang.Override + public com.google.common.collect.ImmutableList> methods() { + return com.google.common.collect.ImmutableList.>of( + hello); + } + } + + public static interface Greetings { + + public void hello(ex.grpc.Helloworld.HelloRequest request, + com.google.net.stubby.stub.StreamObserver responseObserver); + } + + public static interface GreetingsBlockingClient { + + public ex.grpc.Helloworld.HelloReply hello(ex.grpc.Helloworld.HelloRequest request); + } + + public static interface GreetingsFutureClient { + + public com.google.common.util.concurrent.ListenableFuture hello( + ex.grpc.Helloworld.HelloRequest request); + } + + public static class GreetingsStub extends + com.google.net.stubby.stub.AbstractStub + implements Greetings { + private GreetingsStub(com.google.net.stubby.Channel channel, + GreetingsServiceDescriptor config) { + super(channel, config); + } + + @java.lang.Override + protected GreetingsStub build(com.google.net.stubby.Channel channel, + GreetingsServiceDescriptor config) { + return new GreetingsStub(channel, config); + } + + @java.lang.Override + public void hello(ex.grpc.Helloworld.HelloRequest request, + com.google.net.stubby.stub.StreamObserver responseObserver) { + asyncUnaryCall( + channel.newCall(config.hello), request, responseObserver); + } + } + + public static class GreetingsBlockingStub extends + com.google.net.stubby.stub.AbstractStub + implements GreetingsBlockingClient { + private GreetingsBlockingStub(com.google.net.stubby.Channel channel, + GreetingsServiceDescriptor config) { + super(channel, config); + } + + @java.lang.Override + protected GreetingsBlockingStub build(com.google.net.stubby.Channel channel, + GreetingsServiceDescriptor config) { + return new GreetingsBlockingStub(channel, config); + } + + @java.lang.Override + public ex.grpc.Helloworld.HelloReply hello(ex.grpc.Helloworld.HelloRequest request) { + return blockingUnaryCall( + channel.newCall(config.hello), request); + } + } + + public static class GreetingsFutureStub extends + com.google.net.stubby.stub.AbstractStub + implements GreetingsFutureClient { + private GreetingsFutureStub(com.google.net.stubby.Channel channel, + GreetingsServiceDescriptor config) { + super(channel, config); + } + + @java.lang.Override + protected GreetingsFutureStub build(com.google.net.stubby.Channel channel, + GreetingsServiceDescriptor config) { + return new GreetingsFutureStub(channel, config); + } + + @java.lang.Override + public com.google.common.util.concurrent.ListenableFuture hello( + ex.grpc.Helloworld.HelloRequest request) { + return unaryFutureCall( + channel.newCall(config.hello), request); + } + } + + public static com.google.net.stubby.ServerServiceDefinition bindService( + final Greetings serviceImpl) { + return com.google.net.stubby.ServerServiceDefinition.builder("helloworld.Greetings") + .addMethod(createMethodDefinition( + METHOD_HELLO, + asyncUnaryRequestCall( + new com.google.net.stubby.stub.ServerCalls.UnaryRequestMethod< + ex.grpc.Helloworld.HelloRequest, + ex.grpc.Helloworld.HelloReply>() { + @java.lang.Override + public void invoke( + ex.grpc.Helloworld.HelloRequest request, + com.google.net.stubby.stub.StreamObserver responseObserver) { + serviceImpl.hello(request, responseObserver); + } + }))).build(); + } +} diff --git a/src/main/java/ex/grpc/Helloworld.java b/src/main/java/ex/grpc/Helloworld.java new file mode 100644 index 00000000000..f72040fa2bf --- /dev/null +++ b/src/main/java/ex/grpc/Helloworld.java @@ -0,0 +1,951 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: src/main/proto/helloworld.proto + +package ex.grpc; + +public final class Helloworld { + private Helloworld() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + } + public interface HelloRequestOrBuilder extends + // @@protoc_insertion_point(interface_extends:helloworld.HelloRequest) + com.google.protobuf.MessageOrBuilder { + + /** + * optional string name = 1; + */ + java.lang.String getName(); + /** + * optional string name = 1; + */ + com.google.protobuf.ByteString + getNameBytes(); + } + /** + * Protobuf type {@code helloworld.HelloRequest} + * + *
+   * The request message containing the user's name.
+   * 
+ */ + public static final class HelloRequest extends + com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:helloworld.HelloRequest) + HelloRequestOrBuilder { + // Use HelloRequest.newBuilder() to construct. + private HelloRequest(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + } + private HelloRequest() { + name_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); + } + private HelloRequest( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!input.skipField(tag)) { + done = true; + } + break; + } + case 10: { + com.google.protobuf.ByteString bs = input.readBytes(); + + name_ = bs; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + ex.grpc.Helloworld.HelloRequest.class, ex.grpc.Helloworld.HelloRequest.Builder.class); + } + + public static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public HelloRequest parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new HelloRequest(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public static final int NAME_FIELD_NUMBER = 1; + private java.lang.Object name_; + /** + * optional string name = 1; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } + } + /** + * optional string name = 1; + */ + public com.google.protobuf.ByteString + getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (!getNameBytes().isEmpty()) { + output.writeBytes(1, getNameBytes()); + } + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (!getNameBytes().isEmpty()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, getNameBytes()); + } + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + public static ex.grpc.Helloworld.HelloRequest parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static ex.grpc.Helloworld.HelloRequest parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloRequest parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static ex.grpc.Helloworld.HelloRequest parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloRequest parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static ex.grpc.Helloworld.HelloRequest parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloRequest parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static ex.grpc.Helloworld.HelloRequest parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloRequest parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static ex.grpc.Helloworld.HelloRequest parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return new Builder(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(ex.grpc.Helloworld.HelloRequest prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code helloworld.HelloRequest} + * + *
+     * The request message containing the user's name.
+     * 
+ */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:helloworld.HelloRequest) + ex.grpc.Helloworld.HelloRequestOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + ex.grpc.Helloworld.HelloRequest.class, ex.grpc.Helloworld.HelloRequest.Builder.class); + } + + // Construct using ex.grpc.Helloworld.HelloRequest.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + name_ = ""; + + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_descriptor; + } + + public ex.grpc.Helloworld.HelloRequest getDefaultInstanceForType() { + return ex.grpc.Helloworld.HelloRequest.getDefaultInstance(); + } + + public ex.grpc.Helloworld.HelloRequest build() { + ex.grpc.Helloworld.HelloRequest result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public ex.grpc.Helloworld.HelloRequest buildPartial() { + ex.grpc.Helloworld.HelloRequest result = new ex.grpc.Helloworld.HelloRequest(this); + result.name_ = name_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof ex.grpc.Helloworld.HelloRequest) { + return mergeFrom((ex.grpc.Helloworld.HelloRequest)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(ex.grpc.Helloworld.HelloRequest other) { + if (other == ex.grpc.Helloworld.HelloRequest.getDefaultInstance()) return this; + if (!other.getName().isEmpty()) { + name_ = other.name_; + onChanged(); + } + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + ex.grpc.Helloworld.HelloRequest parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (ex.grpc.Helloworld.HelloRequest) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private java.lang.Object name_ = ""; + /** + * optional string name = 1; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + * optional string name = 1; + */ + public com.google.protobuf.ByteString + getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * optional string name = 1; + */ + public Builder setName( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + name_ = value; + onChanged(); + return this; + } + /** + * optional string name = 1; + */ + public Builder clearName() { + + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + /** + * optional string name = 1; + */ + public Builder setNameBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + name_ = value; + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + + // @@protoc_insertion_point(builder_scope:helloworld.HelloRequest) + } + + // @@protoc_insertion_point(class_scope:helloworld.HelloRequest) + private static final ex.grpc.Helloworld.HelloRequest defaultInstance;static { + defaultInstance = new ex.grpc.Helloworld.HelloRequest(); + } + + public static ex.grpc.Helloworld.HelloRequest getDefaultInstance() { + return defaultInstance; + } + + public ex.grpc.Helloworld.HelloRequest getDefaultInstanceForType() { + return defaultInstance; + } + + } + + public interface HelloReplyOrBuilder extends + // @@protoc_insertion_point(interface_extends:helloworld.HelloReply) + com.google.protobuf.MessageOrBuilder { + + /** + * optional string message = 1; + */ + java.lang.String getMessage(); + /** + * optional string message = 1; + */ + com.google.protobuf.ByteString + getMessageBytes(); + } + /** + * Protobuf type {@code helloworld.HelloReply} + * + *
+   * The response message containing the greetings
+   * 
+ */ + public static final class HelloReply extends + com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:helloworld.HelloReply) + HelloReplyOrBuilder { + // Use HelloReply.newBuilder() to construct. + private HelloReply(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + } + private HelloReply() { + message_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); + } + private HelloReply( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!input.skipField(tag)) { + done = true; + } + break; + } + case 10: { + com.google.protobuf.ByteString bs = input.readBytes(); + + message_ = bs; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_fieldAccessorTable + .ensureFieldAccessorsInitialized( + ex.grpc.Helloworld.HelloReply.class, ex.grpc.Helloworld.HelloReply.Builder.class); + } + + public static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public HelloReply parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new HelloReply(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public static final int MESSAGE_FIELD_NUMBER = 1; + private java.lang.Object message_; + /** + * optional string message = 1; + */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + message_ = s; + } + return s; + } + } + /** + * optional string message = 1; + */ + public com.google.protobuf.ByteString + getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (!getMessageBytes().isEmpty()) { + output.writeBytes(1, getMessageBytes()); + } + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (!getMessageBytes().isEmpty()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, getMessageBytes()); + } + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + public static ex.grpc.Helloworld.HelloReply parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static ex.grpc.Helloworld.HelloReply parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloReply parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static ex.grpc.Helloworld.HelloReply parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloReply parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static ex.grpc.Helloworld.HelloReply parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloReply parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static ex.grpc.Helloworld.HelloReply parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static ex.grpc.Helloworld.HelloReply parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static ex.grpc.Helloworld.HelloReply parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return new Builder(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(ex.grpc.Helloworld.HelloReply prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code helloworld.HelloReply} + * + *
+     * The response message containing the greetings
+     * 
+ */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:helloworld.HelloReply) + ex.grpc.Helloworld.HelloReplyOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_fieldAccessorTable + .ensureFieldAccessorsInitialized( + ex.grpc.Helloworld.HelloReply.class, ex.grpc.Helloworld.HelloReply.Builder.class); + } + + // Construct using ex.grpc.Helloworld.HelloReply.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + message_ = ""; + + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_descriptor; + } + + public ex.grpc.Helloworld.HelloReply getDefaultInstanceForType() { + return ex.grpc.Helloworld.HelloReply.getDefaultInstance(); + } + + public ex.grpc.Helloworld.HelloReply build() { + ex.grpc.Helloworld.HelloReply result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public ex.grpc.Helloworld.HelloReply buildPartial() { + ex.grpc.Helloworld.HelloReply result = new ex.grpc.Helloworld.HelloReply(this); + result.message_ = message_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof ex.grpc.Helloworld.HelloReply) { + return mergeFrom((ex.grpc.Helloworld.HelloReply)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(ex.grpc.Helloworld.HelloReply other) { + if (other == ex.grpc.Helloworld.HelloReply.getDefaultInstance()) return this; + if (!other.getMessage().isEmpty()) { + message_ = other.message_; + onChanged(); + } + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + ex.grpc.Helloworld.HelloReply parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (ex.grpc.Helloworld.HelloReply) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private java.lang.Object message_ = ""; + /** + * optional string message = 1; + */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + message_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + * optional string message = 1; + */ + public com.google.protobuf.ByteString + getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * optional string message = 1; + */ + public Builder setMessage( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + message_ = value; + onChanged(); + return this; + } + /** + * optional string message = 1; + */ + public Builder clearMessage() { + + message_ = getDefaultInstance().getMessage(); + onChanged(); + return this; + } + /** + * optional string message = 1; + */ + public Builder setMessageBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + message_ = value; + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + + // @@protoc_insertion_point(builder_scope:helloworld.HelloReply) + } + + // @@protoc_insertion_point(class_scope:helloworld.HelloReply) + private static final ex.grpc.Helloworld.HelloReply defaultInstance;static { + defaultInstance = new ex.grpc.Helloworld.HelloReply(); + } + + public static ex.grpc.Helloworld.HelloReply getDefaultInstance() { + return defaultInstance; + } + + public ex.grpc.Helloworld.HelloReply getDefaultInstanceForType() { + return defaultInstance; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_helloworld_HelloRequest_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_helloworld_HelloRequest_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_helloworld_HelloReply_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_helloworld_HelloReply_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\037src/main/proto/helloworld.proto\022\nhello" + + "world\"\034\n\014HelloRequest\022\014\n\004name\030\001 \001(\t\"\035\n\nH" + + "elloReply\022\017\n\007message\030\001 \001(\t2H\n\tGreetings\022" + + ";\n\005hello\022\030.helloworld.HelloRequest\032\026.hel" + + "loworld.HelloReply\"\000B\t\n\007ex.grpcb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + internal_static_helloworld_HelloRequest_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_helloworld_HelloRequest_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_helloworld_HelloRequest_descriptor, + new java.lang.String[] { "Name", }); + internal_static_helloworld_HelloReply_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_helloworld_HelloReply_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_helloworld_HelloReply_descriptor, + new java.lang.String[] { "Message", }); + } + + // @@protoc_insertion_point(outer_class_scope) +} From 860ae5a0a27b76133e11bfad8474054d9cfbf26d Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 10:00:19 -0800 Subject: [PATCH 010/576] Adds: Step_2 - adds a command line client app --- Step_2.md | 85 ++++++++++++++++++++++ src/main/java/ex/grpc/GreetingsClient.java | 55 ++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 Step_2.md create mode 100644 src/main/java/ex/grpc/GreetingsClient.java diff --git a/Step_2.md b/Step_2.md new file mode 100644 index 00000000000..dd134a989c5 --- /dev/null +++ b/Step_2.md @@ -0,0 +1,85 @@ +# Step-2: Write a service client. + +This step uses the generated code to write a simple client to access the hello +service. The full client is in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). + + +## Configuring the service to connect to. + +The client contains uses a Stub to contact the service. The internet address +is configured in the client constructor. gRPC Channel is the abstraction over +transport handling; its constructor accepts the host name and port of the +service. The channel in turn is used to construct the Stub. + + +``` + private final ChannelImpl channel; + private final GreetingGrpc.GreetingBlockingStub blockingStub; + + public HelloClient(String host, int port) { + channel = NettyChannelBuilder.forAddress(host, port) + .negotiationType(NegotiationType.PLAINTEXT) + .build(); + blockingStub = GreetingGrpc.newBlockingStub(channel); + } + +``` + +## Obtaining a greeting + +The greet method uses the stub to contact the service and obtain a greeting. +It: +- constructs a request +- obtains a reply from the stub +- prints out the greeting + + +``` + public void greet(String name) { + logger.debug("Will try to greet " + name + " ..."); + try { + Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName(name).build(); + Helloworld.HelloReply reply = blockingStub.hello(request); + logger.info("Greeting: " + reply.getMessage()); + } catch (RuntimeException e) { + logger.log(Level.WARNING, "RPC failed", e); + return; + } + } + +``` + +## Running from the command line + +The main method puts together the example so that it can be run from a command +line. + +``` + /* Access a service running on the local machine on port 50051 */ + HelloClient client = new HelloClient("localhost", 50051); + String user = "world"; + if (args.length > 1) { + user = args[1]; + } + client.greet(user); + +``` + +It can be built as follows. + +``` +$ mvn package +``` + +It can also be run, but doing so now would end up a with a failure as there is +no server available yet. The [next step](Step-3.md), describes how to +implement, build and run a server that supports the service description. + +## Notes + +- the client uses a blocking stub. This means that the RPC call waits for the + server to respond, and will either return a response or raise an exception. + +- gRPC Java has other kinds of stubs that make non-blocking calls to the + server, where the response is returned asynchronously. Usage of these stubs + is a more advanced topic and will be described in later steps. diff --git a/src/main/java/ex/grpc/GreetingsClient.java b/src/main/java/ex/grpc/GreetingsClient.java new file mode 100644 index 00000000000..4ae2e7076bc --- /dev/null +++ b/src/main/java/ex/grpc/GreetingsClient.java @@ -0,0 +1,55 @@ +package ex.grpc; + +import com.google.net.stubby.ChannelImpl; +import com.google.net.stubby.stub.StreamObserver; +import com.google.net.stubby.transport.netty.NegotiationType; +import com.google.net.stubby.transport.netty.NettyChannelBuilder; + +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.concurrent.TimeUnit; + +public class GreetingsClient { + private final Logger logger = Logger.getLogger( + GreetingsClient.class.getName()); + private final ChannelImpl channel; + private final GreetingsGrpc.GreetingsBlockingStub blockingStub; + + public GreetingsClient(String host, int port) { + channel = NettyChannelBuilder.forAddress(host, port) + .negotiationType(NegotiationType.PLAINTEXT) + .build(); + blockingStub = GreetingsGrpc.newBlockingStub(channel); + } + + public void shutdown() throws InterruptedException { + channel.shutdown().awaitTerminated(5, TimeUnit.SECONDS); + } + + public void greet(String name) { + try { + logger.fine("Will try to greet " + name + " ..."); + Helloworld.HelloRequest req = + Helloworld.HelloRequest.newBuilder().setName(name).build(); + Helloworld.HelloReply reply = blockingStub.hello(req); + logger.info("Greeting: " + reply.getMessage()); + } catch (RuntimeException e) { + logger.log(Level.WARNING, "RPC failed", e); + return; + } + } + + public static void main(String[] args) throws Exception { + GreetingsClient client = new GreetingsClient("localhost", 50051); + try { + /* Access a service running on the local machine on port 50051 */ + String user = "world"; + if (args.length > 0) { + user = args[0]; /* Use the arg as the name to greet if provided */ + } + client.greet(user); + } finally { + client.shutdown(); + } + } +} From 7131c9798d861a91049519319dd3f93fc4f1cefe Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 10:02:04 -0800 Subject: [PATCH 011/576] Adds: Step_3 - adds a server implementation and command line app --- Step_3.md | 82 ++++++++++++++++++++++ src/main/java/ex/grpc/GreetingsImpl.java | 16 +++++ src/main/java/ex/grpc/GreetingsServer.java | 51 ++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 Step_3.md create mode 100644 src/main/java/ex/grpc/GreetingsImpl.java create mode 100644 src/main/java/ex/grpc/GreetingsServer.java diff --git a/Step_3.md b/Step_3.md new file mode 100644 index 00000000000..56d6e7cfd3a --- /dev/null +++ b/Step_3.md @@ -0,0 +1,82 @@ +# Step-3: Implement a server. + +This step extends the generated server skeleton code to write a simple server +that provides the hello service. This in introduces two new classes + +- a service implementation [GreetingsImpl.java](src/main/java/ex/grpc/GreetingsImpl.java). + +- a server that hosts the service implementation and allows to accessed over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). + +## Service implementation + +[GreetingsSImpl.java](src/main/java/ex/grpc/GreetingsImpl.java) +implements the behaviour we require of our GreetingService. There are a +number of important features of gRPC being used here: + +``` + public void hello(Helloworld.HelloRequest req, + StreamObserver responseObserver) { + Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( + "Hello " + req.getName()).build(); + responseObserver.onValue(reply); + responseObserver.onCompleted(); + } +``` + +- it provides a class `GreetingsImpl` that implements a generated interface `GreetingsGrpc.Greetings` +- `GreetingsGrpc.Greetings` declares the method `hello` that was declared in the proto [IDL](src/main/proto/helloworld.proto) +- `hello's` signature is typesafe: + hello(Helloworld.HelloRequest req, StreamObserver responseObserver) +- `hello` takes two parameters: + `Helloworld.HelloRequest`: the request + `StreamObserver`: a response observer, an interface to be called with the response value +- to complete the call + - the return value is constructed + - the responseObserver.onValue() is called with the response + - responseObserver.onCompleted() is called to indicate that no more work will done on the RPC. + + +## Server implementation + +[GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the +other main feature to required to provde gRPC service; how to allow a service +implementation to be accessed from the network. + +``` + private void start() throws Exception { + server = NettyServerBuilder.forPort(port) + .addService(GreetingsGrpc.bindService(new GreetingsImpl())) + .build(); + server.startAsync(); + server.awaitRunning(5, TimeUnit.SECONDS); + } + +``` + +- it provides a class `GreetingsServer` that holds a `ServerImpl` that will run the server +- in the `start` method, `GreetingServer` binds the `GreetingsService` implementation to a port and begins running it +- there is also a `stop` method that takes care of shutting down the service and cleaning up when the program exits + +## Build it + +This is the same as before: our client and server are part of the same maven +package so the same command builds both. + +``` +$ mvn package +``` + +## Try them out + +We've added simple shell scripts to simplifying running the examples. Now +that they are built, you can run the server with. + +``` +$ ./run_greetings_server.sh +``` + +In another termainal window and confirm that it receives a message. + +``` +$ ./run_greetings_client.sh +``` diff --git a/src/main/java/ex/grpc/GreetingsImpl.java b/src/main/java/ex/grpc/GreetingsImpl.java new file mode 100644 index 00000000000..005489acaa2 --- /dev/null +++ b/src/main/java/ex/grpc/GreetingsImpl.java @@ -0,0 +1,16 @@ +package ex.grpc; + +import com.google.net.stubby.stub.StreamObserver; + +public class GreetingsImpl implements GreetingsGrpc.Greetings { + + @Override + public void hello(Helloworld.HelloRequest req, + StreamObserver responseObserver) { + Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( + "Hello " + req.getName()).build(); + responseObserver.onValue(reply); + responseObserver.onCompleted(); + } + +} diff --git a/src/main/java/ex/grpc/GreetingsServer.java b/src/main/java/ex/grpc/GreetingsServer.java new file mode 100644 index 00000000000..834ae985a44 --- /dev/null +++ b/src/main/java/ex/grpc/GreetingsServer.java @@ -0,0 +1,51 @@ +package ex.grpc; + +import com.google.common.util.concurrent.MoreExecutors; +import com.google.net.stubby.ServerImpl; +import com.google.net.stubby.transport.netty.NettyServerBuilder; + +import java.util.concurrent.TimeUnit; + +/** + * Server that manages startup/shutdown of a {@code Greetings} server. + */ +public class GreetingsServer { + /* The port on which the server should run */ + private int port = 50051; + private ServerImpl server; + + private void start() throws Exception { + server = NettyServerBuilder.forPort(port) + .addService(GreetingsGrpc.bindService(new GreetingsImpl())) + .build(); + server.startAsync(); + server.awaitRunning(5, TimeUnit.SECONDS); + System.out.println("Server started on port:" + port); + } + + private void stop() throws Exception { + server.stopAsync(); + server.awaitTerminated(); + System.out.println("Server shutting down ..."); + } + + /** + * Main launches the server from the command line. + */ + public static void main(String[] args) throws Exception { + final GreetingsServer server = new GreetingsServer(); + + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + try { + System.out.println("Shutting down"); + server.stop(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + server.start(); + } +} From 737ee5848de1a0aa7c35f34889ff5a810a0d07b8 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sun, 25 Jan 2015 10:02:30 -0800 Subject: [PATCH 012/576] Adds: scripts to simplifying running the client and server --- run_greetings_client.sh | 10 ++++++++++ run_greetings_server.sh | 9 +++++++++ 2 files changed, 19 insertions(+) create mode 100755 run_greetings_client.sh create mode 100755 run_greetings_server.sh diff --git a/run_greetings_client.sh b/run_greetings_client.sh new file mode 100755 index 00000000000..8155589adf7 --- /dev/null +++ b/run_greetings_client.sh @@ -0,0 +1,10 @@ +#!/bin/bash -e +TARGET='Greetings Client' +TARGET_CLASS='ex.grpc.GreetingsClient' +TARGET_ARGS="$@" + +cd "$(dirname "$0")" +mvn -q -nsu -am package -Dcheckstyle.skip=true -DskipTests +. target/bootclasspath.properties +echo "[INFO] Running: $TARGET ($TARGET_CLASS $TARGET_ARGS)" +exec java "$bootclasspath" -cp "$jar" "$TARGET_CLASS" $TARGET_ARGS diff --git a/run_greetings_server.sh b/run_greetings_server.sh new file mode 100755 index 00000000000..248229e129e --- /dev/null +++ b/run_greetings_server.sh @@ -0,0 +1,9 @@ +#!/bin/bash -e +TARGET='Greetings Server' +TARGET_CLASS='ex.grpc.GreetingsServer' + +cd "$(dirname "$0")" +mvn -q -nsu -am package -Dcheckstyle.skip=true -DskipTests +. target/bootclasspath.properties +echo "[INFO] Running: $TARGET ($TARGET_CLASS)" +exec java "$bootclasspath" -cp "$jar" "$TARGET_CLASS" From a5570a457e513a66771407ebf0b6d7e8abe23a14 Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Fri, 30 Jan 2015 10:19:22 -0800 Subject: [PATCH 013/576] Initial commit --- LICENSE | 28 ++++++++++++++++++++++++++++ README.md | 2 ++ 2 files changed, 30 insertions(+) create mode 100644 LICENSE create mode 100644 README.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000000..05b6a757dab --- /dev/null +++ b/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2015, grpc +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of grpc-common nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/README.md b/README.md new file mode 100644 index 00000000000..2b288236bdf --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# grpc-common +documents, resources, examples shared across other grpc repositories From 85e9567a201bb23d6e0107cd95dd087817a57eb8 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 30 Jan 2015 10:26:56 -0800 Subject: [PATCH 014/576] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 2b288236bdf..a73b7723d8a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ # grpc-common documents, resources, examples shared across other grpc repositories + +# TODO +fill this out From 00e23cfd2a6f70a17ebaafebdd0eaf62533c1fa1 Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Wed, 4 Feb 2015 09:44:55 -0800 Subject: [PATCH 015/576] Update Step_0.md --- Step_0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_0.md b/Step_0.md index 3fec8376d1a..1a2dbcb2fe5 100644 --- a/Step_0.md +++ b/Step_0.md @@ -37,5 +37,5 @@ The service stanza of the message is an example of protobuf service IDL receives a request containing a name and returns a response containing a message. -Next, in [Step-1](Step-1.md), we'll use protoc to generate client code from +Next, in [Step_1](Step_1.md), we'll use protoc to generate client code from this IDL. From b9c24a11dd66a89ed9ce4f4ff4c93f22e46ffc1c Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Wed, 4 Feb 2015 09:46:09 -0800 Subject: [PATCH 016/576] Update Step_0.md --- Step_0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_0.md b/Step_0.md index 1a2dbcb2fe5..02a2b04c0e3 100644 --- a/Step_0.md +++ b/Step_0.md @@ -37,5 +37,5 @@ The service stanza of the message is an example of protobuf service IDL receives a request containing a name and returns a response containing a message. -Next, in [Step_1](Step_1.md), we'll use protoc to generate client code from +Next, in [Step - 1](Step_1.md), we'll use protoc to generate client code from this IDL. From 15dd5da9f5a1cd6783ae9640ebfe02efbdcfedbc Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Wed, 4 Feb 2015 09:56:29 -0800 Subject: [PATCH 017/576] Update Step_1.md --- Step_1.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_1.md b/Step_1.md index 4ac68aba5df..da85cb4e10f 100644 --- a/Step_1.md +++ b/Step_1.md @@ -29,5 +29,5 @@ $ protoc -I . helloworld.proto --plugin=protoc-gen-grpc=external/grpc_java/bins/ --java_out=src/main/java ``` -Next, in [Step-2](Step-2.md), we'll use the generated Stub implementation to +Next, in [Step - 2](Step_2.md), we'll use the generated Stub implementation to write a client that uses the generated code to make a call to a service. From 5a92194fb0c3fb6936b8144f98853f0b9a234a0f Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Wed, 4 Feb 2015 09:57:40 -0800 Subject: [PATCH 018/576] Update Step_2.md --- Step_2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_2.md b/Step_2.md index dd134a989c5..32c578f18a9 100644 --- a/Step_2.md +++ b/Step_2.md @@ -72,7 +72,7 @@ $ mvn package ``` It can also be run, but doing so now would end up a with a failure as there is -no server available yet. The [next step](Step-3.md), describes how to +no server available yet. The [next step](Step_3.md), describes how to implement, build and run a server that supports the service description. ## Notes From 99a1fe644087da862af2287c452b38b7fd4f1b9c Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Wed, 4 Feb 2015 10:07:45 -0800 Subject: [PATCH 019/576] Fixed 2 typos. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9a668f3b1cd..c0fc227b29b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# gRPC Helloworld Tutorial +# gRPC Hello World Tutorial ## TODO: move this to the tutorial sub-folder @@ -8,7 +8,7 @@ various features of gRPC. When you finish the tutorial, you will be able to -- Create an protobuf schema that defines a simple RPC service +- Create a protobuf schema that defines a simple RPC service - Create a Java server that implements the schema interface - Create a Java client that accesses the server - Create a Go client that accesses the Java server From cdf7f84d073ef17da2b73de53cdcc0164368e109 Mon Sep 17 00:00:00 2001 From: Mugur Marculescu Date: Wed, 4 Feb 2015 20:14:08 -0800 Subject: [PATCH 020/576] Attempt to Fix broken link to helloworld.proto Actually Fix broken link to helloworld.proto --- Step_0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_0.md b/Step_0.md index 02a2b04c0e3..a346f77e814 100644 --- a/Step_0.md +++ b/Step_0.md @@ -5,7 +5,7 @@ a message from a remote client. The message contains the users's name and sends back a greeting to that person. It's shown below in full; it's actually contained in separate file -[helloworld.proto](helloworld.proto). +[helloworld.proto](src/main/proto/helloworld.proto). ``` syntax = "proto3"; From 5d8c3b264c89fb1598e4cc418e2c0c4c417d5c4b Mon Sep 17 00:00:00 2001 From: Mugur Marculescu Date: Wed, 4 Feb 2015 21:21:37 -0800 Subject: [PATCH 021/576] Fixing a couple of typos and grammer issues. --- README.md | 18 +++++++++--------- Step_0.md | 6 +++--- Step_1.md | 4 ++-- Step_2.md | 10 +++++----- Step_3.md | 16 ++++++++-------- 5 files changed, 27 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index c0fc227b29b..41b79ba883d 100644 --- a/README.md +++ b/README.md @@ -3,16 +3,16 @@ ## TODO: move this to the tutorial sub-folder A great way to get introduced to gRPC is to work through this tutorial, which -walks you through the construction of simple client and server that introduces +walks you through the construction of a simple client and server and introduces various features of gRPC. When you finish the tutorial, you will be able to -- Create a protobuf schema that defines a simple RPC service -- Create a Java server that implements the schema interface -- Create a Java client that accesses the server -- Create a Go client that accesses the Java server -- Update the service with advanced features like RPC streaming +- Create a protobuf schema that defines a simple RPC service. +- Create a Java server that implements the schema interface. +- Create a Java client that accesses the server. +- Create a Go client that accesses the Java server. +- Update the service with advanced features like RPC streaming. # Get Started @@ -22,7 +22,7 @@ If you just want to read the tutorial, you can go straight to the next step: [St # Working with the code You can follow along with this tutorial and hack on the code in the comfort of -your own computer. In this way you can get hands-on practice of really writing +your own computer. This way you can get hands-on practice of really writing gRPC code. The tutorial relies on the use of the Git versioning system for source code @@ -61,7 +61,7 @@ for instructions. # Install Maven -To simplify building and the managing of gRPC's dependencies, the java client +To simplify building and the managing of gRPC's dependencies, the Java client are server are structured as a standard [Maven](http://maven.apache.org/guides/getting-started/) project. See [Install Maven](http://maven.apache.org/users/index.html) for instructions. @@ -76,6 +76,6 @@ Go gRPC requires Go 1.4, the latest version of Go. See gRPC uses the latest version of the protocol buffer compiler, protoc. For following this tutorial, the protoc is not strictly necessary, as all the -generated code is checked into the Git repository. If you want to experiment +generated code is checked into the Git repository. If you want to experiment with generating the code yourself, download and install protoc from its [Git repo](https://github.com/google/protobuf) diff --git a/Step_0.md b/Step_0.md index a346f77e814..07c5bc5690f 100644 --- a/Step_0.md +++ b/Step_0.md @@ -1,10 +1,10 @@ # Step-0: define a service This section presents an example of a simple service definition that receives -a message from a remote client. The message contains the users's name and +a message from a remote client. The message contains the user's name and sends back a greeting to that person. -It's shown below in full; it's actually contained in separate file +It's shown below in full; it's actually contained in separate file. [helloworld.proto](src/main/proto/helloworld.proto). ``` @@ -33,7 +33,7 @@ service Greeting { ``` The service stanza of the message is an example of protobuf service IDL -(Interface Defintion Language). Here, it defines a simple service that +(Interface Defintion Language). Here, it defines a simple service that receives a request containing a name and returns a response containing a message. diff --git a/Step_1.md b/Step_1.md index da85cb4e10f..c7aed326c38 100644 --- a/Step_1.md +++ b/Step_1.md @@ -1,6 +1,6 @@ # Step-1: Generate a service client. -In this step, we use protoc to generate the java Stub classes. A Stub is the +In this step, we use protoc to generate the Java Stub classes. A Stub is the name gRPC uses for the code that initiates contact with a gRPC service running remotely via the internet. @@ -11,7 +11,7 @@ First, you'll need to build the protobuf plugin that generates the rpc classes. `protoc` uses other tools called plugins to add additional features to generated code. -The grpc Java Stub classes are created using a grpc java plugin, but first the +The gRPC Java Stub classes are created using a gRPC Java plugin, but first the plugin must be built and installed. To build the plugin: diff --git a/Step_2.md b/Step_2.md index 32c578f18a9..eafe70b6923 100644 --- a/Step_2.md +++ b/Step_2.md @@ -1,15 +1,15 @@ # Step-2: Write a service client. This step uses the generated code to write a simple client to access the hello -service. The full client is in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). +service. The full client is in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). ## Configuring the service to connect to. -The client contains uses a Stub to contact the service. The internet address -is configured in the client constructor. gRPC Channel is the abstraction over +The client contains uses a Stub to contact the service. The internet address +is configured in the client constructor. gRPC Channel is the abstraction over transport handling; its constructor accepts the host name and port of the -service. The channel in turn is used to construct the Stub. +service. The channel in turn is used to construct the Stub. ``` @@ -77,7 +77,7 @@ implement, build and run a server that supports the service description. ## Notes -- the client uses a blocking stub. This means that the RPC call waits for the +- The client uses a blocking stub. This means that the RPC call waits for the server to respond, and will either return a response or raise an exception. - gRPC Java has other kinds of stubs that make non-blocking calls to the diff --git a/Step_3.md b/Step_3.md index 56d6e7cfd3a..bba8f0aa3fb 100644 --- a/Step_3.md +++ b/Step_3.md @@ -1,16 +1,16 @@ # Step-3: Implement a server. This step extends the generated server skeleton code to write a simple server -that provides the hello service. This in introduces two new classes +that provides the hello service. This introduces two new classes: - a service implementation [GreetingsImpl.java](src/main/java/ex/grpc/GreetingsImpl.java). -- a server that hosts the service implementation and allows to accessed over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). +- a server that hosts the service implementation and allows access over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). ## Service implementation -[GreetingsSImpl.java](src/main/java/ex/grpc/GreetingsImpl.java) -implements the behaviour we require of our GreetingService. There are a +[GreetingsImpl.java](src/main/java/ex/grpc/GreetingsImpl.java) +implements the behaviour we require of our GreetingService. There are a number of important features of gRPC being used here: ``` @@ -39,7 +39,7 @@ number of important features of gRPC being used here: ## Server implementation [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the -other main feature to required to provde gRPC service; how to allow a service +other main feature required to provde the gRPC service; how to allow a service implementation to be accessed from the network. ``` @@ -68,14 +68,14 @@ $ mvn package ## Try them out -We've added simple shell scripts to simplifying running the examples. Now -that they are built, you can run the server with. +We've added simple shell scripts to simplifying running the examples. Now +that they are built, you can run the server with: ``` $ ./run_greetings_server.sh ``` -In another termainal window and confirm that it receives a message. +and in another termainal window and confirm that it receives a message. ``` $ ./run_greetings_client.sh From d2828d9b1b0341e068741516fc91702a96844519 Mon Sep 17 00:00:00 2001 From: Mugur Marculescu Date: Wed, 4 Feb 2015 21:50:56 -0800 Subject: [PATCH 022/576] Another grammar fix. --- Step_3.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_3.md b/Step_3.md index bba8f0aa3fb..d2d7f4788db 100644 --- a/Step_3.md +++ b/Step_3.md @@ -75,7 +75,7 @@ that they are built, you can run the server with: $ ./run_greetings_server.sh ``` -and in another termainal window and confirm that it receives a message. +and in another termainal window confirm that it receives a message. ``` $ ./run_greetings_client.sh From 8c92a90a4a3bdd0bd5ec37b7f9ad412cd0cd7f1f Mon Sep 17 00:00:00 2001 From: Mugur Marculescu Date: Wed, 4 Feb 2015 21:52:45 -0800 Subject: [PATCH 023/576] Another typo fix. --- Step_3.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_3.md b/Step_3.md index d2d7f4788db..7b03cdf585f 100644 --- a/Step_3.md +++ b/Step_3.md @@ -75,7 +75,7 @@ that they are built, you can run the server with: $ ./run_greetings_server.sh ``` -and in another termainal window confirm that it receives a message. +and in another terminal window confirm that it receives a message. ``` $ ./run_greetings_client.sh From a14935fceeaa9111579a65e85929b9a171debe43 Mon Sep 17 00:00:00 2001 From: Mugur Marculescu Date: Thu, 5 Feb 2015 16:14:17 -0800 Subject: [PATCH 024/576] Another typo. --- Step_0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Step_0.md b/Step_0.md index 07c5bc5690f..d0745b0dd1f 100644 --- a/Step_0.md +++ b/Step_0.md @@ -33,7 +33,7 @@ service Greeting { ``` The service stanza of the message is an example of protobuf service IDL -(Interface Defintion Language). Here, it defines a simple service that +(Interface Definition Language). Here, it defines a simple service that receives a request containing a name and returns a response containing a message. From 8f505f74e420a5fe52cf084a55117f5c73e11774 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Thu, 5 Feb 2015 17:34:47 -0800 Subject: [PATCH 025/576] Adds the common protos along with a README.md --- protos/README.md | 12 +++++++ protos/helloworld.proto | 51 ++++++++++++++++++++++++++ protos/math.proto | 79 +++++++++++++++++++++++++++++++++++++++++ protos/stock.proto | 71 ++++++++++++++++++++++++++++++++++++ 4 files changed, 213 insertions(+) create mode 100644 protos/README.md create mode 100644 protos/helloworld.proto create mode 100644 protos/math.proto create mode 100644 protos/stock.proto diff --git a/protos/README.md b/protos/README.md new file mode 100644 index 00000000000..29639a68f44 --- /dev/null +++ b/protos/README.md @@ -0,0 +1,12 @@ +# Example protos + +## Contents + +- helloworld.proto + A very simple example used in the overview. + +- stock.proto + A detailed example that's described in detail in the tutorial. + +- math.proto + Another detailed example for further reference. diff --git a/protos/helloworld.proto b/protos/helloworld.proto new file mode 100644 index 00000000000..aa44b851f43 --- /dev/null +++ b/protos/helloworld.proto @@ -0,0 +1,51 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +option java_package = "ex.grpc"; + +package helloworld; + +// The request message containing the user's name. +message HelloRequest { + optional string name = 1; +} + +// The response message containing the greetings +message HelloReply { + optional string message = 1; +} + +// The greeting service definition. +service Greetings { + // Sends a greeting + rpc hello (HelloRequest) returns (HelloReply) { + } +} diff --git a/protos/math.proto b/protos/math.proto new file mode 100644 index 00000000000..46a33aeee53 --- /dev/null +++ b/protos/math.proto @@ -0,0 +1,79 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package math; + +message DivArgs { + optional int64 dividend = 1; + optional int64 divisor = 2; +} + +message DivReply { + optional int64 quotient = 1; + optional int64 remainder = 2; +} + +message FibArgs { + optional int64 limit = 1; +} + +message Num { + optional int64 num = 1; +} + +message FibReply { + optional int64 count = 1; +} + +service Math { + // Div divides args.dividend by args.divisor and returns the quotient and + // remainder. + rpc Div (DivArgs) returns (DivReply) { + } + + // DivMany accepts an arbitrary number of division args from the client stream + // and sends back the results in the reply stream. The stream continues until + // the client closes its end; the server does the same after sending all the + // replies. The stream ends immediately if either end aborts. + rpc DivMany (stream DivArgs) returns (stream DivReply) { + } + + // Fib generates numbers in the Fibonacci sequence. If args.limit > 0, Fib + // generates up to limit numbers; otherwise it continues until the call is + // canceled. + rpc Fib (FibArgs) returns (stream Num) { + } + + // Sum sums a stream of numbers, returning the final result once the stream + // is closed. + rpc Sum (stream Num) returns (Num) { + } +} diff --git a/protos/stock.proto b/protos/stock.proto new file mode 100644 index 00000000000..dcb677e4733 --- /dev/null +++ b/protos/stock.proto @@ -0,0 +1,71 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package examples; + +// Protocol type definitions +message StockRequest { + optional string symbol = 1; + optional int32 num_trades_to_watch = 2; +}; + +message StockReply { + optional float price = 1; + optional string symbol = 2; +}; + +// Interface exported by the server +service Stock { + // A simple blocking RPC. + // + // Obtains the last traded price for the given Stock. + rpc GetLastTradePrice(StockRequest) returns (StockReply) { + }; + + // A Unidirectional server-to-client streaming RPC. + // + // Streams future prices for a given symbol. + rpc WatchFutureTrades(StockRequest) returns (stream StockReply) { + }; + + // A Unidirectional client-to-server streaming RPC. + // + // Gets the highest traded price for a series of symbols + rpc GetHighestTradePrice(stream StockRequest) returns (StockReply) { + }; + + // Bidirectional streaming RPC. + // + // Gets the most recent traded price of series of trades. + rpc GetLastTradePriceMultiple(stream StockRequest) returns + (stream StockReply) { + }; +}; From bb9e6f4e7ce17d5a06e10a487e65ed6a1473155a Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 6 Feb 2015 12:56:33 -0800 Subject: [PATCH 026/576] removed superfluous semi-colons --- protos/stock.proto | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/protos/stock.proto b/protos/stock.proto index dcb677e4733..49efbf2730a 100644 --- a/protos/stock.proto +++ b/protos/stock.proto @@ -35,12 +35,12 @@ package examples; message StockRequest { optional string symbol = 1; optional int32 num_trades_to_watch = 2; -}; +} message StockReply { optional float price = 1; optional string symbol = 2; -}; +} // Interface exported by the server service Stock { @@ -48,24 +48,24 @@ service Stock { // // Obtains the last traded price for the given Stock. rpc GetLastTradePrice(StockRequest) returns (StockReply) { - }; + } // A Unidirectional server-to-client streaming RPC. // // Streams future prices for a given symbol. rpc WatchFutureTrades(StockRequest) returns (stream StockReply) { - }; + } // A Unidirectional client-to-server streaming RPC. // // Gets the highest traded price for a series of symbols rpc GetHighestTradePrice(stream StockRequest) returns (StockReply) { - }; + } // Bidirectional streaming RPC. // // Gets the most recent traded price of series of trades. rpc GetLastTradePriceMultiple(stream StockRequest) returns (stream StockReply) { - }; -}; + } +} From aa7afd63a8611c1e64de21d54da0eeb86a0c8360 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 6 Feb 2015 13:09:20 -0800 Subject: [PATCH 027/576] Moves java overview project to a subdirectory --- pom.xml => java/pom.xml | 0 run_greetings_client.sh => java/run_greetings_client.sh | 0 run_greetings_server.sh => java/run_greetings_server.sh | 0 {src => java/src}/main/java/ex/grpc/GreetingsClient.java | 0 {src => java/src}/main/java/ex/grpc/GreetingsGrpc.java | 0 {src => java/src}/main/java/ex/grpc/GreetingsImpl.java | 0 {src => java/src}/main/java/ex/grpc/GreetingsServer.java | 0 {src => java/src}/main/java/ex/grpc/Helloworld.java | 0 {src => java/src}/main/proto/helloworld.proto | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename pom.xml => java/pom.xml (100%) rename run_greetings_client.sh => java/run_greetings_client.sh (100%) rename run_greetings_server.sh => java/run_greetings_server.sh (100%) rename {src => java/src}/main/java/ex/grpc/GreetingsClient.java (100%) rename {src => java/src}/main/java/ex/grpc/GreetingsGrpc.java (100%) rename {src => java/src}/main/java/ex/grpc/GreetingsImpl.java (100%) rename {src => java/src}/main/java/ex/grpc/GreetingsServer.java (100%) rename {src => java/src}/main/java/ex/grpc/Helloworld.java (100%) rename {src => java/src}/main/proto/helloworld.proto (100%) diff --git a/pom.xml b/java/pom.xml similarity index 100% rename from pom.xml rename to java/pom.xml diff --git a/run_greetings_client.sh b/java/run_greetings_client.sh similarity index 100% rename from run_greetings_client.sh rename to java/run_greetings_client.sh diff --git a/run_greetings_server.sh b/java/run_greetings_server.sh similarity index 100% rename from run_greetings_server.sh rename to java/run_greetings_server.sh diff --git a/src/main/java/ex/grpc/GreetingsClient.java b/java/src/main/java/ex/grpc/GreetingsClient.java similarity index 100% rename from src/main/java/ex/grpc/GreetingsClient.java rename to java/src/main/java/ex/grpc/GreetingsClient.java diff --git a/src/main/java/ex/grpc/GreetingsGrpc.java b/java/src/main/java/ex/grpc/GreetingsGrpc.java similarity index 100% rename from src/main/java/ex/grpc/GreetingsGrpc.java rename to java/src/main/java/ex/grpc/GreetingsGrpc.java diff --git a/src/main/java/ex/grpc/GreetingsImpl.java b/java/src/main/java/ex/grpc/GreetingsImpl.java similarity index 100% rename from src/main/java/ex/grpc/GreetingsImpl.java rename to java/src/main/java/ex/grpc/GreetingsImpl.java diff --git a/src/main/java/ex/grpc/GreetingsServer.java b/java/src/main/java/ex/grpc/GreetingsServer.java similarity index 100% rename from src/main/java/ex/grpc/GreetingsServer.java rename to java/src/main/java/ex/grpc/GreetingsServer.java diff --git a/src/main/java/ex/grpc/Helloworld.java b/java/src/main/java/ex/grpc/Helloworld.java similarity index 100% rename from src/main/java/ex/grpc/Helloworld.java rename to java/src/main/java/ex/grpc/Helloworld.java diff --git a/src/main/proto/helloworld.proto b/java/src/main/proto/helloworld.proto similarity index 100% rename from src/main/proto/helloworld.proto rename to java/src/main/proto/helloworld.proto From c509d3545531f1424335123670c9bcf9ca5ba934 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 6 Feb 2015 13:21:36 -0800 Subject: [PATCH 028/576] Updates the references to the moved java source files. - Also specifies the what type of source is being rendered in the syntax-highlighted sections --- Step_1.md | 9 ++++----- Step_2.md | 2 +- Step_3.md | 23 ++++++++++++----------- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Step_1.md b/Step_1.md index c7aed326c38..1e9ca2b2a50 100644 --- a/Step_1.md +++ b/Step_1.md @@ -15,18 +15,17 @@ The gRPC Java Stub classes are created using a gRPC Java plugin, but first the plugin must be built and installed. To build the plugin: -``` +```sh $ pushd external/grpc_java $ make java_plugin $ popd ``` To use it to generate the code: -``` -$ mkdir -p src/main/java +```sh $ protoc -I . helloworld.proto --plugin=protoc-gen-grpc=external/grpc_java/bins/opt/java_plugin \ - --grpc_out=src/main/java \ - --java_out=src/main/java + --grpc_out=java/src/main/java \ + --java_out=java/src/main/java ``` Next, in [Step - 2](Step_2.md), we'll use the generated Stub implementation to diff --git a/Step_2.md b/Step_2.md index eafe70b6923..d2e1ae48b05 100644 --- a/Step_2.md +++ b/Step_2.md @@ -1,7 +1,7 @@ # Step-2: Write a service client. This step uses the generated code to write a simple client to access the hello -service. The full client is in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). +service. The full client is in [GreetingsClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). ## Configuring the service to connect to. diff --git a/Step_3.md b/Step_3.md index 7b03cdf585f..9eb1009d2e6 100644 --- a/Step_3.md +++ b/Step_3.md @@ -3,17 +3,17 @@ This step extends the generated server skeleton code to write a simple server that provides the hello service. This introduces two new classes: -- a service implementation [GreetingsImpl.java](src/main/java/ex/grpc/GreetingsImpl.java). +- a service implementation [GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). -- a server that hosts the service implementation and allows access over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). +- a server that hosts the service implementation and allows access over the network: [GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java). ## Service implementation -[GreetingsImpl.java](src/main/java/ex/grpc/GreetingsImpl.java) +[GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java) implements the behaviour we require of our GreetingService. There are a number of important features of gRPC being used here: -``` +```java public void hello(Helloworld.HelloRequest req, StreamObserver responseObserver) { Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( @@ -24,7 +24,7 @@ number of important features of gRPC being used here: ``` - it provides a class `GreetingsImpl` that implements a generated interface `GreetingsGrpc.Greetings` -- `GreetingsGrpc.Greetings` declares the method `hello` that was declared in the proto [IDL](src/main/proto/helloworld.proto) +- `GreetingsGrpc.Greetings` declares the method `hello` that was declared in the proto [IDL](java/src/main/proto/helloworld.proto) - `hello's` signature is typesafe: hello(Helloworld.HelloRequest req, StreamObserver responseObserver) - `hello` takes two parameters: @@ -38,11 +38,11 @@ number of important features of gRPC being used here: ## Server implementation -[GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the +[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) shows the other main feature required to provde the gRPC service; how to allow a service implementation to be accessed from the network. -``` +```java private void start() throws Exception { server = NettyServerBuilder.forPort(port) .addService(GreetingsGrpc.bindService(new GreetingsImpl())) @@ -62,7 +62,8 @@ implementation to be accessed from the network. This is the same as before: our client and server are part of the same maven package so the same command builds both. -``` +```sh +$ cd java $ mvn package ``` @@ -71,12 +72,12 @@ $ mvn package We've added simple shell scripts to simplifying running the examples. Now that they are built, you can run the server with: -``` +```sh $ ./run_greetings_server.sh ``` and in another terminal window confirm that it receives a message. -``` -$ ./run_greetings_client.sh +```sh +$ ./java/run_greetings_client.sh ``` From f751995e86eacf7a475f7fb7ee52d2e45ab0b599 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 6 Feb 2015 13:59:50 -0800 Subject: [PATCH 029/576] Update README.md --- protos/README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/protos/README.md b/protos/README.md index 29639a68f44..374d4350aca 100644 --- a/protos/README.md +++ b/protos/README.md @@ -3,10 +3,8 @@ ## Contents - helloworld.proto - A very simple example used in the overview. - + - A very simple example used in the overview. - stock.proto - A detailed example that's described in detail in the tutorial. - + - A detailed example that's described in detail in the tutorial. - math.proto - Another detailed example for further reference. + - Another detailed example for further reference. From cf6360377c9d42f66b8940f6006c503f276907da Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 9 Feb 2015 17:14:14 +0000 Subject: [PATCH 030/576] First commit of consolidated overview/README --- README.md | 275 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 237 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 41b79ba883d..fbd35ebad97 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,64 @@ -# gRPC Hello World Tutorial +# Getting started ## TODO: move this to the tutorial sub-folder -A great way to get introduced to gRPC is to work through this tutorial, which -walks you through the construction of a simple client and server and introduces -various features of gRPC. +Welcome to the developer documentation for gRPC, a language-neutral, +platform-neutral remote procedure call (RPC) system developed at Google that +helps you build connected systems. -When you finish the tutorial, you will be able to +This document introduces you to gRPC with a quick overview and a simple +Hello World example. More documentation is coming soon! -- Create a protobuf schema that defines a simple RPC service. -- Create a Java server that implements the schema interface. -- Create a Java client that accesses the server. -- Create a Go client that accesses the Java server. -- Update the service with advanced features like RPC streaming. +## What is gRPC? + +## TODO: basic conceptual intro (anything more in-depth will go in gRPC Concepts doc) + +## Hello gRPC! -# Get Started +Now that you know a bit more about gRPC, the easiest way to see how it +works is to look at a simple example. Our Hello World walks you through the +construction of a simple gRPC client-server application, showing you how to: + +- Create a protobuf schema that defines a simple RPC service with a single +Hello World method. +- Create a Java server that implements the schema interface. +- Create a Java client that accesses the Java server. +- Create a Go client that accesses the same Java server. +- Update the service with more advanced features like RPC streaming. -The rest of this page explains how you can set up your local machine for development. -If you just want to read the tutorial, you can go straight to the next step: [Step - 0](Step_0.md) +The complete code for the example is available in [wherever we put it]. You can +work along with the example and hack on the code in the comfort of your own +computer, giving you hands-on practice of really writing +gRPC code. We use the Git versioning system for source code management: +however, you don't need to know anything about Git to follow along other +than how to install and run a few git commands. -# Working with the code +This is an introductory example rather than a comprehensive tutorial, so +don't worry if you're not a Go or +Java developer - complete tutorials and reference documentation for all gRPC +languages are coming soon. -You can follow along with this tutorial and hack on the code in the comfort of -your own computer. This way you can get hands-on practice of really writing -gRPC code. +### Setup -The tutorial relies on the use of the Git versioning system for source code -management. You don't need to know anything about Git to follow the tutorial -other than how to install and run a few git commands. +The rest of this page explains how to set up your local machine to work with +the example code. +If you just want to read the example, you can go straight to the next step: +[Step - 0](Step_0.md) -# Install Git +#### Install Git You can download and install Git from http://git-scm.com/download. Once installed you should have access to the git command line tool. The main commands that you will need to use are: - git clone ... : clone a remote repository onto your local machine -- git checkout ... : check out a particular branch or a tagged version of the code to hack on +- git checkout ... : check out a particular branch or a tagged version of +the code to hack on -# Download grpc-helloworld +#### Download grpc-helloworld -Clone the grpc-helloword repository located at GitHub by running the following command: +Clone the grpc-helloword repository located at GitHub by running the +following command: ``` git clone https://github.com/google/grpc-helloworld.git @@ -52,30 +70,211 @@ Change your current directory to grpc-helloworld cd grpc-helloworld ``` -# Install Java 8 +#### Install Java 8 -Java gRPC is designed to work with both Java 7 and Java 8. For simplicity, -the example assumes that Java 8 is installed. See -[Install Java 8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) -for instructions. +Java gRPC is designed to work with both Java 7 and Java 8 - our example uses +Java 8. See +[Install Java +8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) +for instructions if you need to install Java 8. -# Install Maven +#### Install Maven -To simplify building and the managing of gRPC's dependencies, the Java client -are server are structured as a standard [Maven](http://maven.apache.org/guides/getting-started/) -project. See [Install Maven](http://maven.apache.org/users/index.html) for instructions. +To simplify building and managing gRPC's dependencies, the Java client +and server are structured as a standard +[Maven](http://maven.apache.org/guides/getting-started/) +project. See [Install Maven](http://maven.apache.org/users/index.html) +for instructions. -# Install Go 1.4 +#### Install Go 1.4 Go gRPC requires Go 1.4, the latest version of Go. See [Install Go](https://golang.org/doc/install) for instructions. -# (optional) Install protoc +#### (optional) Install protoc -gRPC uses the latest version of the protocol buffer compiler, protoc. +gRPC uses the latest version of the [protocol +buffer](https://developers.google.com/protocol-buffers/docs/overview) +compiler, protoc. -For following this tutorial, the protoc is not strictly necessary, as all the -generated code is checked into the Git repository. If you want to experiment +Having protoc installed isn't strictly necessary to follow along with this +example, as all the +generated code is checked into the Git repository. However, if you want +to experiment with generating the code yourself, download and install protoc from its [Git repo](https://github.com/google/protobuf) + +### Defining a service + +The first step in creating our example is to define a *service*: an RPC +service specifies the methods that can be called remotely with their parameters +and return types. In gRPC, we use the protocol buffers interface definition +language (IDL) to define our service methods, and the parameters and return +types are defined as protocol buffer message types. Both the client and the +server use interface code generated from the service definition. If you're not +familiar with protocol buffers, you can find out more in the [Protocol Buffers +Developer Guide](https://developers.google.com/protocol-buffers/docs/overview). + +Here's our example service definition, defined using protocol buffers IDL in +[helloworld.proto](src/main/proto/helloworld.proto). The `Greeting` service +has one method, `hello`, that lets the server receive a single `HelloRequest` +message from the remote client containing the user's name, then send back +a greeting in a `HelloReply`. + +``` +syntax = "proto3"; + +package helloworld; + +// The request message containing the user's name. +message HelloRequest { + optional string name = 1; +} + +// The response message containing the greetings +message HelloReply { + optional string message = 1; +} + +// The greeting service definition. +service Greeting { + + // Sends a greeting + rpc hello (HelloRequest) returns (HelloReply) { + } +} + +``` + +### Generating gRPC code + +Once we've defined our service, we use the protocol buffer compiler +`protoc` to generate the special client and server code we need to create +our application - right now we're going to generate Java code, though you +can generate gRPC code in any gRPC-supported language (as you'll see later +in this example). The generated code contains both stub code for clients to +use and an abstract interface for servers to implement, both with the method +defined in our `Greeting` service. A stub is code that initiates contact +with a gRPC service running remotely via the internet. [can probably define +this up in "what is gRPC"?] + +(If you didn't install `protoc` on your system and are working along with +the example, you can skip this step and move +onto the next one where we examine the generated code.) + +As this is our first time using gRPC, we need to build the protobuf plugin that generates our RPC +classes. By default `protoc` just generates code for reading and writing +protocol buffers, so you need to use plugins to add additional features +to generated code. As we're creating Java code, we use the gRPC Java plugin. + +To build the plugin: + +``` +$ pushd external/grpc_java +$ make java_plugin +$ popd +``` + +To use it to generate the code: + +``` +$ mkdir -p src/main/java +$ protoc -I . helloworld.proto +--plugin=protoc-gen-grpc=external/grpc_java/bins/opt/java_plugin \ + --grpc_out=src/main/java \ + --java_out=src/main/java +``` + +This generates the following Java classes + +### Writing a client + +Now let's write some code! Client-side gRPC is pretty simple, so we'll start there - we'll look at how to implement a gRPC server later. In this step, we'll use the generated code to write a simple client that can access the `Greetings` service. You can see the complete client code in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). + +Note that we're not going to go into much detail about how to implement a client - we'll leave that for the tutorial. + +#### Connecting to the service + +. The internet address +is configured in the client constructor. gRPC Channel is the abstraction over +transport handling; its constructor accepts the host name and port of the +service. The channel in turn is used to construct the Stub. + + +``` + private final ChannelImpl channel; + private final GreetingGrpc.GreetingBlockingStub blockingStub; + + public HelloClient(String host, int port) { + channel = NettyChannelBuilder.forAddress(host, port) + .negotiationType(NegotiationType.PLAINTEXT) + .build(); + blockingStub = GreetingGrpc.newBlockingStub(channel); + } + +``` + +#### Obtaining a greeting + +The greet method uses the stub to contact the service and obtain a greeting. +It: +- constructs a request +- obtains a reply from the stub +- prints out the greeting + + +``` + public void greet(String name) { + logger.debug("Will try to greet " + name + " ..."); + try { + Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName(name).build(); + Helloworld.HelloReply reply = blockingStub.hello(request); + logger.info("Greeting: " + reply.getMessage()); + } catch (RuntimeException e) { + logger.log(Level.WARNING, "RPC failed", e); + return; + } + } + +``` + +#### Running from the command line + +The main method puts together the example so that it can be run from a command +line. + +``` + /* Access a service running on the local machine on port 50051 */ + HelloClient client = new HelloClient("localhost", 50051); + String user = "world"; + if (args.length > 1) { + user = args[1]; + } + client.greet(user); + +``` + +It can be built as follows. + +``` +$ mvn package +``` + +It can also be run, but doing so now would end up a with a failure as there is +no server available yet. The [next step](Step_3.md), describes how to +implement, build and run a server that supports the service description. + +#### Notes + +- The client uses a blocking stub. This means that the RPC call waits for the + server to respond, and will either return a response or raise an exception. + +- gRPC Java has other kinds of stubs that make non-blocking calls to the + server, where the response is returned asynchronously. Usage of these stubs + is a more advanced topic and will be described in later steps. + + +We haven't looked at implementing a server yet, but + + From ad011166baf7eb1359a5db25d3933e2ec940b1db Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 9 Feb 2015 17:30:37 +0000 Subject: [PATCH 031/576] Minor restructure --- README.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index fbd35ebad97..d7ecba75669 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,7 @@ languages are coming soon. The rest of this page explains how to set up your local machine to work with the example code. -If you just want to read the example, you can go straight to the next step: -[Step - 0](Step_0.md) +If you just want to read the example, you can go straight to the next step. #### Install Git @@ -188,11 +187,18 @@ $ protoc -I . helloworld.proto This generates the following Java classes +### Writing a server + +Now let's write some code! First we'll create the `Greetings` server. + +Note that we're not going to go into a lot of detail about how to create a server in this section More detailed information will be in the tutorial for your chosen language (coming soon). + + ### Writing a client -Now let's write some code! Client-side gRPC is pretty simple, so we'll start there - we'll look at how to implement a gRPC server later. In this step, we'll use the generated code to write a simple client that can access the `Greetings` service. You can see the complete client code in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). +Client-side gRPC is pretty simple. In this step, we'll use the generated code to write a simple client that can access the `Greetings` server we created in the previous section. You can see the complete client code in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). -Note that we're not going to go into much detail about how to implement a client - we'll leave that for the tutorial. +Again, we're not going to go into much detail about how to implement a client - we'll leave that for the tutorial. #### Connecting to the service From c57778bdba28d6db3bf08f30cc0350f3d0b36812 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 10 Feb 2015 16:38:10 +0000 Subject: [PATCH 032/576] Added server and client steps. Still a bit rough round the edges.... --- README.md | 139 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 122 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index d7ecba75669..3a2f3c85551 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,7 @@ ## TODO: move this to the tutorial sub-folder Welcome to the developer documentation for gRPC, a language-neutral, -platform-neutral remote procedure call (RPC) system developed at Google that -helps you build connected systems. +platform-neutral remote procedure call (RPC) system developed at Google. This document introduces you to gRPC with a quick overview and a simple Hello World example. More documentation is coming soon! @@ -13,6 +12,7 @@ Hello World example. More documentation is coming soon! ## TODO: basic conceptual intro (anything more in-depth will go in gRPC Concepts doc) + ## Hello gRPC! Now that you know a bit more about gRPC, the easiest way to see how it @@ -38,11 +38,12 @@ don't worry if you're not a Go or Java developer - complete tutorials and reference documentation for all gRPC languages are coming soon. + ### Setup The rest of this page explains how to set up your local machine to work with the example code. -If you just want to read the example, you can go straight to the next step. +If you just want to read the example, you can go straight to the [next step](#servicedef). #### Install Git @@ -54,19 +55,19 @@ commands that you will need to use are: - git checkout ... : check out a particular branch or a tagged version of the code to hack on -#### Download grpc-helloworld +#### Get the source code -Clone the grpc-helloword repository located at GitHub by running the +The example code for this and our other examples lives in the `grpc-common` GitHub repository. Clone this repository to your local machine by running the following command: ``` -git clone https://github.com/google/grpc-helloworld.git +git clone https://github.com/google/grpc-common.git ``` -Change your current directory to grpc-helloworld +Change your current directory to grpc-common/java ``` -cd grpc-helloworld +cd grpc-common/java ``` #### Install Java 8 @@ -104,6 +105,7 @@ to experiment with generating the code yourself, download and install protoc from its [Git repo](https://github.com/google/protobuf) + ### Defining a service The first step in creating our example is to define a *service*: an RPC @@ -116,7 +118,7 @@ familiar with protocol buffers, you can find out more in the [Protocol Buffers Developer Guide](https://developers.google.com/protocol-buffers/docs/overview). Here's our example service definition, defined using protocol buffers IDL in -[helloworld.proto](src/main/proto/helloworld.proto). The `Greeting` service +[helloworld.proto](java/src/main/proto/helloworld.proto) _should we link to the version in the Java subdirectory or the one in the common protos directory?_. The `Greeting` service has one method, `hello`, that lets the server receive a single `HelloRequest` message from the remote client containing the user's name, then send back a greeting in a `HelloReply`. @@ -124,6 +126,8 @@ a greeting in a `HelloReply`. ``` syntax = "proto3"; +option java_package = "ex.grpc"; + package helloworld; // The request message containing the user's name. @@ -146,6 +150,7 @@ service Greeting { ``` + ### Generating gRPC code Once we've defined our service, we use the protocol buffer compiler @@ -185,15 +190,103 @@ $ protoc -I . helloworld.proto --java_out=src/main/java ``` -This generates the following Java classes +This generates the following classes, which contain all the generated code we need to create our example: + +- [`Helloworld.java`](java/src/main/java/ex/grpc/Helloworld.java), which has all the protocol buffer code to populate, serialize, and retrieve our `HelloRequest` and `HelloReply` message types +- [`GreetingsGrpc.java`](java/src/main/java/ex/grpc/GreetingsGrpc.java), which contains (along with some other useful code): + - an interface for `Greetings` servers to implement + +``` + public static interface Greetings { + + public void hello(ex.grpc.Helloworld.HelloRequest request, + com.google.net.stubby.stub.StreamObserver responseObserver); + } +``` + + - _stub_ classes that clients can use to talk to a `Greetings` server. + +``` +public static class GreetingsStub extends + com.google.net.stubby.stub.AbstractStub + implements Greetings { + ... + } +``` + +_Does gRPC output multiple Java classes per proto by default?_ + ### Writing a server -Now let's write some code! First we'll create the `Greetings` server. +Now let's write some code! First we'll create a server application to implement our service. Note that we're not going to go into a lot of detail about how to create a server in this section More detailed information will be in the tutorial for your chosen language (coming soon). + +Our server application has two classes: + +- a simple service implementation [GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). + +- a server that hosts the service implementation and allows access over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). + +## Service implementation + +[GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java) +implements the behaviour we require of our GreetingService. There are a +number of important features of gRPC being used here: + +``` + public void hello(Helloworld.HelloRequest req, + StreamObserver responseObserver) { + Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( + "Hello " + req.getName()).build(); + responseObserver.onValue(reply); + responseObserver.onCompleted(); + } +``` + +- it provides a class `GreetingsImpl` that implements a generated interface `GreetingsGrpc.Greetings` +- `GreetingsGrpc.Greetings` declares the method `hello` that was declared in the proto [IDL](src/main/proto/helloworld.proto) +- `hello's` signature is typesafe: + hello(Helloworld.HelloRequest req, StreamObserver responseObserver) +- `hello` takes two parameters: + `Helloworld.HelloRequest`: the request + `StreamObserver`: a response observer, an interface to be called with the response value +- to complete the call + - the return value is constructed + - the responseObserver.onValue() is called with the response + - responseObserver.onCompleted() is called to indicate that no more work will done on the RPC. + -Note that we're not going to go into a lot of detail about how to create a server in this section More detailed information will be in the tutorial for your chosen language (coming soon). +## Server implementation +[GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the +other main feature required to provde the gRPC service; how to allow a service +implementation to be accessed from the network. +``` + private void start() throws Exception { + server = NettyServerBuilder.forPort(port) + .addService(GreetingsGrpc.bindService(new GreetingsImpl())) + .build(); + server.startAsync(); + server.awaitRunning(5, TimeUnit.SECONDS); + } + +``` + +- it provides a class `GreetingsServer` that holds a `ServerImpl` that will run the server +- in the `start` method, `GreetingServer` binds the `GreetingsService` implementation to a port and begins running it +- there is also a `stop` method that takes care of shutting down the service and cleaning up when the program exits + +## Build it + +This is the same as before: our client and server are part of the same maven +package so the same command builds both. + +``` +$ mvn package +``` + + ### Writing a client Client-side gRPC is pretty simple. In this step, we'll use the generated code to write a simple client that can access the `Greetings` server we created in the previous section. You can see the complete client code in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). @@ -267,10 +360,6 @@ It can be built as follows. $ mvn package ``` -It can also be run, but doing so now would end up a with a failure as there is -no server available yet. The [next step](Step_3.md), describes how to -implement, build and run a server that supports the service description. - #### Notes - The client uses a blocking stub. This means that the RPC call waits for the @@ -280,7 +369,23 @@ implement, build and run a server that supports the service description. server, where the response is returned asynchronously. Usage of these stubs is a more advanced topic and will be described in later steps. + +### Try it out! + +We've added simple shell scripts to simplifying running the examples. Now +that they are built, you can run the server with: + +``` +$ ./run_greetings_server.sh +``` + +and in another terminal window confirm that it receives a message. + +``` +$ ./run_greetings_client.sh +``` + + -We haven't looked at implementing a server yet, but From 4a8df2ae35d5864c30d09bd72376dece749c3ff1 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Tue, 10 Feb 2015 16:46:20 +0000 Subject: [PATCH 033/576] Delete Step_0.md Remove separate step now everything's been moved into the main doc --- Step_0.md | 41 ----------------------------------------- 1 file changed, 41 deletions(-) delete mode 100644 Step_0.md diff --git a/Step_0.md b/Step_0.md deleted file mode 100644 index d0745b0dd1f..00000000000 --- a/Step_0.md +++ /dev/null @@ -1,41 +0,0 @@ -# Step-0: define a service - -This section presents an example of a simple service definition that receives -a message from a remote client. The message contains the user's name and -sends back a greeting to that person. - -It's shown below in full; it's actually contained in separate file. -[helloworld.proto](src/main/proto/helloworld.proto). - -``` -syntax = "proto3"; - -package helloworld; - -// The request message containing the user's name. -message HelloRequest { - optional string name = 1; -} - -// The response message containing the greetings -message HelloReply { - optional string message = 1; -} - -// The greeting service definition. -service Greeting { - - // Sends a greeting - rpc hello (HelloRequest) returns (HelloReply) { - } -} - -``` - -The service stanza of the message is an example of protobuf service IDL -(Interface Definition Language). Here, it defines a simple service that -receives a request containing a name and returns a response containing a -message. - -Next, in [Step - 1](Step_1.md), we'll use protoc to generate client code from -this IDL. From baa905deefac19dcd32b2ccedcc53e41b077825a Mon Sep 17 00:00:00 2001 From: LisaFC Date: Tue, 10 Feb 2015 16:46:45 +0000 Subject: [PATCH 034/576] Delete Step_1.md Remove separate step now that all the content has been moved into the main doc --- Step_1.md | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 Step_1.md diff --git a/Step_1.md b/Step_1.md deleted file mode 100644 index c7aed326c38..00000000000 --- a/Step_1.md +++ /dev/null @@ -1,33 +0,0 @@ -# Step-1: Generate a service client. - -In this step, we use protoc to generate the Java Stub classes. A Stub is the -name gRPC uses for the code that initiates contact with a gRPC service running -remotely via the internet. - -If you did not install protoc on your system, you can skip this step and move -onto the next one where we examine the generated code. - -First, you'll need to build the protobuf plugin that generates the rpc -classes. `protoc` uses other tools called plugins to add additional features -to generated code. - -The gRPC Java Stub classes are created using a gRPC Java plugin, but first the -plugin must be built and installed. - -To build the plugin: -``` -$ pushd external/grpc_java -$ make java_plugin -$ popd -``` - -To use it to generate the code: -``` -$ mkdir -p src/main/java -$ protoc -I . helloworld.proto --plugin=protoc-gen-grpc=external/grpc_java/bins/opt/java_plugin \ - --grpc_out=src/main/java \ - --java_out=src/main/java -``` - -Next, in [Step - 2](Step_2.md), we'll use the generated Stub implementation to -write a client that uses the generated code to make a call to a service. From b8d33683de3fa51b45c285b35030e0568420f299 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Tue, 10 Feb 2015 16:47:00 +0000 Subject: [PATCH 035/576] Delete Step_2.md Remove separate step now that all the content has been moved into the main doc --- Step_2.md | 85 ------------------------------------------------------- 1 file changed, 85 deletions(-) delete mode 100644 Step_2.md diff --git a/Step_2.md b/Step_2.md deleted file mode 100644 index eafe70b6923..00000000000 --- a/Step_2.md +++ /dev/null @@ -1,85 +0,0 @@ -# Step-2: Write a service client. - -This step uses the generated code to write a simple client to access the hello -service. The full client is in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). - - -## Configuring the service to connect to. - -The client contains uses a Stub to contact the service. The internet address -is configured in the client constructor. gRPC Channel is the abstraction over -transport handling; its constructor accepts the host name and port of the -service. The channel in turn is used to construct the Stub. - - -``` - private final ChannelImpl channel; - private final GreetingGrpc.GreetingBlockingStub blockingStub; - - public HelloClient(String host, int port) { - channel = NettyChannelBuilder.forAddress(host, port) - .negotiationType(NegotiationType.PLAINTEXT) - .build(); - blockingStub = GreetingGrpc.newBlockingStub(channel); - } - -``` - -## Obtaining a greeting - -The greet method uses the stub to contact the service and obtain a greeting. -It: -- constructs a request -- obtains a reply from the stub -- prints out the greeting - - -``` - public void greet(String name) { - logger.debug("Will try to greet " + name + " ..."); - try { - Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName(name).build(); - Helloworld.HelloReply reply = blockingStub.hello(request); - logger.info("Greeting: " + reply.getMessage()); - } catch (RuntimeException e) { - logger.log(Level.WARNING, "RPC failed", e); - return; - } - } - -``` - -## Running from the command line - -The main method puts together the example so that it can be run from a command -line. - -``` - /* Access a service running on the local machine on port 50051 */ - HelloClient client = new HelloClient("localhost", 50051); - String user = "world"; - if (args.length > 1) { - user = args[1]; - } - client.greet(user); - -``` - -It can be built as follows. - -``` -$ mvn package -``` - -It can also be run, but doing so now would end up a with a failure as there is -no server available yet. The [next step](Step_3.md), describes how to -implement, build and run a server that supports the service description. - -## Notes - -- The client uses a blocking stub. This means that the RPC call waits for the - server to respond, and will either return a response or raise an exception. - -- gRPC Java has other kinds of stubs that make non-blocking calls to the - server, where the response is returned asynchronously. Usage of these stubs - is a more advanced topic and will be described in later steps. From a60ad9e4221046b3444789d67873186cd1dd2103 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Tue, 10 Feb 2015 16:47:10 +0000 Subject: [PATCH 036/576] Delete Step_3.md Remove separate step now that all the content has been moved into the main doc --- Step_3.md | 82 ------------------------------------------------------- 1 file changed, 82 deletions(-) delete mode 100644 Step_3.md diff --git a/Step_3.md b/Step_3.md deleted file mode 100644 index 7b03cdf585f..00000000000 --- a/Step_3.md +++ /dev/null @@ -1,82 +0,0 @@ -# Step-3: Implement a server. - -This step extends the generated server skeleton code to write a simple server -that provides the hello service. This introduces two new classes: - -- a service implementation [GreetingsImpl.java](src/main/java/ex/grpc/GreetingsImpl.java). - -- a server that hosts the service implementation and allows access over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). - -## Service implementation - -[GreetingsImpl.java](src/main/java/ex/grpc/GreetingsImpl.java) -implements the behaviour we require of our GreetingService. There are a -number of important features of gRPC being used here: - -``` - public void hello(Helloworld.HelloRequest req, - StreamObserver responseObserver) { - Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( - "Hello " + req.getName()).build(); - responseObserver.onValue(reply); - responseObserver.onCompleted(); - } -``` - -- it provides a class `GreetingsImpl` that implements a generated interface `GreetingsGrpc.Greetings` -- `GreetingsGrpc.Greetings` declares the method `hello` that was declared in the proto [IDL](src/main/proto/helloworld.proto) -- `hello's` signature is typesafe: - hello(Helloworld.HelloRequest req, StreamObserver responseObserver) -- `hello` takes two parameters: - `Helloworld.HelloRequest`: the request - `StreamObserver`: a response observer, an interface to be called with the response value -- to complete the call - - the return value is constructed - - the responseObserver.onValue() is called with the response - - responseObserver.onCompleted() is called to indicate that no more work will done on the RPC. - - -## Server implementation - -[GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the -other main feature required to provde the gRPC service; how to allow a service -implementation to be accessed from the network. - -``` - private void start() throws Exception { - server = NettyServerBuilder.forPort(port) - .addService(GreetingsGrpc.bindService(new GreetingsImpl())) - .build(); - server.startAsync(); - server.awaitRunning(5, TimeUnit.SECONDS); - } - -``` - -- it provides a class `GreetingsServer` that holds a `ServerImpl` that will run the server -- in the `start` method, `GreetingServer` binds the `GreetingsService` implementation to a port and begins running it -- there is also a `stop` method that takes care of shutting down the service and cleaning up when the program exits - -## Build it - -This is the same as before: our client and server are part of the same maven -package so the same command builds both. - -``` -$ mvn package -``` - -## Try them out - -We've added simple shell scripts to simplifying running the examples. Now -that they are built, you can run the server with: - -``` -$ ./run_greetings_server.sh -``` - -and in another terminal window confirm that it receives a message. - -``` -$ ./run_greetings_client.sh -``` From 874bff090a0231940e0c60e6520f80d3834b91f3 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 10 Feb 2015 16:47:41 +0000 Subject: [PATCH 037/576] Minor formatting tweaks --- README.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3a2f3c85551..61ff9a5e97d 100644 --- a/README.md +++ b/README.md @@ -227,7 +227,7 @@ Our server application has two classes: - a server that hosts the service implementation and allows access over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). -## Service implementation +#### Service implementation [GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java) implements the behaviour we require of our GreetingService. There are a @@ -256,7 +256,7 @@ number of important features of gRPC being used here: - responseObserver.onCompleted() is called to indicate that no more work will done on the RPC. -## Server implementation +#### Server implementation [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the other main feature required to provde the gRPC service; how to allow a service @@ -277,15 +277,16 @@ implementation to be accessed from the network. - in the `start` method, `GreetingServer` binds the `GreetingsService` implementation to a port and begins running it - there is also a `stop` method that takes care of shutting down the service and cleaning up when the program exits -## Build it +#### Build it -This is the same as before: our client and server are part of the same maven -package so the same command builds both. +Once we've implemented everything, we use Maven to build the server: ``` $ mvn package ``` +We'll look at using a client to access the server in the next section. + ### Writing a client @@ -354,7 +355,10 @@ line. ``` -It can be built as follows. +#### Build the client + +This is the same as before: our client and server are part of the same maven +package so the same command builds both. ``` $ mvn package From d7e29f4b313faa71acd2cee5f46ca9fc380e9c3d Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Wed, 11 Feb 2015 13:14:16 +0000 Subject: [PATCH 038/576] Implementing Tim's edits --- README.md | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 61ff9a5e97d..c7c896db61d 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Hello World method. - Create a Go client that accesses the same Java server. - Update the service with more advanced features like RPC streaming. -The complete code for the example is available in [wherever we put it]. You can +The complete code for the example is available in the `grpc-common` GitHub repository. You can work along with the example and hack on the code in the comfort of your own computer, giving you hands-on practice of really writing gRPC code. We use the Git versioning system for source code management: @@ -174,7 +174,7 @@ to generated code. As we're creating Java code, we use the gRPC Java plugin. To build the plugin: -``` +```sh $ pushd external/grpc_java $ make java_plugin $ popd @@ -182,7 +182,7 @@ $ popd To use it to generate the code: -``` +```sh $ mkdir -p src/main/java $ protoc -I . helloworld.proto --plugin=protoc-gen-grpc=external/grpc_java/bins/opt/java_plugin \ @@ -194,27 +194,25 @@ This generates the following classes, which contain all the generated code we ne - [`Helloworld.java`](java/src/main/java/ex/grpc/Helloworld.java), which has all the protocol buffer code to populate, serialize, and retrieve our `HelloRequest` and `HelloReply` message types - [`GreetingsGrpc.java`](java/src/main/java/ex/grpc/GreetingsGrpc.java), which contains (along with some other useful code): - - an interface for `Greetings` servers to implement + - an interface for `Greetings` servers to implement -``` + ```java public static interface Greetings { public void hello(ex.grpc.Helloworld.HelloRequest request, com.google.net.stubby.stub.StreamObserver responseObserver); } -``` + ``` - - _stub_ classes that clients can use to talk to a `Greetings` server. + - _stub_ classes that clients can use to talk to a `Greetings` server. -``` + ```java public static class GreetingsStub extends com.google.net.stubby.stub.AbstractStub implements Greetings { ... } -``` - -_Does gRPC output multiple Java classes per proto by default?_ + ``` ### Writing a server @@ -233,7 +231,7 @@ Our server application has two classes: implements the behaviour we require of our GreetingService. There are a number of important features of gRPC being used here: -``` +```java public void hello(Helloworld.HelloRequest req, StreamObserver responseObserver) { Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( @@ -262,7 +260,7 @@ number of important features of gRPC being used here: other main feature required to provde the gRPC service; how to allow a service implementation to be accessed from the network. -``` +```java private void start() throws Exception { server = NettyServerBuilder.forPort(port) .addService(GreetingsGrpc.bindService(new GreetingsImpl())) @@ -302,7 +300,7 @@ transport handling; its constructor accepts the host name and port of the service. The channel in turn is used to construct the Stub. -``` +```java private final ChannelImpl channel; private final GreetingGrpc.GreetingBlockingStub blockingStub; @@ -324,7 +322,7 @@ It: - prints out the greeting -``` +```java public void greet(String name) { logger.debug("Will try to greet " + name + " ..."); try { @@ -344,7 +342,7 @@ It: The main method puts together the example so that it can be run from a command line. -``` +```java /* Access a service running on the local machine on port 50051 */ HelloClient client = new HelloClient("localhost", 50051); String user = "world"; @@ -379,13 +377,13 @@ $ mvn package We've added simple shell scripts to simplifying running the examples. Now that they are built, you can run the server with: -``` +```sh $ ./run_greetings_server.sh ``` and in another terminal window confirm that it receives a message. -``` +```sh $ ./run_greetings_client.sh ``` From 8e9a709d47fcf79379cb04fa0d98a03f5915f8b4 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Thu, 12 Feb 2015 17:48:42 +0000 Subject: [PATCH 039/576] More tidying up of example... --- README.md | 70 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 44 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index c7c896db61d..bd0738447a8 100644 --- a/README.md +++ b/README.md @@ -118,10 +118,11 @@ familiar with protocol buffers, you can find out more in the [Protocol Buffers Developer Guide](https://developers.google.com/protocol-buffers/docs/overview). Here's our example service definition, defined using protocol buffers IDL in -[helloworld.proto](java/src/main/proto/helloworld.proto) _should we link to the version in the Java subdirectory or the one in the common protos directory?_. The `Greeting` service +[helloworld.proto](java/src/main/proto/helloworld.proto). The `Greeting` service has one method, `hello`, that lets the server receive a single `HelloRequest` message from the remote client containing the user's name, then send back -a greeting in a `HelloReply`. +a greeting in a single `HelloReply`. This is the simplest type of RPC you +can specify in gRPC - we'll look at some other types later in this document. ``` syntax = "proto3"; @@ -167,7 +168,8 @@ this up in "what is gRPC"?] the example, you can skip this step and move onto the next one where we examine the generated code.) -As this is our first time using gRPC, we need to build the protobuf plugin that generates our RPC +As this is our first time using gRPC, we need to build the protobuf plugin +that generates our RPC classes. By default `protoc` just generates code for reading and writing protocol buffers, so you need to use plugins to add additional features to generated code. As we're creating Java code, we use the gRPC Java plugin. @@ -190,17 +192,22 @@ $ protoc -I . helloworld.proto --java_out=src/main/java ``` -This generates the following classes, which contain all the generated code we need to create our example: +This generates the following classes, which contain all the generated code +we need to create our example: -- [`Helloworld.java`](java/src/main/java/ex/grpc/Helloworld.java), which has all the protocol buffer code to populate, serialize, and retrieve our `HelloRequest` and `HelloReply` message types -- [`GreetingsGrpc.java`](java/src/main/java/ex/grpc/GreetingsGrpc.java), which contains (along with some other useful code): +- [`Helloworld.java`](java/src/main/java/ex/grpc/Helloworld.java), which +has all the protocol buffer code to populate, serialize, and retrieve our +`HelloRequest` and `HelloReply` message types +- [`GreetingsGrpc.java`](java/src/main/java/ex/grpc/GreetingsGrpc.java), +which contains (along with some other useful code): - an interface for `Greetings` servers to implement ```java public static interface Greetings { public void hello(ex.grpc.Helloworld.HelloRequest request, - com.google.net.stubby.stub.StreamObserver responseObserver); + com.google.net.stubby.stub.StreamObserver + responseObserver); } ``` @@ -208,7 +215,8 @@ This generates the following classes, which contain all the generated code we ne ```java public static class GreetingsStub extends - com.google.net.stubby.stub.AbstractStub + com.google.net.stubby.stub.AbstractStub implements Greetings { ... } @@ -217,48 +225,58 @@ public static class GreetingsStub extends ### Writing a server -Now let's write some code! First we'll create a server application to implement our service. Note that we're not going to go into a lot of detail about how to create a server in this section More detailed information will be in the tutorial for your chosen language (coming soon). +Now let's write some code! First we'll create a server application to implement +our service. Note that we're not going to go into a lot of detail about how +to create a server in this section More detailed information will be in the +tutorial for your chosen language (coming soon). Our server application has two classes: -- a simple service implementation [GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). +- a simple service implementation +[GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). -- a server that hosts the service implementation and allows access over the network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). +- a server that hosts the service implementation and allows access over the +network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). #### Service implementation [GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java) -implements the behaviour we require of our GreetingService. There are a -number of important features of gRPC being used here: +actually implements our GreetingService's required behaviour. + +As you can see, the class `GreetingsImpl` implements the interface +`GreetingsGrpc.Greetings` that we [generated](#generating) from our proto +[IDL](src/main/proto/helloworld.proto) by implementing the method `hello`: ```java public void hello(Helloworld.HelloRequest req, StreamObserver responseObserver) { - Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( + Helloworld.HelloReply reply = + Helloworld.HelloReply.newBuilder().setMessage( "Hello " + req.getName()).build(); responseObserver.onValue(reply); responseObserver.onCompleted(); } ``` - -- it provides a class `GreetingsImpl` that implements a generated interface `GreetingsGrpc.Greetings` -- `GreetingsGrpc.Greetings` declares the method `hello` that was declared in the proto [IDL](src/main/proto/helloworld.proto) - `hello's` signature is typesafe: - hello(Helloworld.HelloRequest req, StreamObserver responseObserver) + `hello(Helloworld.HelloRequest req, StreamObserver + responseObserver)` - `hello` takes two parameters: - `Helloworld.HelloRequest`: the request - `StreamObserver`: a response observer, an interface to be called with the response value -- to complete the call - - the return value is constructed - - the responseObserver.onValue() is called with the response - - responseObserver.onCompleted() is called to indicate that no more work will done on the RPC. + -`Helloworld.HelloRequest`: the request + -`StreamObserver`: a response observer, which is + a special interface for the server to call with its response +To return our response to the client and complete the call: +1. We construct and populate a `HelloReply` response object with our exciting +message, as specified in our interface definition. +2. We call `responseObserver.onValue()` with the `HelloReply` that we want to send back to the client. +3. Finally, we call `responseObserver.onCompleted()` to indicate that we're +finished dealing with this RPC. #### Server implementation [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the -other main feature required to provde the gRPC service; how to allow a service -implementation to be accessed from the network. +other main feature required to provde the gRPC service; making the service +implementation available from the network. ```java private void start() throws Exception { From 2fdb96388faa6ef94fd768ba921dcf0a3ffe9a39 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Thu, 12 Feb 2015 17:51:13 +0000 Subject: [PATCH 040/576] Style tweaks --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bd0738447a8..89e8d2942c3 100644 --- a/README.md +++ b/README.md @@ -264,11 +264,12 @@ As you can see, the class `GreetingsImpl` implements the interface -`Helloworld.HelloRequest`: the request -`StreamObserver`: a response observer, which is a special interface for the server to call with its response + To return our response to the client and complete the call: -1. We construct and populate a `HelloReply` response object with our exciting + 1. We construct and populate a `HelloReply` response object with our exciting message, as specified in our interface definition. -2. We call `responseObserver.onValue()` with the `HelloReply` that we want to send back to the client. -3. Finally, we call `responseObserver.onCompleted()` to indicate that we're + 2. We call `responseObserver.onValue()` with the `HelloReply` that we want to send back to the client. + 3. Finally, we call `responseObserver.onCompleted()` to indicate that we're finished dealing with this RPC. From 034eb2e8097262ee9a6a543f47ab9baa15a92b92 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 11:05:25 +0000 Subject: [PATCH 041/576] Markdown, I hate you. --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 89e8d2942c3..cc0ce4943fd 100644 --- a/README.md +++ b/README.md @@ -213,14 +213,14 @@ which contains (along with some other useful code): - _stub_ classes that clients can use to talk to a `Greetings` server. - ```java +```java public static class GreetingsStub extends com.google.net.stubby.stub.AbstractStub implements Greetings { ... } - ``` +``` ### Writing a server @@ -266,6 +266,7 @@ As you can see, the class `GreetingsImpl` implements the interface a special interface for the server to call with its response To return our response to the client and complete the call: + 1. We construct and populate a `HelloReply` response object with our exciting message, as specified in our interface definition. 2. We call `responseObserver.onValue()` with the `HelloReply` that we want to send back to the client. From 31d143ce0745b485b315c56c1715dc46fe060a5e Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 11:07:16 +0000 Subject: [PATCH 042/576] AAAAAAARRRGHHHHH --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index cc0ce4943fd..16304f65eb3 100644 --- a/README.md +++ b/README.md @@ -213,14 +213,14 @@ which contains (along with some other useful code): - _stub_ classes that clients can use to talk to a `Greetings` server. -```java + ```java public static class GreetingsStub extends com.google.net.stubby.stub.AbstractStub implements Greetings { ... } -``` + ``` ### Writing a server @@ -267,10 +267,10 @@ As you can see, the class `GreetingsImpl` implements the interface To return our response to the client and complete the call: - 1. We construct and populate a `HelloReply` response object with our exciting +1. We construct and populate a `HelloReply` response object with our exciting message, as specified in our interface definition. - 2. We call `responseObserver.onValue()` with the `HelloReply` that we want to send back to the client. - 3. Finally, we call `responseObserver.onCompleted()` to indicate that we're +2. We call `responseObserver.onValue()` with the `HelloReply` that we want to send back to the client. +3. Finally, we call `responseObserver.onCompleted()` to indicate that we're finished dealing with this RPC. From 0af588a9cf75fd5769bb3bca5a978a3463f80668 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 15:42:03 +0000 Subject: [PATCH 043/576] More tidying up of existing text --- README.md | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 16304f65eb3..8f6fd5cc6d5 100644 --- a/README.md +++ b/README.md @@ -211,7 +211,7 @@ which contains (along with some other useful code): } ``` - - _stub_ classes that clients can use to talk to a `Greetings` server. + - _stub_ classes that clients can use to talk to a `Greetings` server. As you can see, they also implement the `Greetings` interface. ```java public static class GreetingsStub extends @@ -236,7 +236,7 @@ Our server application has two classes: [GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). - a server that hosts the service implementation and allows access over the -network: [GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java). +network: [GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java). #### Service implementation @@ -245,7 +245,7 @@ actually implements our GreetingService's required behaviour. As you can see, the class `GreetingsImpl` implements the interface `GreetingsGrpc.Greetings` that we [generated](#generating) from our proto -[IDL](src/main/proto/helloworld.proto) by implementing the method `hello`: +[IDL](java/src/main/proto/helloworld.proto) by implementing the method `hello`: ```java public void hello(Helloworld.HelloRequest req, @@ -276,11 +276,13 @@ finished dealing with this RPC. #### Server implementation -[GreetingsServer.java](src/main/java/ex/grpc/GreetingsServer.java) shows the -other main feature required to provde the gRPC service; making the service +[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) shows the +other main feature required to provide a gRPC service; making the service implementation available from the network. ```java + private ServerImpl server; + ... private void start() throws Exception { server = NettyServerBuilder.forPort(port) .addService(GreetingsGrpc.bindService(new GreetingsImpl())) @@ -291,9 +293,9 @@ implementation available from the network. ``` -- it provides a class `GreetingsServer` that holds a `ServerImpl` that will run the server -- in the `start` method, `GreetingServer` binds the `GreetingsService` implementation to a port and begins running it -- there is also a `stop` method that takes care of shutting down the service and cleaning up when the program exits +The `GreetingsServer` class has a `ServerImpl` member that actually runs the server. To create an appropriate `ServerImpl`, we use a special `ServerBuilder` class (in this case a `NettyServerBuilder`) in the `GreetingsServer`'s `start` method, binding the `GreetingsService` implementation that we created to a port. Then we start the server running: the server is now ready to receive requests from `Greetings` service clients on our specified port. We'll cover how all this works in a bit more detail in our language-specific documentation. + +`GreetingsServer` also has a `stop` method that takes care of shutting down the service and cleaning up when the program exits. #### Build it @@ -308,16 +310,16 @@ We'll look at using a client to access the server in the next section. ### Writing a client -Client-side gRPC is pretty simple. In this step, we'll use the generated code to write a simple client that can access the `Greetings` server we created in the previous section. You can see the complete client code in [GreetingsClient.java](src/main/java/ex/grpc/GreetingsClient.java). +Client-side gRPC is pretty simple. In this step, we'll use the generated code to write a simple client that can access the `Greetings` server we created in the [previous section](#server). You can see the complete client code in [GreetingsClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). Again, we're not going to go into much detail about how to implement a client - we'll leave that for the tutorial. #### Connecting to the service -. The internet address -is configured in the client constructor. gRPC Channel is the abstraction over +First let's look at how we connect to the `Greetings` server. The internet address +is configured in the client constructor. gRPC `Channel` provides the abstraction layer over transport handling; its constructor accepts the host name and port of the -service. The channel in turn is used to construct the Stub. +service. The channel in turn is used to construct the stub instance. ```java @@ -335,11 +337,11 @@ service. The channel in turn is used to construct the Stub. #### Obtaining a greeting -The greet method uses the stub to contact the service and obtain a greeting. -It: -- constructs a request -- obtains a reply from the stub -- prints out the greeting +The `greet()` method uses the stub to contact the service and obtain a greeting. +In the method we: +- construct and fill in a `HelloRequest` to send to the stub +- get a reply from the stub +- print out the greeting ```java @@ -375,7 +377,7 @@ line. #### Build the client -This is the same as before: our client and server are part of the same maven +This is the same as building the server: our client and server are part of the same maven package so the same command builds both. ``` @@ -407,6 +409,10 @@ and in another terminal window confirm that it receives a message. $ ./run_greetings_client.sh ``` +### Adding another client + +###TODO: Section on Go client for same server + From 26e6d380abce8fd667597acb0c7f785e33beac79 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 15:45:10 +0000 Subject: [PATCH 044/576] Bit of tidying up... --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8f6fd5cc6d5..72a8de9eb06 100644 --- a/README.md +++ b/README.md @@ -338,10 +338,10 @@ service. The channel in turn is used to construct the stub instance. #### Obtaining a greeting The `greet()` method uses the stub to contact the service and obtain a greeting. -In the method we: -- construct and fill in a `HelloRequest` to send to the stub -- get a reply from the stub -- print out the greeting +To do this: + +1. We construct and fill in a `HelloRequest` to send to the stub. +2. We call the RPC with our request and get a `HelloReply` from the stub, from which we can get our greeting. ```java From 27da19feb43157260195732a8f63a5bc3545475b Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 15:58:20 +0000 Subject: [PATCH 045/576] Bit more tidying up --- README.md | 57 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 72a8de9eb06..e3719357ea5 100644 --- a/README.md +++ b/README.md @@ -276,8 +276,8 @@ finished dealing with this RPC. #### Server implementation -[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) shows the -other main feature required to provide a gRPC service; making the service +[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) +shows the other main feature required to provide a gRPC service; making the service implementation available from the network. ```java @@ -293,9 +293,16 @@ implementation available from the network. ``` -The `GreetingsServer` class has a `ServerImpl` member that actually runs the server. To create an appropriate `ServerImpl`, we use a special `ServerBuilder` class (in this case a `NettyServerBuilder`) in the `GreetingsServer`'s `start` method, binding the `GreetingsService` implementation that we created to a port. Then we start the server running: the server is now ready to receive requests from `Greetings` service clients on our specified port. We'll cover how all this works in a bit more detail in our language-specific documentation. +The `GreetingsServer` class has a `ServerImpl` member that actually runs the +server. To create an appropriate `ServerImpl`, we use a special `ServerBuilder` +class (in this case a `NettyServerBuilder`) in the `GreetingsServer`'s `start` +method, binding the `GreetingsService` implementation that we created to a +port. Then we start the server running: the server is now ready to receive +requests from `Greetings` service clients on our specified port. We'll cover +how all this works in a bit more detail in our language-specific documentation. -`GreetingsServer` also has a `stop` method that takes care of shutting down the service and cleaning up when the program exits. +`GreetingsServer` also has a `stop` method that takes care of shutting down +the service and cleaning up when the program exits. #### Build it @@ -310,14 +317,20 @@ We'll look at using a client to access the server in the next section. ### Writing a client -Client-side gRPC is pretty simple. In this step, we'll use the generated code to write a simple client that can access the `Greetings` server we created in the [previous section](#server). You can see the complete client code in [GreetingsClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). +Client-side gRPC is pretty simple. In this step, we'll use the generated code +to write a simple client that can access the `Greetings` server we created +in the [previous section](#server). You can see the complete client code in +[GreetingsClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). -Again, we're not going to go into much detail about how to implement a client - we'll leave that for the tutorial. +Again, we're not going to go into much detail about how to implement a client +- we'll leave that for the tutorial. #### Connecting to the service -First let's look at how we connect to the `Greetings` server. The internet address -is configured in the client constructor. gRPC `Channel` provides the abstraction layer over +First let's look at how we connect to the `Greetings` server. The internet +address +is configured in the client constructor. gRPC `Channel` provides the +abstraction layer over transport handling; its constructor accepts the host name and port of the service. The channel in turn is used to construct the stub instance. @@ -335,20 +348,28 @@ service. The channel in turn is used to construct the stub instance. ``` +In this case, we create a blocking stub. This means that the RPC call waits +for the server to respond, and will either return a response or raise an +exception. gRPC Java has other kinds of stubs that make non-blocking calls +to the server, where the response is returned asynchronously. + #### Obtaining a greeting -The `greet()` method uses the stub to contact the service and obtain a greeting. +The `greet()` method uses the stub to contact the service and obtain +a greeting. To do this: 1. We construct and fill in a `HelloRequest` to send to the stub. -2. We call the RPC with our request and get a `HelloReply` from the stub, from which we can get our greeting. +2. We call the RPC with our request and get a `HelloReply` from the stub, +from which we can get our greeting. ```java public void greet(String name) { logger.debug("Will try to greet " + name + " ..."); try { - Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName(name).build(); + Helloworld.HelloRequest request = + Helloworld.HelloRequest.newBuilder().setName(name).build(); Helloworld.HelloReply reply = blockingStub.hello(request); logger.info("Greeting: " + reply.getMessage()); } catch (RuntimeException e) { @@ -377,22 +398,14 @@ line. #### Build the client -This is the same as building the server: our client and server are part of the same maven +This is the same as building the server: our client and server are part of +the same maven package so the same command builds both. ``` $ mvn package ``` -#### Notes - -- The client uses a blocking stub. This means that the RPC call waits for the - server to respond, and will either return a response or raise an exception. - -- gRPC Java has other kinds of stubs that make non-blocking calls to the - server, where the response is returned asynchronously. Usage of these stubs - is a more advanced topic and will be described in later steps. - ### Try it out! @@ -409,7 +422,7 @@ and in another terminal window confirm that it receives a message. $ ./run_greetings_client.sh ``` -### Adding another client +### Adding another client ###TODO: Section on Go client for same server From 461780145938e452e113f4eb951c3a28ff69b214 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 16:38:49 +0000 Subject: [PATCH 046/576] Starting intro --- README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/README.md b/README.md index e3719357ea5..592e1663f73 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,33 @@ Hello World example. More documentation is coming soon! ## What is gRPC? +gRPC is It enables communication between clients and servers using any combination of gRPC's supported languages, helping you to build distributed applications and services. + +In gRPC, like + +### Plays well with Protocol Buffers + +While gRPC’s architecture allows it to be extended for use with other +data formats such as JSON, by default it uses protocol buffers, Google’s +mature open source mechanism for serializing structured data. As you'll +see in our example below, you define gRPC interfaces using proto files and +protocol buffer messages, letting you take advantage of protocol buffers’ +efficient serialization, simple IDL, and easy interface updating. You +can find out lots more about protocol buffers in the [Protocol Buffers +documentation](https://developers.google.com/protocol-buffers/docs/overview). + +Note that our examples use a new flavour of protocol buffers called proto3, +which has a slightly simplified syntax, some useful new features, and supports +lots more languages. This is currently available as an alpha release in +[languages] from [wherever it's going], with more languages in development. In +general, we recommend that you use proto3 with gRPC as it lets you use the +full range of gRPC-supported languages, as well as avoiding any compatibility +issues with proto2 clients talking to proto3 servers and vice versa. + +If you need to continue using proto2 for Java, C++, or Python but want +to try gRPC, you can see an example using a proto2 gRPC client and server +[wherever we put it]. + ## TODO: basic conceptual intro (anything more in-depth will go in gRPC Concepts doc) From bdcda72cec23554d5ef1dd5695de9e97e8bb3235 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 16:40:23 +0000 Subject: [PATCH 047/576] Fixed typo --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 592e1663f73..413f5008a2f 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@ Hello World example. More documentation is coming soon! ## What is gRPC? -gRPC is It enables communication between clients and servers using any combination of gRPC's supported languages, helping you to build distributed applications and services. +gRPC enables communication between clients and servers using any combination of gRPC's supported languages, helping you to build distributed applications and services. -In gRPC, like +In gRPC, like other RPC systems... ### Plays well with Protocol Buffers @@ -46,7 +46,7 @@ Now that you know a bit more about gRPC, the easiest way to see how it works is to look at a simple example. Our Hello World walks you through the construction of a simple gRPC client-server application, showing you how to: -- Create a protobuf schema that defines a simple RPC service with a single +- Create a protocol buffers schema that defines a simple RPC service with a single Hello World method. - Create a Java server that implements the schema interface. - Create a Java client that accesses the Java server. From 907119eafd930085c8067e7bdaabbe294cef9605 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 13 Feb 2015 16:52:03 +0000 Subject: [PATCH 048/576] Intro tweaks --- README.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 413f5008a2f..2d3a3a8f5b5 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,7 @@ Hello World example. More documentation is coming soon! ## What is gRPC? -gRPC enables communication between clients and servers using any combination of gRPC's supported languages, helping you to build distributed applications and services. - -In gRPC, like other RPC systems... +In gRPC, like other RPC systems, a *client* application can directly call methods on a *server* application on a different machine as if it was a local object, making it easier for you to create distributed applications and services. gRPC clients and servers can run and talk to each other in a variety of environments - from servers inside Google to your own desktop - and can be written in any of gRPC's supported languages. So, for example, you can easily create a gRPC server in Java with clients in Go, Python, or Ruby. ### Plays well with Protocol Buffers @@ -68,9 +66,8 @@ languages are coming soon. ### Setup -The rest of this page explains how to set up your local machine to work with -the example code. -If you just want to read the example, you can go straight to the [next step](#servicedef). +This section explains how to set up your local machine to work with +the example code. If you just want to read the example, you can go straight to the [next step](#servicedef). #### Install Git From e82f310a440c75e5234c4aa6b0028ec5b550d8df Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 17 Feb 2015 16:27:51 +0000 Subject: [PATCH 049/576] Added a simple overview/protocol buffers information --- README.md | 45 ++++++++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 2d3a3a8f5b5..a1575392e02 100644 --- a/README.md +++ b/README.md @@ -10,32 +10,34 @@ Hello World example. More documentation is coming soon! ## What is gRPC? -In gRPC, like other RPC systems, a *client* application can directly call methods on a *server* application on a different machine as if it was a local object, making it easier for you to create distributed applications and services. gRPC clients and servers can run and talk to each other in a variety of environments - from servers inside Google to your own desktop - and can be written in any of gRPC's supported languages. So, for example, you can easily create a gRPC server in Java with clients in Go, Python, or Ruby. +In gRPC, like other RPC systems, a *client* application can directly call methods on a *server* application on a different machine as if it was a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a *service*, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a *stub* that provides exactly the same methods as the server. -### Plays well with Protocol Buffers +##TODO: diagram? + +gRPC clients and servers can run and talk to each other in a variety of environments - from servers inside Google to your own desktop - and can be written in any of gRPC's [supported languages](link to list). So, for example, you can easily create a gRPC server in Java with clients in Go, Python, or Ruby. In addition, the latest Google APIs will have gRPC versions of their interfaces, letting you easily build Google functionality into your applications. + + +### Working with protocol buffers While gRPC’s architecture allows it to be extended for use with other -data formats such as JSON, by default it uses protocol buffers, Google’s +data formats such as JSON, by default it uses *protocol buffers*, Google’s mature open source mechanism for serializing structured data. As you'll -see in our example below, you define gRPC interfaces using proto files and -protocol buffer messages, letting you take advantage of protocol buffers’ -efficient serialization, simple IDL, and easy interface updating. You -can find out lots more about protocol buffers in the [Protocol Buffers -documentation](https://developers.google.com/protocol-buffers/docs/overview). +see in our example below, you define gRPC services using *proto files*, with method parameters and return types specified as protocol buffer message types. You +can find out lots more about protocol buffers in the [Protocol Buffers documentation](https://developers.google.com/protocol-buffers/docs/overview). + +#### Protocol buffer versions -Note that our examples use a new flavour of protocol buffers called proto3, +While protocol buffers have been available for open source users for some time, our examples use a new flavour of protocol buffers called proto3, which has a slightly simplified syntax, some useful new features, and supports lots more languages. This is currently available as an alpha release in -[languages] from [wherever it's going], with more languages in development. In -general, we recommend that you use proto3 with gRPC as it lets you use the -full range of gRPC-supported languages, as well as avoiding any compatibility -issues with proto2 clients talking to proto3 servers and vice versa. +[languages] from [wherever it's going], with more languages in development. -If you need to continue using proto2 for Java, C++, or Python but want +In general, we recommend that you use proto3 with gRPC as it lets you use the +full range of gRPC-supported languages, as well as avoiding compatibility +issues with proto2 clients talking to proto3 servers and vice versa. You can find out more about these potential issues in [where should we put this info? It's important but not really part of an overview]. If you need to continue using proto2 for Java, C++, or Python but want to try gRPC, you can see an example using a proto2 gRPC client and server [wherever we put it]. -## TODO: basic conceptual intro (anything more in-depth will go in gRPC Concepts doc) ## Hello gRPC! @@ -46,9 +48,9 @@ construction of a simple gRPC client-server application, showing you how to: - Create a protocol buffers schema that defines a simple RPC service with a single Hello World method. -- Create a Java server that implements the schema interface. +- Create a Java server that implements thid interface. - Create a Java client that accesses the Java server. -- Create a Go client that accesses the same Java server. +- Create a [probably need a different language now] client that accesses the same Java server. - Update the service with more advanced features like RPC streaming. The complete code for the example is available in the `grpc-common` GitHub repository. You can @@ -134,12 +136,9 @@ with generating the code yourself, download and install protoc from its The first step in creating our example is to define a *service*: an RPC service specifies the methods that can be called remotely with their parameters -and return types. In gRPC, we use the protocol buffers interface definition -language (IDL) to define our service methods, and the parameters and return -types are defined as protocol buffer message types. Both the client and the -server use interface code generated from the service definition. If you're not -familiar with protocol buffers, you can find out more in the [Protocol Buffers -Developer Guide](https://developers.google.com/protocol-buffers/docs/overview). +and return types. As you saw in the [overview](#protocolbuffers) above, gRPC does this using [protocol buffers]((https://developers.google.com/protocol-buffers/docs/overview). We use the protocol buffers interface definition language (IDL) to define our service methods, and define the parameters and return +types as protocol buffer message types. Both the client and the +server use interface code generated from the service definition. Here's our example service definition, defined using protocol buffers IDL in [helloworld.proto](java/src/main/proto/helloworld.proto). The `Greeting` service From e416242fe1fcf43c95496c10da28a0131d102457 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 17 Feb 2015 16:30:13 +0000 Subject: [PATCH 050/576] Tidy formatting --- README.md | 46 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index a1575392e02..1820becdf06 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,24 @@ Hello World example. More documentation is coming soon! ## What is gRPC? -In gRPC, like other RPC systems, a *client* application can directly call methods on a *server* application on a different machine as if it was a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a *service*, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a *stub* that provides exactly the same methods as the server. +In gRPC, like other RPC systems, a *client* application can directly call +methods on a *server* application on a different machine as if it was a +local object, making it easier for you to create distributed applications and +services. As in many RPC systems, gRPC is based around the idea of defining +a *service*, specifying the methods that can be called remotely with their +parameters and return types. On the server side, the server implements this +interface and runs a gRPC server to handle client calls. On the client side, +the client has a *stub* that provides exactly the same methods as the server. ##TODO: diagram? -gRPC clients and servers can run and talk to each other in a variety of environments - from servers inside Google to your own desktop - and can be written in any of gRPC's [supported languages](link to list). So, for example, you can easily create a gRPC server in Java with clients in Go, Python, or Ruby. In addition, the latest Google APIs will have gRPC versions of their interfaces, letting you easily build Google functionality into your applications. +gRPC clients and servers can run and talk to each other in a variety of +environments - from servers inside Google to your own desktop - and can +be written in any of gRPC's [supported languages](link to list). So, for +example, you can easily create a gRPC server in Java with clients in Go, +Python, or Ruby. In addition, the latest Google APIs will have gRPC versions +of their interfaces, letting you easily build Google functionality into +your applications. ### Working with protocol buffers @@ -22,19 +35,26 @@ gRPC clients and servers can run and talk to each other in a variety of environm While gRPC’s architecture allows it to be extended for use with other data formats such as JSON, by default it uses *protocol buffers*, Google’s mature open source mechanism for serializing structured data. As you'll -see in our example below, you define gRPC services using *proto files*, with method parameters and return types specified as protocol buffer message types. You -can find out lots more about protocol buffers in the [Protocol Buffers documentation](https://developers.google.com/protocol-buffers/docs/overview). +see in our example below, you define gRPC services using *proto files*, +with method parameters and return types specified as protocol buffer message +types. You +can find out lots more about protocol buffers in the [Protocol Buffers +documentation](https://developers.google.com/protocol-buffers/docs/overview). #### Protocol buffer versions -While protocol buffers have been available for open source users for some time, our examples use a new flavour of protocol buffers called proto3, +While protocol buffers have been available for open source users for some +time, our examples use a new flavour of protocol buffers called proto3, which has a slightly simplified syntax, some useful new features, and supports lots more languages. This is currently available as an alpha release in [languages] from [wherever it's going], with more languages in development. In general, we recommend that you use proto3 with gRPC as it lets you use the full range of gRPC-supported languages, as well as avoiding compatibility -issues with proto2 clients talking to proto3 servers and vice versa. You can find out more about these potential issues in [where should we put this info? It's important but not really part of an overview]. If you need to continue using proto2 for Java, C++, or Python but want +issues with proto2 clients talking to proto3 servers and vice versa. You +can find out more about these potential issues in [where should we put this +info? It's important but not really part of an overview]. If you need to +continue using proto2 for Java, C++, or Python but want to try gRPC, you can see an example using a proto2 gRPC client and server [wherever we put it]. @@ -83,9 +103,11 @@ the code to hack on #### Get the source code -The example code for this and our other examples lives in the `grpc-common` GitHub repository. Clone this repository to your local machine by running the +The example code for this and our other examples lives in the `grpc-common` +GitHub repository. Clone this repository to your local machine by running the following command: + ``` git clone https://github.com/google/grpc-common.git ``` @@ -136,13 +158,17 @@ with generating the code yourself, download and install protoc from its The first step in creating our example is to define a *service*: an RPC service specifies the methods that can be called remotely with their parameters -and return types. As you saw in the [overview](#protocolbuffers) above, gRPC does this using [protocol buffers]((https://developers.google.com/protocol-buffers/docs/overview). We use the protocol buffers interface definition language (IDL) to define our service methods, and define the parameters and return +and return types. As you saw in the +[overview](#protocolbuffers) above, gRPC does this using [protocol +buffers]((https://developers.google.com/protocol-buffers/docs/overview). We +use the protocol buffers interface definition language (IDL) to define our +service methods, and define the parameters and return types as protocol buffer message types. Both the client and the server use interface code generated from the service definition. Here's our example service definition, defined using protocol buffers IDL in -[helloworld.proto](java/src/main/proto/helloworld.proto). The `Greeting` service -has one method, `hello`, that lets the server receive a single `HelloRequest` +[helloworld.proto](java/src/main/proto/helloworld.proto). The `Greeting` +service has one method, `hello`, that lets the server receive a single `HelloRequest` message from the remote client containing the user's name, then send back a greeting in a single `HelloReply`. This is the simplest type of RPC you can specify in gRPC - we'll look at some other types later in this document. From b789acd2d2ce0d94064527c2890db4887140616f Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 17 Feb 2015 16:41:45 +0000 Subject: [PATCH 051/576] Fixed typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1820becdf06..fdbd1f0de02 100644 --- a/README.md +++ b/README.md @@ -160,7 +160,7 @@ The first step in creating our example is to define a *service*: an RPC service specifies the methods that can be called remotely with their parameters and return types. As you saw in the [overview](#protocolbuffers) above, gRPC does this using [protocol -buffers]((https://developers.google.com/protocol-buffers/docs/overview). We +buffers](https://developers.google.com/protocol-buffers/docs/overview). We use the protocol buffers interface definition language (IDL) to define our service methods, and define the parameters and return types as protocol buffer message types. Both the client and the From 23307f261c68a9b1f85892720f697d44df1fc06d Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 04:12:18 -0800 Subject: [PATCH 052/576] Adds a route guide sample proto --- protos/route_guide.proto | 124 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 protos/route_guide.proto diff --git a/protos/route_guide.proto b/protos/route_guide.proto new file mode 100644 index 00000000000..0850239d014 --- /dev/null +++ b/protos/route_guide.proto @@ -0,0 +1,124 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +option java_package = "ex.grpc"; + +package examples; + +// Points are represented as latitude-longitude pairs in the E7 representation +// (degrees multiplied by 10**7 and rounded to the nearest integer). +// Latitudes should be in the range +/- 90 degrees and longitude should be in +// the range +/- 180 degrees (inclusive). +message Point { + optional int32 latitude = 1; + optional int32 longitude = 2; +} + +// A latitude-longitude rectangle, represented as two diagonally opposite +// points "lo" and "hi". +message Rectangle { + // One corner of the rectangle. + optional Point lo = 1; + + // The other corner of the rectangle. + optional Point hi = 2; +} + +// A feature names something at a given point. +// +// If a feature could not be named, the name value is blank. +message Feature { + // The name of the feature. + optional string name = 1; + + // The point where the feature is detected. + optional Point location = 2; +} + +// A RouteNote is a message sent while at a given point. +message RouteNote { + // The location at from which the message is sent. + optional Point location = 1; + + // The message to be sent + optional string message = 2; +} + +// Route summary is the message received in response to a RecordRoute rpc. +// +// It details the number of individual points received, the number of detected +// features and the total distance covered as the cumulative sum of the +// distance between each point. +message RouteSummary { + // The number of points received. + optional int32 point_count = 1; + + // The number of known features passed while traversing the route. + optional int32 feature_count = 2; + + // The distance covered in metres. + optional int32 distance = 3; + + // The duration of the traversal in seconds. + optional int32 elapsed_time = 4; +} + +// Interface exported by the server +service RouteGuide { + // A simple RPC. + // + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) { + } + + // A server-to-client streaming RPC. + // + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) { + } + + // A client-to-server streaming RPC. + // + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) { + } + + // Bidirectional streaming RPC. + // + // Accepts a streams of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) { + } +} From 9ab2c8b5bac6d2fd905a9ca341d3d44b935ae994 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 08:08:15 -0800 Subject: [PATCH 053/576] Another pass at the docs --- protos/route_guide.proto | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/protos/route_guide.proto b/protos/route_guide.proto index 0850239d014..57576937a6f 100644 --- a/protos/route_guide.proto +++ b/protos/route_guide.proto @@ -54,7 +54,7 @@ message Rectangle { // A feature names something at a given point. // -// If a feature could not be named, the name value is blank. +// If a feature could not be named, the name is empty. message Feature { // The name of the feature. optional string name = 1; @@ -65,18 +65,18 @@ message Feature { // A RouteNote is a message sent while at a given point. message RouteNote { - // The location at from which the message is sent. + // The location from which the message is sent. optional Point location = 1; - // The message to be sent + // The message to be sent. optional string message = 2; } -// Route summary is the message received in response to a RecordRoute rpc. +// A RouteSummary is received in response to a RecordRoute rpc. // -// It details the number of individual points received, the number of detected -// features and the total distance covered as the cumulative sum of the -// distance between each point. +// It contains the number of individual points received, the number of +// detected features, and the total distance covered as the cumulative sum of +// the distance between each point. message RouteSummary { // The number of points received. optional int32 point_count = 1; @@ -115,9 +115,9 @@ service RouteGuide { rpc RecordRoute(stream Point) returns (RouteSummary) { } - // Bidirectional streaming RPC. + // A Bidirectional streaming RPC. // - // Accepts a streams of RouteNotes sent while a route is being traversed, + // Accepts a stream of RouteNotes sent while a route is being traversed, // while receiving other RouteNotes (e.g. from other users). rpc RouteChat(stream RouteNote) returns (stream RouteNote) { } From 66e79fa3618f8987fa9398eb2321fe89f42326e6 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 14:07:48 -0800 Subject: [PATCH 054/576] Cleans up helloworld.proto --- protos/helloworld.proto | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/protos/helloworld.proto b/protos/helloworld.proto index aa44b851f43..86402ad71f9 100644 --- a/protos/helloworld.proto +++ b/protos/helloworld.proto @@ -33,19 +33,18 @@ option java_package = "ex.grpc"; package helloworld; +// The greeting service definition. +service Greetings { + // Sends a greeting + rpc hello (HelloRequest) returns (HelloReply) {} +} + // The request message containing the user's name. message HelloRequest { - optional string name = 1; + string name = 1; } // The response message containing the greetings message HelloReply { - optional string message = 1; -} - -// The greeting service definition. -service Greetings { - // Sends a greeting - rpc hello (HelloRequest) returns (HelloReply) { - } + string message = 1; } From c1ee3824b4a20a31fce4cd53ae69128e2d28bdc6 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 14:15:05 -0800 Subject: [PATCH 055/576] Cleans up route_guide.proto --- protos/route_guide.proto | 84 +++++++++++++++++++--------------------- 1 file changed, 40 insertions(+), 44 deletions(-) diff --git a/protos/route_guide.proto b/protos/route_guide.proto index 57576937a6f..7cda80efad8 100644 --- a/protos/route_guide.proto +++ b/protos/route_guide.proto @@ -33,23 +33,51 @@ option java_package = "ex.grpc"; package examples; +// Interface exported by the server. +service RouteGuide { + // A simple RPC. + // + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) {} + + // A server-to-client streaming RPC. + // + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) {} + + // A client-to-server streaming RPC. + // + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} + + // A Bidirectional streaming RPC. + // + // Accepts a stream of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} +} + // Points are represented as latitude-longitude pairs in the E7 representation // (degrees multiplied by 10**7 and rounded to the nearest integer). // Latitudes should be in the range +/- 90 degrees and longitude should be in // the range +/- 180 degrees (inclusive). message Point { - optional int32 latitude = 1; - optional int32 longitude = 2; + int32 latitude = 1; + int32 longitude = 2; } // A latitude-longitude rectangle, represented as two diagonally opposite // points "lo" and "hi". message Rectangle { // One corner of the rectangle. - optional Point lo = 1; + Point lo = 1; // The other corner of the rectangle. - optional Point hi = 2; + Point hi = 2; } // A feature names something at a given point. @@ -57,19 +85,19 @@ message Rectangle { // If a feature could not be named, the name is empty. message Feature { // The name of the feature. - optional string name = 1; + string name = 1; // The point where the feature is detected. - optional Point location = 2; + Point location = 2; } // A RouteNote is a message sent while at a given point. message RouteNote { // The location from which the message is sent. - optional Point location = 1; + Point location = 1; // The message to be sent. - optional string message = 2; + string message = 2; } // A RouteSummary is received in response to a RecordRoute rpc. @@ -79,46 +107,14 @@ message RouteNote { // the distance between each point. message RouteSummary { // The number of points received. - optional int32 point_count = 1; + int32 point_count = 1; // The number of known features passed while traversing the route. - optional int32 feature_count = 2; + int32 feature_count = 2; // The distance covered in metres. - optional int32 distance = 3; + int32 distance = 3; // The duration of the traversal in seconds. - optional int32 elapsed_time = 4; -} - -// Interface exported by the server -service RouteGuide { - // A simple RPC. - // - // Obtains the feature at a given position. - rpc GetFeature(Point) returns (Feature) { - } - - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - rpc ListFeatures(Rectangle) returns (stream Feature) { - } - - // A client-to-server streaming RPC. - // - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - rpc RecordRoute(stream Point) returns (RouteSummary) { - } - - // A Bidirectional streaming RPC. - // - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - rpc RouteChat(stream RouteNote) returns (stream RouteNote) { - } + int32 elapsed_time = 4; } From c5a093c784e1c686bcd9731158d2323d04da19c1 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 14:28:50 -0800 Subject: [PATCH 056/576] Renames method and service name --- protos/helloworld.proto | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/protos/helloworld.proto b/protos/helloworld.proto index 86402ad71f9..4781fb48304 100644 --- a/protos/helloworld.proto +++ b/protos/helloworld.proto @@ -34,9 +34,9 @@ option java_package = "ex.grpc"; package helloworld; // The greeting service definition. -service Greetings { +service Greeter { // Sends a greeting - rpc hello (HelloRequest) returns (HelloReply) {} + rpc sayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. From 01acb4cc49cf72d51594410a709ef7ad6a857627 Mon Sep 17 00:00:00 2001 From: louiscryan Date: Wed, 18 Feb 2015 15:34:00 -0800 Subject: [PATCH 057/576] Initial checkin of protocol draft. --- PROTOCOL-HTTP2.md | 190 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 PROTOCOL-HTTP2.md diff --git a/PROTOCOL-HTTP2.md b/PROTOCOL-HTTP2.md new file mode 100644 index 00000000000..810c6b7e529 --- /dev/null +++ b/PROTOCOL-HTTP2.md @@ -0,0 +1,190 @@ +# gRPC over HTTP2 + +## Introduction +This document serves as a detailed description for an implementation of gRPC carried over HTTP2 draft 17 framing. It assumes familiarity with the HTTP2 specification. + +## Protocol +Production rules are using ABNF syntax. + +### Outline + +The following is the general sequence of message atoms in a GRPC request & response message stream + +* Request → Request-Headers *Delimited-Message EOS +* Response → (Response-Headers *Delimited-Message Trailers) / Trailers-Only + + +### Requests + +* Request → Request-Headers *Delimited-Message EOS + +Request-Headers are delivered as HTTP2 headers in HEADERS + CONTINUATION frames. + +* **Request-Headers** → Call-Definition *Custom-Metadata +* **Call-Definition** → Method Scheme Path TE [Authority] [Timeout] [Content-Type] [Message-Type] [Message-Encoding] [User-Agent] +* **Method** → “:method POST” +* **Scheme** → “:scheme ” (“http” / “https”) +* **Path** → “:path” {_path identifying method within exposed API_} +* **Authority** → “:authority” {_virtual host name of authority_} +* **TE** → “te” “trailers” # Used to detect incompatible proxies +* **Timeout** → “grpc-timeout” TimeoutValue TimeoutUnit +* **TimeoutValue** → {_positive integer as ASCII string of at most 8 digits_} +* **TimeoutUnit** → Hour / Minute / Second / Millisecond / Microsecond / Nanosecond +* **Hour** → “H” +* **Minute** → “M” +* **Second** → “S” +* **Millisecond** → “m” +* **Microsecond** → “u” +* **Nanosecond** → “n” +* **Content-Type** → “content-type” “application/grpc” [(“+proto” / “+json” / {_custom_})] +* **Message-Encoding** → “grpc-encoding ” (“gzip” / “deflate” / “snappy” / {_custom_} ) +* **User-Agent** → “user-agent” {_structured user-agent string_} +* **Message-Type** → “grpc-message-type” {_type name for message schema_} +* **Custom-Metadata** → Binary-Header / ASCII-Header +* **Binary-Header** → {lowercase ASCII header name ending in “-bin” } {_base64 encoded value_} +* **ASCII-Header** → {lowercase ASCII header name} {_value_} + + +HTTP2 requires that reserved headers, ones starting with “:” appear before all other headers. Additionally implementations should send **Timeout** immediately after the reserved headers and they should send the **Call-Definition** headers before sending **Custom-Metadata**. + +If **Timeout** is omitted a server should assume an infinite timeout. Client implementations are free to send a default minimum timeout based on their deployment requirements. + +**Custom-Metadata** is an arbitrary set of key-value pairs defined by the application layer. Aside from transport limits on the total length of HTTP2 HEADERS the only other constraint is that header names starting with “grpc-” are reserved for future use. + +Note that HTTP2 does not allow arbitrary octet sequences for header values so binary header values must be encoded using Base64 as per https://tools.ietf.org/html/rfc4648#section-4. Implementations MUST accept padded and un-padded values and should emit un-padded values. Applications define binary headers by having their names end with “-bin”. Runtime libraries use this suffix to detect binary headers and properly apply base64 encoding & decoding as headers are sent and received. + +The repeated sequence of **Delimited-Message** items is delivered in DATA frames + +* **Delimited-Message** → Compressed-Flag Message-Length Message +* **Compressed-Flag** → 0 / 1 # encoded as 1 byte unsigned integer +* **Message-Length** → {_length of Message_} # encoded as 4 byte unsigned integer +* **Message** → *{binary octet} + +A **Compressed-Flag** value of 1 indicates that the binary octet sequence of **Message** is compressed using the mechanism declared by the **Message-Encoding** header. A value of 0 indicates that no encoding of **Message** bytes has occurred. Compression contexts are NOT maintained over message boundaries, implementations must create a new context for each message in the stream. If the **Message-Encoding** header is omitted then the **Compressed-Flag** must be 0. + +For requests, **EOS** (end-of-stream) is indicated by the presence of the END_STREAM flag on the last received DATA frame. In scenarios where the **Request** stream needs to be closed but no data remains to be sent implementations MUST send an empty DATA frame with this flag set. + +###Responses + +* **Response** → (Response-Headers *Delimited-Message Trailers) / Trailers-Only +* **Response-Headers** → HTTP-Status [Message-Encoding] Content-Type *Custom-Metadata +* **Trailers-Only** → HTTP-Status Content-Type Trailers +* **Trailers** → Status [Status-Message] *Custom-Metadata +* **HTTP-Status** → “:status 200” +* **Status** → “grpc-status” +* **Status-Message** → “grpc-message” + +**Response-Headers** & **Trailers-Only** are each delivered in a single HTTP2 HEADERS frame block. Most responses are expected to have both headers and trailers but **Trailers-Only** is permitted for calls that produce an immediate error. Status must be sent in **Trailers** even if the status code is OK. + +For responses end-of-stream is indicated by the presence of the END_STREAM flag on the last received HEADERS frame that carries **Trailers**. + +Implementations should expect broken deployments to send non-200 HTTP status codes in responses as well as a variety of non-GRPC content-types and to omit **Status** & **Status-Message**. Implementations must synthesize a **Status** & **Status-Message** to propagate to the application layer when this occurs. + +####Example + +Sample unary-call showing HTTP2 framing sequence + +**Request** + +``` +HEADERS (flags = END_HEADERS) +:method = POST +:scheme = http +:path = /google.pubsub.v2.PublisherService/CreateTopic +:authority = pubsub.googleapis.com +grpc-timeout = 1S +content-type = application/grpc+proto +grpc-encoding = gzip +authorization = Bearer y235.wef315yfh138vh31hv93hv8h3v + +DATA (flags = END_STREAM) + +``` +**Response** +``` +HEADERS (flags = END_HEADERS) +:status = 200 +grpc-encoding = gzip + +DATA + + +HEADERS (flags = END_STREAM, END_HEADERS) +grpc-status = 0 # OK +trace-proto-bin = jher831yy13JHy3hc +``` +####User Agents + +While the protocol does not require a user-agent to function it is recommended that clients provide a structured user-agent string that provides a basic description of the calling library, version & platform to facilitate issue diagnosis in heterogeneous environments. The following structure is recommended to library developers +``` +User-Agent → “grpc-” Language ?(“-” Variant) “/” Version ?( “ (“ *(AdditionalProperty “;”) “)” ) +``` +E.g. + +``` +grpc-java/1.2.3 +grpc-ruby/1.2.3 +grpc-ruby-jruby/1.3.4 +grpc-java-android/0.9.1 (gingerbread/1.2.4; nexus5; tmobile) +``` +####HTTP2 Transport Mapping + +#####Stream Identification +All GRPC calls need to specify an internal ID. We will use HTTP2 stream-ids as call identifiers in this scheme. NOTE: These id’s are contextual to an open HTTP2 session and will not be unique within a given process that is handling more than one HTTP2 session nor can they be used as GUIDs. + +#####Data Frames +DATA frame boundaries have no relation to **Delimited-Message** boundaries and implementations should make no assumptions about their alignment. + +#####Errors + +When an application or runtime error occurs during an RPC a **Status** and **Status-Message** are delivered in **Trailers**. + +In some cases it is possible that the framing of the message stream has become corrupt and the RPC runtime will choose to use an **RST_STREAM** frame to indicate this state to its peer. RPC runtime implementations should interpret RST_STREAM as immediate full-closure of the stream and should propagate an error up to the calling application layer. + +The following mapping from RST_STREAM error codes to GRPC error codes is applied. + +HTTP2 Code|GRPC Code +----------|----------- +NO_ERROR(0)|INTERNAL - An explicit GRPC status of OK should have been sent but this might be used to aggressively lameduck in some scenarios. +PROTOCOL_ERROR(1)|INTERNAL +INTERNAL_ERROR(2)|INTERNAL +FLOW_CONTROL_ERROR(3)|INTERNAL +SETTINGS_TIMEOUT(4)|INTERNAL +STREAM_CLOSED|No mapping as there is no open stream to propagate to. Implementations should log. +FRAME_SIZE_ERROR|INTERNAL +REFUSED_STREAM|UNAVAILABLE - Indicates that no processing occurred and the request can be retried, possibly elsewhere. +CANCEL(8)|Mapped to call cancellation when sent by a client.Mapped to CANCELLED when sent by a server. Note that servers should only use this mechanism when they need to cancel a call but the payload byte sequence is incomplete. +COMPRESSION_ERROR|INTERNAL +CONNECT_ERROR|INTERNAL +ENHANCE_YOUR_CALM|RESOURCE_EXHAUSTED ...with additional error detail provided by runtime to indicate that the exhausted resource is bandwidth. +INADEQUATE_SECURITY| PERMISSION_DENIED … with additional detail indicating that permission was denied as protocol is not secure enough for call. + + +#####Security + +The HTTP2 specification mandates the use of TLS 1.2 or higher when TLS is used with HTTP2. It also places some additional constraints on the allowed ciphers in deployments to avoid known-problems as well as requiring SNI support. It is also expected that HTTP2 will be used in conjunction with proprietary transport security mechanisms about which the specification can make no meaningful recommendations. + +#####Connection Management +######GOAWAY Frame +Sent by servers to clients to indicate that they will no longer accept any new streams on the associated connections. This frame includes the id of the last successfully accepted stream by the server. Clients should consider any stream initiated after the last successfully accepted stream as UNAVAILABLE and retry the call elsewhere. Clients are free to continue working with the already accepted streams until they complete or the connection is terminated. + +Servers should send GOAWAY before terminating a connection to reliably inform clients which work has been accepted by the server and is being executed. + +######PING Frame +Both clients and servers can send a PING frame that the peer must respond to by precisely echoing what they received. This is used to assert that the connection is still live as well as providing a means to estimate end-to-end latency. If a server initiated PING does not receive a response within the deadline expected by the runtime all outstanding calls on the server will be closed with a CANCELLED status. An expired client initiated PING will cause all calls to be closed with an UNAVAILABLE status. Note that the frequency of PINGs is highly dependent on the network environment, implementations are free to adjust PING frequency based on network and application requirements. + +######Connection failure +If a detectable connection failure occurs on the client all calls will be closed with an UNAVAILABLE status. For servers open calls will be closed with a CANCELLED status. + + +### Appendix A - GRPC for Protobuf + +The service interfaces declared by protobuf are easily mapped onto GRPC by code generation extensions to protoc. The following defines the mapping to be used + + +* **Path** → / Service-Name / {_method name_} +* **Service-Name** → ?( {_proto package name_} "." ) {_service name_} +* **Message-Type** → {_fully qualified proto message name_} +* **Content-Type** → "application/grpc+proto" + + From 87faa1cf45e498dd2b5969eb39bcbda89ab7eddd Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 17:22:46 -0800 Subject: [PATCH 058/576] Updates generated code to reflect the proto changes in #19 --- .../{GreetingsGrpc.java => GreeterGrpc.java} | 126 +++++++++--------- .../{GreetingsImpl.java => GreeterImpl.java} | 4 +- .../main/java/ex/grpc/GreetingsClient.java | 6 +- .../main/java/ex/grpc/GreetingsServer.java | 2 +- java/src/main/java/ex/grpc/Helloworld.java | 12 +- 5 files changed, 75 insertions(+), 75 deletions(-) rename java/src/main/java/ex/grpc/{GreetingsGrpc.java => GreeterGrpc.java} (51%) rename java/src/main/java/ex/grpc/{GreetingsImpl.java => GreeterImpl.java} (75%) diff --git a/java/src/main/java/ex/grpc/GreetingsGrpc.java b/java/src/main/java/ex/grpc/GreeterGrpc.java similarity index 51% rename from java/src/main/java/ex/grpc/GreetingsGrpc.java rename to java/src/main/java/ex/grpc/GreeterGrpc.java index 97c2f00a1e0..080c3dfc434 100644 --- a/java/src/main/java/ex/grpc/GreetingsGrpc.java +++ b/java/src/main/java/ex/grpc/GreeterGrpc.java @@ -13,150 +13,150 @@ import static com.google.net.stubby.stub.ServerCalls.asyncUnaryRequestCall; import static com.google.net.stubby.stub.ServerCalls.asyncStreamingRequestCall; @javax.annotation.Generated("by gRPC proto compiler") -public class GreetingsGrpc { +public class GreeterGrpc { private static final com.google.net.stubby.stub.Method METHOD_HELLO = + ex.grpc.Helloworld.HelloReply> METHOD_SAY_HELLO = com.google.net.stubby.stub.Method.create( - com.google.net.stubby.MethodType.UNARY, "hello", + com.google.net.stubby.MethodType.UNARY, "sayHello", com.google.net.stubby.proto.ProtoUtils.marshaller(ex.grpc.Helloworld.HelloRequest.PARSER), com.google.net.stubby.proto.ProtoUtils.marshaller(ex.grpc.Helloworld.HelloReply.PARSER)); - public static GreetingsStub newStub(com.google.net.stubby.Channel channel) { - return new GreetingsStub(channel, CONFIG); + public static GreeterStub newStub(com.google.net.stubby.Channel channel) { + return new GreeterStub(channel, CONFIG); } - public static GreetingsBlockingStub newBlockingStub( + public static GreeterBlockingStub newBlockingStub( com.google.net.stubby.Channel channel) { - return new GreetingsBlockingStub(channel, CONFIG); + return new GreeterBlockingStub(channel, CONFIG); } - public static GreetingsFutureStub newFutureStub( + public static GreeterFutureStub newFutureStub( com.google.net.stubby.Channel channel) { - return new GreetingsFutureStub(channel, CONFIG); + return new GreeterFutureStub(channel, CONFIG); } - public static final GreetingsServiceDescriptor CONFIG = - new GreetingsServiceDescriptor(); + public static final GreeterServiceDescriptor CONFIG = + new GreeterServiceDescriptor(); @javax.annotation.concurrent.Immutable - public static class GreetingsServiceDescriptor extends - com.google.net.stubby.stub.AbstractServiceDescriptor { + public static class GreeterServiceDescriptor extends + com.google.net.stubby.stub.AbstractServiceDescriptor { public final com.google.net.stubby.MethodDescriptor hello; + ex.grpc.Helloworld.HelloReply> sayHello; - private GreetingsServiceDescriptor() { - hello = createMethodDescriptor( - "helloworld.Greetings", METHOD_HELLO); + private GreeterServiceDescriptor() { + sayHello = createMethodDescriptor( + "helloworld.Greeter", METHOD_SAY_HELLO); } - private GreetingsServiceDescriptor( + private GreeterServiceDescriptor( java.util.Map> methodMap) { - hello = (com.google.net.stubby.MethodDescriptor) methodMap.get( - CONFIG.hello.getName()); + CONFIG.sayHello.getName()); } @java.lang.Override - protected GreetingsServiceDescriptor build( + protected GreeterServiceDescriptor build( java.util.Map> methodMap) { - return new GreetingsServiceDescriptor(methodMap); + return new GreeterServiceDescriptor(methodMap); } @java.lang.Override public com.google.common.collect.ImmutableList> methods() { return com.google.common.collect.ImmutableList.>of( - hello); + sayHello); } } - public static interface Greetings { + public static interface Greeter { - public void hello(ex.grpc.Helloworld.HelloRequest request, + public void sayHello(ex.grpc.Helloworld.HelloRequest request, com.google.net.stubby.stub.StreamObserver responseObserver); } - public static interface GreetingsBlockingClient { + public static interface GreeterBlockingClient { - public ex.grpc.Helloworld.HelloReply hello(ex.grpc.Helloworld.HelloRequest request); + public ex.grpc.Helloworld.HelloReply sayHello(ex.grpc.Helloworld.HelloRequest request); } - public static interface GreetingsFutureClient { + public static interface GreeterFutureClient { - public com.google.common.util.concurrent.ListenableFuture hello( + public com.google.common.util.concurrent.ListenableFuture sayHello( ex.grpc.Helloworld.HelloRequest request); } - public static class GreetingsStub extends - com.google.net.stubby.stub.AbstractStub - implements Greetings { - private GreetingsStub(com.google.net.stubby.Channel channel, - GreetingsServiceDescriptor config) { + public static class GreeterStub extends + com.google.net.stubby.stub.AbstractStub + implements Greeter { + private GreeterStub(com.google.net.stubby.Channel channel, + GreeterServiceDescriptor config) { super(channel, config); } @java.lang.Override - protected GreetingsStub build(com.google.net.stubby.Channel channel, - GreetingsServiceDescriptor config) { - return new GreetingsStub(channel, config); + protected GreeterStub build(com.google.net.stubby.Channel channel, + GreeterServiceDescriptor config) { + return new GreeterStub(channel, config); } @java.lang.Override - public void hello(ex.grpc.Helloworld.HelloRequest request, + public void sayHello(ex.grpc.Helloworld.HelloRequest request, com.google.net.stubby.stub.StreamObserver responseObserver) { asyncUnaryCall( - channel.newCall(config.hello), request, responseObserver); + channel.newCall(config.sayHello), request, responseObserver); } } - public static class GreetingsBlockingStub extends - com.google.net.stubby.stub.AbstractStub - implements GreetingsBlockingClient { - private GreetingsBlockingStub(com.google.net.stubby.Channel channel, - GreetingsServiceDescriptor config) { + public static class GreeterBlockingStub extends + com.google.net.stubby.stub.AbstractStub + implements GreeterBlockingClient { + private GreeterBlockingStub(com.google.net.stubby.Channel channel, + GreeterServiceDescriptor config) { super(channel, config); } @java.lang.Override - protected GreetingsBlockingStub build(com.google.net.stubby.Channel channel, - GreetingsServiceDescriptor config) { - return new GreetingsBlockingStub(channel, config); + protected GreeterBlockingStub build(com.google.net.stubby.Channel channel, + GreeterServiceDescriptor config) { + return new GreeterBlockingStub(channel, config); } @java.lang.Override - public ex.grpc.Helloworld.HelloReply hello(ex.grpc.Helloworld.HelloRequest request) { + public ex.grpc.Helloworld.HelloReply sayHello(ex.grpc.Helloworld.HelloRequest request) { return blockingUnaryCall( - channel.newCall(config.hello), request); + channel.newCall(config.sayHello), request); } } - public static class GreetingsFutureStub extends - com.google.net.stubby.stub.AbstractStub - implements GreetingsFutureClient { - private GreetingsFutureStub(com.google.net.stubby.Channel channel, - GreetingsServiceDescriptor config) { + public static class GreeterFutureStub extends + com.google.net.stubby.stub.AbstractStub + implements GreeterFutureClient { + private GreeterFutureStub(com.google.net.stubby.Channel channel, + GreeterServiceDescriptor config) { super(channel, config); } @java.lang.Override - protected GreetingsFutureStub build(com.google.net.stubby.Channel channel, - GreetingsServiceDescriptor config) { - return new GreetingsFutureStub(channel, config); + protected GreeterFutureStub build(com.google.net.stubby.Channel channel, + GreeterServiceDescriptor config) { + return new GreeterFutureStub(channel, config); } @java.lang.Override - public com.google.common.util.concurrent.ListenableFuture hello( + public com.google.common.util.concurrent.ListenableFuture sayHello( ex.grpc.Helloworld.HelloRequest request) { return unaryFutureCall( - channel.newCall(config.hello), request); + channel.newCall(config.sayHello), request); } } public static com.google.net.stubby.ServerServiceDefinition bindService( - final Greetings serviceImpl) { - return com.google.net.stubby.ServerServiceDefinition.builder("helloworld.Greetings") + final Greeter serviceImpl) { + return com.google.net.stubby.ServerServiceDefinition.builder("helloworld.Greeter") .addMethod(createMethodDefinition( - METHOD_HELLO, + METHOD_SAY_HELLO, asyncUnaryRequestCall( new com.google.net.stubby.stub.ServerCalls.UnaryRequestMethod< ex.grpc.Helloworld.HelloRequest, @@ -165,7 +165,7 @@ public class GreetingsGrpc { public void invoke( ex.grpc.Helloworld.HelloRequest request, com.google.net.stubby.stub.StreamObserver responseObserver) { - serviceImpl.hello(request, responseObserver); + serviceImpl.sayHello(request, responseObserver); } }))).build(); } diff --git a/java/src/main/java/ex/grpc/GreetingsImpl.java b/java/src/main/java/ex/grpc/GreeterImpl.java similarity index 75% rename from java/src/main/java/ex/grpc/GreetingsImpl.java rename to java/src/main/java/ex/grpc/GreeterImpl.java index 005489acaa2..825ba8631ec 100644 --- a/java/src/main/java/ex/grpc/GreetingsImpl.java +++ b/java/src/main/java/ex/grpc/GreeterImpl.java @@ -2,10 +2,10 @@ package ex.grpc; import com.google.net.stubby.stub.StreamObserver; -public class GreetingsImpl implements GreetingsGrpc.Greetings { +public class GreeterImpl implements GreeterGrpc.Greeter { @Override - public void hello(Helloworld.HelloRequest req, + public void sayHello(Helloworld.HelloRequest req, StreamObserver responseObserver) { Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( "Hello " + req.getName()).build(); diff --git a/java/src/main/java/ex/grpc/GreetingsClient.java b/java/src/main/java/ex/grpc/GreetingsClient.java index 4ae2e7076bc..141ad1e20a6 100644 --- a/java/src/main/java/ex/grpc/GreetingsClient.java +++ b/java/src/main/java/ex/grpc/GreetingsClient.java @@ -13,13 +13,13 @@ public class GreetingsClient { private final Logger logger = Logger.getLogger( GreetingsClient.class.getName()); private final ChannelImpl channel; - private final GreetingsGrpc.GreetingsBlockingStub blockingStub; + private final GreeterGrpc.GreeterBlockingStub blockingStub; public GreetingsClient(String host, int port) { channel = NettyChannelBuilder.forAddress(host, port) .negotiationType(NegotiationType.PLAINTEXT) .build(); - blockingStub = GreetingsGrpc.newBlockingStub(channel); + blockingStub = GreeterGrpc.newBlockingStub(channel); } public void shutdown() throws InterruptedException { @@ -31,7 +31,7 @@ public class GreetingsClient { logger.fine("Will try to greet " + name + " ..."); Helloworld.HelloRequest req = Helloworld.HelloRequest.newBuilder().setName(name).build(); - Helloworld.HelloReply reply = blockingStub.hello(req); + Helloworld.HelloReply reply = blockingStub.sayHello(req); logger.info("Greeting: " + reply.getMessage()); } catch (RuntimeException e) { logger.log(Level.WARNING, "RPC failed", e); diff --git a/java/src/main/java/ex/grpc/GreetingsServer.java b/java/src/main/java/ex/grpc/GreetingsServer.java index 834ae985a44..237309d13c7 100644 --- a/java/src/main/java/ex/grpc/GreetingsServer.java +++ b/java/src/main/java/ex/grpc/GreetingsServer.java @@ -16,7 +16,7 @@ public class GreetingsServer { private void start() throws Exception { server = NettyServerBuilder.forPort(port) - .addService(GreetingsGrpc.bindService(new GreetingsImpl())) + .addService(GreeterGrpc.bindService(new GreeterImpl())) .build(); server.startAsync(); server.awaitRunning(5, TimeUnit.SECONDS); diff --git a/java/src/main/java/ex/grpc/Helloworld.java b/java/src/main/java/ex/grpc/Helloworld.java index f72040fa2bf..b25a63fca32 100644 --- a/java/src/main/java/ex/grpc/Helloworld.java +++ b/java/src/main/java/ex/grpc/Helloworld.java @@ -1,5 +1,5 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! -// source: src/main/proto/helloworld.proto +// source: helloworld.proto package ex.grpc; @@ -915,11 +915,11 @@ public final class Helloworld { descriptor; static { java.lang.String[] descriptorData = { - "\n\037src/main/proto/helloworld.proto\022\nhello" + - "world\"\034\n\014HelloRequest\022\014\n\004name\030\001 \001(\t\"\035\n\nH" + - "elloReply\022\017\n\007message\030\001 \001(\t2H\n\tGreetings\022" + - ";\n\005hello\022\030.helloworld.HelloRequest\032\026.hel" + - "loworld.HelloReply\"\000B\t\n\007ex.grpcb\006proto3" + "\n\020helloworld.proto\022\nhelloworld\"\034\n\014HelloR" + + "equest\022\014\n\004name\030\001 \001(\t\"\035\n\nHelloReply\022\017\n\007me" + + "ssage\030\001 \001(\t2I\n\007Greeter\022>\n\010sayHello\022\030.hel" + + "loworld.HelloRequest\032\026.helloworld.HelloR" + + "eply\"\000B\t\n\007ex.grpcb\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { From 2604848108f26d4b4a38ca9316db376d5e470634 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 17:31:03 -0800 Subject: [PATCH 059/576] Updates the main to reflect the proto changes in #19 --- README.md | 57 +++++++++++++++++++++++++------------------------------ 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index fdbd1f0de02..1203465660d 100644 --- a/README.md +++ b/README.md @@ -247,26 +247,26 @@ we need to create our example: - [`Helloworld.java`](java/src/main/java/ex/grpc/Helloworld.java), which has all the protocol buffer code to populate, serialize, and retrieve our `HelloRequest` and `HelloReply` message types -- [`GreetingsGrpc.java`](java/src/main/java/ex/grpc/GreetingsGrpc.java), +- [`GreeterGrpc.java`](java/src/main/java/ex/grpc/GreeterGrpc.java), which contains (along with some other useful code): - - an interface for `Greetings` servers to implement + - an interface for `Greeter` servers to implement ```java - public static interface Greetings { + public static interface Greeter { - public void hello(ex.grpc.Helloworld.HelloRequest request, + public void sayHello(ex.grpc.Helloworld.HelloRequest request, com.google.net.stubby.stub.StreamObserver responseObserver); } ``` - - _stub_ classes that clients can use to talk to a `Greetings` server. As you can see, they also implement the `Greetings` interface. + - _stub_ classes that clients can use to talk to a `Greeter` server. As you can see, they also implement the `Greeter` interface. ```java -public static class GreetingsStub extends - com.google.net.stubby.stub.AbstractStub - implements Greetings { +public static class GreeterStub extends + com.google.net.stubby.stub.AbstractStub + implements Greeter { ... } ``` @@ -282,18 +282,18 @@ tutorial for your chosen language (coming soon). Our server application has two classes: - a simple service implementation -[GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). +[GreeterImpl.java](java/src/main/java/ex/grpc/GreeterImpl.java). - a server that hosts the service implementation and allows access over the -network: [GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java). +network: [GreeterServer.java](java/src/main/java/ex/grpc/GreeterServer.java). #### Service implementation -[GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java) +[GreeterImpl.java](java/src/main/java/ex/grpc/GreeterImpl.java) actually implements our GreetingService's required behaviour. -As you can see, the class `GreetingsImpl` implements the interface -`GreetingsGrpc.Greetings` that we [generated](#generating) from our proto +As you can see, the class `GreeterImpl` implements the interface +`GreeterGrpc.Greeter` that we [generated](#generating) from our proto [IDL](java/src/main/proto/helloworld.proto) by implementing the method `hello`: ```java @@ -325,7 +325,7 @@ finished dealing with this RPC. #### Server implementation -[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) +[GreeterServer.java](java/src/main/java/ex/grpc/GreeterServer.java) shows the other main feature required to provide a gRPC service; making the service implementation available from the network. @@ -334,7 +334,7 @@ implementation available from the network. ... private void start() throws Exception { server = NettyServerBuilder.forPort(port) - .addService(GreetingsGrpc.bindService(new GreetingsImpl())) + .addService(GreeterGrpc.bindService(new GreeterImpl())) .build(); server.startAsync(); server.awaitRunning(5, TimeUnit.SECONDS); @@ -342,15 +342,15 @@ implementation available from the network. ``` -The `GreetingsServer` class has a `ServerImpl` member that actually runs the +The `GreeterServer` class has a `ServerImpl` member that actually runs the server. To create an appropriate `ServerImpl`, we use a special `ServerBuilder` -class (in this case a `NettyServerBuilder`) in the `GreetingsServer`'s `start` -method, binding the `GreetingsService` implementation that we created to a +class (in this case a `NettyServerBuilder`) in the `GreeterServer`'s `start` +method, binding the `GreeterService` implementation that we created to a port. Then we start the server running: the server is now ready to receive -requests from `Greetings` service clients on our specified port. We'll cover +requests from `Greeter` service clients on our specified port. We'll cover how all this works in a bit more detail in our language-specific documentation. -`GreetingsServer` also has a `stop` method that takes care of shutting down +`GreeterServer` also has a `stop` method that takes care of shutting down the service and cleaning up when the program exits. #### Build it @@ -367,9 +367,9 @@ We'll look at using a client to access the server in the next section. ### Writing a client Client-side gRPC is pretty simple. In this step, we'll use the generated code -to write a simple client that can access the `Greetings` server we created +to write a simple client that can access the `Greeter` server we created in the [previous section](#server). You can see the complete client code in -[GreetingsClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). +[GreetingClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). Again, we're not going to go into much detail about how to implement a client - we'll leave that for the tutorial. @@ -386,13 +386,13 @@ service. The channel in turn is used to construct the stub instance. ```java private final ChannelImpl channel; - private final GreetingGrpc.GreetingBlockingStub blockingStub; + private final GreeterGrpc.GreeterBlockingStub blockingStub; public HelloClient(String host, int port) { channel = NettyChannelBuilder.forAddress(host, port) .negotiationType(NegotiationType.PLAINTEXT) .build(); - blockingStub = GreetingGrpc.newBlockingStub(channel); + blockingStub = GreeterGrpc.newBlockingStub(channel); } ``` @@ -419,7 +419,7 @@ from which we can get our greeting. try { Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName(name).build(); - Helloworld.HelloReply reply = blockingStub.hello(request); + Helloworld.HelloReply reply = blockingStub.sayHello(request); logger.info("Greeting: " + reply.getMessage()); } catch (RuntimeException e) { logger.log(Level.WARNING, "RPC failed", e); @@ -474,8 +474,3 @@ $ ./run_greetings_client.sh ### Adding another client ###TODO: Section on Go client for same server - - - - - From a16a4d551f9035bd720107732ab71bb9bf337dda Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 17:43:41 -0800 Subject: [PATCH 060/576] Complete the change s/Greetings/Greeter --- README.md | 6 +++--- java/{run_greetings_client.sh => run_greeter_client.sh} | 4 ++-- java/{run_greetings_server.sh => run_greeter_server.sh} | 4 ++-- .../ex/grpc/{GreetingsClient.java => GreeterClient.java} | 8 ++++---- .../ex/grpc/{GreetingsServer.java => GreeterServer.java} | 6 +++--- 5 files changed, 14 insertions(+), 14 deletions(-) rename java/{run_greetings_client.sh => run_greeter_client.sh} (80%) rename java/{run_greetings_server.sh => run_greeter_server.sh} (78%) rename java/src/main/java/ex/grpc/{GreetingsClient.java => GreeterClient.java} (89%) rename java/src/main/java/ex/grpc/{GreetingsServer.java => GreeterServer.java} (88%) diff --git a/README.md b/README.md index 1203465660d..71f3004c71d 100644 --- a/README.md +++ b/README.md @@ -369,7 +369,7 @@ We'll look at using a client to access the server in the next section. Client-side gRPC is pretty simple. In this step, we'll use the generated code to write a simple client that can access the `Greeter` server we created in the [previous section](#server). You can see the complete client code in -[GreetingClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). +[GreeterClient.java](java/src/main/java/ex/grpc/GreeterClient.java). Again, we're not going to go into much detail about how to implement a client - we'll leave that for the tutorial. @@ -462,13 +462,13 @@ We've added simple shell scripts to simplifying running the examples. Now that they are built, you can run the server with: ```sh -$ ./run_greetings_server.sh +$ ./run_greeter_server.sh ``` and in another terminal window confirm that it receives a message. ```sh -$ ./run_greetings_client.sh +$ ./run_greeter_client.sh ``` ### Adding another client diff --git a/java/run_greetings_client.sh b/java/run_greeter_client.sh similarity index 80% rename from java/run_greetings_client.sh rename to java/run_greeter_client.sh index 8155589adf7..e86ab4ae891 100755 --- a/java/run_greetings_client.sh +++ b/java/run_greeter_client.sh @@ -1,6 +1,6 @@ #!/bin/bash -e -TARGET='Greetings Client' -TARGET_CLASS='ex.grpc.GreetingsClient' +TARGET='Greeter Client' +TARGET_CLASS='ex.grpc.GreeterClient' TARGET_ARGS="$@" cd "$(dirname "$0")" diff --git a/java/run_greetings_server.sh b/java/run_greeter_server.sh similarity index 78% rename from java/run_greetings_server.sh rename to java/run_greeter_server.sh index 248229e129e..836abc7f48a 100755 --- a/java/run_greetings_server.sh +++ b/java/run_greeter_server.sh @@ -1,6 +1,6 @@ #!/bin/bash -e -TARGET='Greetings Server' -TARGET_CLASS='ex.grpc.GreetingsServer' +TARGET='Greeter Server' +TARGET_CLASS='ex.grpc.GreeterServer' cd "$(dirname "$0")" mvn -q -nsu -am package -Dcheckstyle.skip=true -DskipTests diff --git a/java/src/main/java/ex/grpc/GreetingsClient.java b/java/src/main/java/ex/grpc/GreeterClient.java similarity index 89% rename from java/src/main/java/ex/grpc/GreetingsClient.java rename to java/src/main/java/ex/grpc/GreeterClient.java index 141ad1e20a6..9a4615132d6 100644 --- a/java/src/main/java/ex/grpc/GreetingsClient.java +++ b/java/src/main/java/ex/grpc/GreeterClient.java @@ -9,13 +9,13 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.concurrent.TimeUnit; -public class GreetingsClient { +public class GreeterClient { private final Logger logger = Logger.getLogger( - GreetingsClient.class.getName()); + GreeterClient.class.getName()); private final ChannelImpl channel; private final GreeterGrpc.GreeterBlockingStub blockingStub; - public GreetingsClient(String host, int port) { + public GreeterClient(String host, int port) { channel = NettyChannelBuilder.forAddress(host, port) .negotiationType(NegotiationType.PLAINTEXT) .build(); @@ -40,7 +40,7 @@ public class GreetingsClient { } public static void main(String[] args) throws Exception { - GreetingsClient client = new GreetingsClient("localhost", 50051); + GreeterClient client = new GreeterClient("localhost", 50051); try { /* Access a service running on the local machine on port 50051 */ String user = "world"; diff --git a/java/src/main/java/ex/grpc/GreetingsServer.java b/java/src/main/java/ex/grpc/GreeterServer.java similarity index 88% rename from java/src/main/java/ex/grpc/GreetingsServer.java rename to java/src/main/java/ex/grpc/GreeterServer.java index 237309d13c7..bb05680b0a6 100644 --- a/java/src/main/java/ex/grpc/GreetingsServer.java +++ b/java/src/main/java/ex/grpc/GreeterServer.java @@ -7,9 +7,9 @@ import com.google.net.stubby.transport.netty.NettyServerBuilder; import java.util.concurrent.TimeUnit; /** - * Server that manages startup/shutdown of a {@code Greetings} server. + * Server that manages startup/shutdown of a {@code Greeter} server. */ -public class GreetingsServer { +public class GreeterServer { /* The port on which the server should run */ private int port = 50051; private ServerImpl server; @@ -33,7 +33,7 @@ public class GreetingsServer { * Main launches the server from the command line. */ public static void main(String[] args) throws Exception { - final GreetingsServer server = new GreetingsServer(); + final GreeterServer server = new GreeterServer(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override From 5aa9eeba547205b309c66aed97253b4fb670fa60 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Thu, 19 Feb 2015 07:30:43 -0800 Subject: [PATCH 061/576] Removes the unused protos, updates the README to reflect the protos in use --- java/src/main/proto/helloworld.proto | 22 -------- protos/README.md | 10 ++-- protos/math.proto | 79 ---------------------------- protos/stock.proto | 71 ------------------------- 4 files changed, 4 insertions(+), 178 deletions(-) delete mode 100644 java/src/main/proto/helloworld.proto delete mode 100644 protos/math.proto delete mode 100644 protos/stock.proto diff --git a/java/src/main/proto/helloworld.proto b/java/src/main/proto/helloworld.proto deleted file mode 100644 index da5c3a1d85d..00000000000 --- a/java/src/main/proto/helloworld.proto +++ /dev/null @@ -1,22 +0,0 @@ -syntax = "proto3"; - -option java_package = "ex.grpc"; - -package helloworld; - -// The request message containing the user's name. -message HelloRequest { - optional string name = 1; -} - -// The response message containing the greetings -message HelloReply { - optional string message = 1; -} - -// The greeting service definition. -service Greetings { - // Sends a greeting - rpc hello (HelloRequest) returns (HelloReply) { - } -} diff --git a/protos/README.md b/protos/README.md index 374d4350aca..48df7c8943e 100644 --- a/protos/README.md +++ b/protos/README.md @@ -2,9 +2,7 @@ ## Contents -- helloworld.proto - - A very simple example used in the overview. -- stock.proto - - A detailed example that's described in detail in the tutorial. -- math.proto - - Another detailed example for further reference. +- [helloworld.proto] + - The simple example used in the overview. +- [route_guide.proto] + - An example service described in detail in the tutorial. diff --git a/protos/math.proto b/protos/math.proto deleted file mode 100644 index 46a33aeee53..00000000000 --- a/protos/math.proto +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2015, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package math; - -message DivArgs { - optional int64 dividend = 1; - optional int64 divisor = 2; -} - -message DivReply { - optional int64 quotient = 1; - optional int64 remainder = 2; -} - -message FibArgs { - optional int64 limit = 1; -} - -message Num { - optional int64 num = 1; -} - -message FibReply { - optional int64 count = 1; -} - -service Math { - // Div divides args.dividend by args.divisor and returns the quotient and - // remainder. - rpc Div (DivArgs) returns (DivReply) { - } - - // DivMany accepts an arbitrary number of division args from the client stream - // and sends back the results in the reply stream. The stream continues until - // the client closes its end; the server does the same after sending all the - // replies. The stream ends immediately if either end aborts. - rpc DivMany (stream DivArgs) returns (stream DivReply) { - } - - // Fib generates numbers in the Fibonacci sequence. If args.limit > 0, Fib - // generates up to limit numbers; otherwise it continues until the call is - // canceled. - rpc Fib (FibArgs) returns (stream Num) { - } - - // Sum sums a stream of numbers, returning the final result once the stream - // is closed. - rpc Sum (stream Num) returns (Num) { - } -} diff --git a/protos/stock.proto b/protos/stock.proto deleted file mode 100644 index 49efbf2730a..00000000000 --- a/protos/stock.proto +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2015, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package examples; - -// Protocol type definitions -message StockRequest { - optional string symbol = 1; - optional int32 num_trades_to_watch = 2; -} - -message StockReply { - optional float price = 1; - optional string symbol = 2; -} - -// Interface exported by the server -service Stock { - // A simple blocking RPC. - // - // Obtains the last traded price for the given Stock. - rpc GetLastTradePrice(StockRequest) returns (StockReply) { - } - - // A Unidirectional server-to-client streaming RPC. - // - // Streams future prices for a given symbol. - rpc WatchFutureTrades(StockRequest) returns (stream StockReply) { - } - - // A Unidirectional client-to-server streaming RPC. - // - // Gets the highest traded price for a series of symbols - rpc GetHighestTradePrice(stream StockRequest) returns (StockReply) { - } - - // Bidirectional streaming RPC. - // - // Gets the most recent traded price of series of trades. - rpc GetLastTradePriceMultiple(stream StockRequest) returns - (stream StockReply) { - } -} From 554b4d7e202ff57b5f60619e6eb675858fb689a6 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Thu, 19 Feb 2015 16:05:49 +0000 Subject: [PATCH 062/576] More tidying up, pared down explanations for server and client code as was getting a bit too Java-specific. --- README.md | 72 ++++++++++++++----------------------------------------- 1 file changed, 18 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index fdbd1f0de02..5669b8318c5 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Hello World example. More documentation is coming soon! ## What is gRPC? -In gRPC, like other RPC systems, a *client* application can directly call +In gRPC a *client* application can directly call methods on a *server* application on a different machine as if it was a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining @@ -32,9 +32,8 @@ your applications. ### Working with protocol buffers -While gRPC’s architecture allows it to be extended for use with other -data formats such as JSON, by default it uses *protocol buffers*, Google’s -mature open source mechanism for serializing structured data. As you'll +By default gRPC uses *protocol buffers*, Google’s +mature open source mechanism for serializing structured data (although it can be used with other data formats such as JSON). As you'll see in our example below, you define gRPC services using *proto files*, with method parameters and return types specified as protocol buffer message types. You @@ -68,7 +67,7 @@ construction of a simple gRPC client-server application, showing you how to: - Create a protocol buffers schema that defines a simple RPC service with a single Hello World method. -- Create a Java server that implements thid interface. +- Create a Java server that implements this interface. - Create a Java client that accesses the Java server. - Create a [probably need a different language now] client that accesses the same Java server. - Update the service with more advanced features like RPC streaming. @@ -82,7 +81,7 @@ than how to install and run a few git commands. This is an introductory example rather than a comprehensive tutorial, so don't worry if you're not a Go or -Java developer - complete tutorials and reference documentation for all gRPC +Java developer - the concepts introduced here are similar for all languages, and complete tutorials and reference documentation for all gRPC languages are coming soon. @@ -209,9 +208,7 @@ our application - right now we're going to generate Java code, though you can generate gRPC code in any gRPC-supported language (as you'll see later in this example). The generated code contains both stub code for clients to use and an abstract interface for servers to implement, both with the method -defined in our `Greeting` service. A stub is code that initiates contact -with a gRPC service running remotely via the internet. [can probably define -this up in "what is gRPC"?] +defined in our `Greeting` service. (If you didn't install `protoc` on your system and are working along with the example, you can skip this step and move @@ -276,7 +273,7 @@ public static class GreetingsStub extends Now let's write some code! First we'll create a server application to implement our service. Note that we're not going to go into a lot of detail about how -to create a server in this section More detailed information will be in the +to create a server in this section. More detailed information will be in the tutorial for your chosen language (coming soon). Our server application has two classes: @@ -293,7 +290,7 @@ network: [GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) actually implements our GreetingService's required behaviour. As you can see, the class `GreetingsImpl` implements the interface -`GreetingsGrpc.Greetings` that we [generated](#generating) from our proto +`GreetingsGrpc.Greetings` that we [generated](#Generating gRPC code) from our proto [IDL](java/src/main/proto/helloworld.proto) by implementing the method `hello`: ```java @@ -306,9 +303,6 @@ As you can see, the class `GreetingsImpl` implements the interface responseObserver.onCompleted(); } ``` -- `hello's` signature is typesafe: - `hello(Helloworld.HelloRequest req, StreamObserver - responseObserver)` - `hello` takes two parameters: -`Helloworld.HelloRequest`: the request -`StreamObserver`: a response observer, which is @@ -318,9 +312,7 @@ To return our response to the client and complete the call: 1. We construct and populate a `HelloReply` response object with our exciting message, as specified in our interface definition. -2. We call `responseObserver.onValue()` with the `HelloReply` that we want to send back to the client. -3. Finally, we call `responseObserver.onCompleted()` to indicate that we're -finished dealing with this RPC. +2. We use the`responseObserver` to return the `HelloReply` to the client and then specify that we've finished dealing with the RPC #### Server implementation @@ -342,17 +334,11 @@ implementation available from the network. ``` -The `GreetingsServer` class has a `ServerImpl` member that actually runs the -server. To create an appropriate `ServerImpl`, we use a special `ServerBuilder` -class (in this case a `NettyServerBuilder`) in the `GreetingsServer`'s `start` -method, binding the `GreetingsService` implementation that we created to a +Here we create an appropriate gRPC server, binding the `GreetingsService` implementation that we created to a port. Then we start the server running: the server is now ready to receive requests from `Greetings` service clients on our specified port. We'll cover how all this works in a bit more detail in our language-specific documentation. -`GreetingsServer` also has a `stop` method that takes care of shutting down -the service and cleaning up when the program exits. - #### Build it Once we've implemented everything, we use Maven to build the server: @@ -376,12 +362,7 @@ Again, we're not going to go into much detail about how to implement a client #### Connecting to the service -First let's look at how we connect to the `Greetings` server. The internet -address -is configured in the client constructor. gRPC `Channel` provides the -abstraction layer over -transport handling; its constructor accepts the host name and port of the -service. The channel in turn is used to construct the stub instance. +First let's look at how we connect to the `Greetings` server. First we need to create a gRPC channel, specifying the hostname and port of the server we want to connect to. Then we use the channel to construct the stub instance. ```java @@ -402,14 +383,12 @@ for the server to respond, and will either return a response or raise an exception. gRPC Java has other kinds of stubs that make non-blocking calls to the server, where the response is returned asynchronously. -#### Obtaining a greeting +#### Calling an RPC -The `greet()` method uses the stub to contact the service and obtain -a greeting. -To do this: +Now we can contact the service and obtain a greeting: -1. We construct and fill in a `HelloRequest` to send to the stub. -2. We call the RPC with our request and get a `HelloReply` from the stub, +1. We construct and fill in a `HelloRequest` to send to the service. +2. We call the stub's `hello()` RPC with our request and get a `HelloReply` back, from which we can get our greeting. @@ -429,27 +408,10 @@ from which we can get our greeting. ``` -#### Running from the command line - -The main method puts together the example so that it can be run from a command -line. - -```java - /* Access a service running on the local machine on port 50051 */ - HelloClient client = new HelloClient("localhost", 50051); - String user = "world"; - if (args.length > 1) { - user = args[1]; - } - client.greet(user); - -``` - #### Build the client This is the same as building the server: our client and server are part of -the same maven -package so the same command builds both. +the same maven package so the same command builds both. ``` $ mvn package @@ -473,6 +435,8 @@ $ ./run_greetings_client.sh ### Adding another client +Finally, let's look at one of gRPC's most useful features - interoperability between code in different languages. So far, we've just generated Java code from our `Greetings` service definition. + ###TODO: Section on Go client for same server From e1a9ebdce3911f5b834d6590d5235b5f8d450ab3 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Thu, 19 Feb 2015 17:35:10 +0000 Subject: [PATCH 063/576] Couple more small fixes --- README.md | 76 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 5669b8318c5..4701619b699 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@ # Getting started -## TODO: move this to the tutorial sub-folder - Welcome to the developer documentation for gRPC, a language-neutral, platform-neutral remote procedure call (RPC) system developed at Google. @@ -33,7 +31,8 @@ your applications. ### Working with protocol buffers By default gRPC uses *protocol buffers*, Google’s -mature open source mechanism for serializing structured data (although it can be used with other data formats such as JSON). As you'll +mature open source mechanism for serializing structured data (although it +can be used with other data formats such as JSON). As you'll see in our example below, you define gRPC services using *proto files*, with method parameters and return types specified as protocol buffer message types. You @@ -65,14 +64,17 @@ Now that you know a bit more about gRPC, the easiest way to see how it works is to look at a simple example. Our Hello World walks you through the construction of a simple gRPC client-server application, showing you how to: -- Create a protocol buffers schema that defines a simple RPC service with a single +- Create a protocol buffers schema that defines a simple RPC service with +a single Hello World method. - Create a Java server that implements this interface. - Create a Java client that accesses the Java server. -- Create a [probably need a different language now] client that accesses the same Java server. +- Create a [probably need a different language now] client that accesses +the same Java server. - Update the service with more advanced features like RPC streaming. -The complete code for the example is available in the `grpc-common` GitHub repository. You can +The complete code for the example is available in the `grpc-common` GitHub +repository. You can work along with the example and hack on the code in the comfort of your own computer, giving you hands-on practice of really writing gRPC code. We use the Git versioning system for source code management: @@ -81,14 +83,16 @@ than how to install and run a few git commands. This is an introductory example rather than a comprehensive tutorial, so don't worry if you're not a Go or -Java developer - the concepts introduced here are similar for all languages, and complete tutorials and reference documentation for all gRPC +Java developer - the concepts introduced here are similar for all languages, +and complete tutorials and reference documentation for all gRPC languages are coming soon. ### Setup This section explains how to set up your local machine to work with -the example code. If you just want to read the example, you can go straight to the [next step](#servicedef). +the example code. If you just want to read the example, you can go straight +to the [next step](#servicedef). #### Install Git @@ -167,7 +171,8 @@ server use interface code generated from the service definition. Here's our example service definition, defined using protocol buffers IDL in [helloworld.proto](java/src/main/proto/helloworld.proto). The `Greeting` -service has one method, `hello`, that lets the server receive a single `HelloRequest` +service has one method, `hello`, that lets the server receive a single +`HelloRequest` message from the remote client containing the user's name, then send back a greeting in a single `HelloReply`. This is the simplest type of RPC you can specify in gRPC - we'll look at some other types later in this document. @@ -179,22 +184,20 @@ option java_package = "ex.grpc"; package helloworld; +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc sayHello (HelloRequest) returns (HelloReply) {} +} + // The request message containing the user's name. message HelloRequest { - optional string name = 1; + string name = 1; } // The response message containing the greetings message HelloReply { - optional string message = 1; -} - -// The greeting service definition. -service Greeting { - - // Sends a greeting - rpc hello (HelloRequest) returns (HelloReply) { - } + string message = 1; } ``` @@ -257,7 +260,8 @@ which contains (along with some other useful code): } ``` - - _stub_ classes that clients can use to talk to a `Greetings` server. As you can see, they also implement the `Greetings` interface. + - _stub_ classes that clients can use to talk to a `Greetings` server. As + you can see, they also implement the `Greetings` interface. ```java public static class GreetingsStub extends @@ -282,7 +286,8 @@ Our server application has two classes: [GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). - a server that hosts the service implementation and allows access over the -network: [GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java). +network: +[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java). #### Service implementation @@ -290,8 +295,9 @@ network: [GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) actually implements our GreetingService's required behaviour. As you can see, the class `GreetingsImpl` implements the interface -`GreetingsGrpc.Greetings` that we [generated](#Generating gRPC code) from our proto -[IDL](java/src/main/proto/helloworld.proto) by implementing the method `hello`: +`GreetingsGrpc.Greetings` that we [generated](#generating) from +our proto +[IDL](proto/helloworld.proto) by implementing the method `hello`: ```java public void hello(Helloworld.HelloRequest req, @@ -312,13 +318,15 @@ To return our response to the client and complete the call: 1. We construct and populate a `HelloReply` response object with our exciting message, as specified in our interface definition. -2. We use the`responseObserver` to return the `HelloReply` to the client and then specify that we've finished dealing with the RPC +2. We use the`responseObserver` to return the `HelloReply` to the client +and then specify that we've finished dealing with the RPC #### Server implementation [GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) -shows the other main feature required to provide a gRPC service; making the service +shows the other main feature required to provide a gRPC service; making +the service implementation available from the network. ```java @@ -334,7 +342,8 @@ implementation available from the network. ``` -Here we create an appropriate gRPC server, binding the `GreetingsService` implementation that we created to a +Here we create an appropriate gRPC server, binding the `GreetingsService` +implementation that we created to a port. Then we start the server running: the server is now ready to receive requests from `Greetings` service clients on our specified port. We'll cover how all this works in a bit more detail in our language-specific documentation. @@ -357,12 +366,14 @@ to write a simple client that can access the `Greetings` server we created in the [previous section](#server). You can see the complete client code in [GreetingsClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). -Again, we're not going to go into much detail about how to implement a client -- we'll leave that for the tutorial. +Again, we're not going to go into much detail about how to implement a client; +we'll leave that for the tutorial. #### Connecting to the service -First let's look at how we connect to the `Greetings` server. First we need to create a gRPC channel, specifying the hostname and port of the server we want to connect to. Then we use the channel to construct the stub instance. +First let's look at how we connect to the `Greetings` server. First we need +to create a gRPC channel, specifying the hostname and port of the server we +want to connect to. Then we use the channel to construct the stub instance. ```java @@ -388,7 +399,8 @@ to the server, where the response is returned asynchronously. Now we can contact the service and obtain a greeting: 1. We construct and fill in a `HelloRequest` to send to the service. -2. We call the stub's `hello()` RPC with our request and get a `HelloReply` back, +2. We call the stub's `hello()` RPC with our request and get a `HelloReply` +back, from which we can get our greeting. @@ -435,7 +447,9 @@ $ ./run_greetings_client.sh ### Adding another client -Finally, let's look at one of gRPC's most useful features - interoperability between code in different languages. So far, we've just generated Java code from our `Greetings` service definition. +Finally, let's look at one of gRPC's most useful features - interoperability +between code in different languages. So far, we've just generated Java code +from our `Greetings` service definition.... ###TODO: Section on Go client for same server From 48dbd9bd6062193c955ee02523d40ed41791287c Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Thu, 19 Feb 2015 17:47:29 +0000 Subject: [PATCH 064/576] Mergey mergey --- README.md | 63 ++++++++++++++++++++++++------------------------------- 1 file changed, 27 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 4701619b699..43c65b42a10 100644 --- a/README.md +++ b/README.md @@ -247,27 +247,26 @@ we need to create our example: - [`Helloworld.java`](java/src/main/java/ex/grpc/Helloworld.java), which has all the protocol buffer code to populate, serialize, and retrieve our `HelloRequest` and `HelloReply` message types -- [`GreetingsGrpc.java`](java/src/main/java/ex/grpc/GreetingsGrpc.java), +- [`GreeterGrpc.java`](java/src/main/java/ex/grpc/GreeterGrpc.java), which contains (along with some other useful code): - - an interface for `Greetings` servers to implement + - an interface for `Greeter` servers to implement ```java - public static interface Greetings { + public static interface Greeter { - public void hello(ex.grpc.Helloworld.HelloRequest request, + public void sayHello(ex.grpc.Helloworld.HelloRequest request, com.google.net.stubby.stub.StreamObserver responseObserver); } ``` - - _stub_ classes that clients can use to talk to a `Greetings` server. As - you can see, they also implement the `Greetings` interface. + - _stub_ classes that clients can use to talk to a `Greeter` server. As you can see, they also implement the `Greeter` interface. ```java -public static class GreetingsStub extends - com.google.net.stubby.stub.AbstractStub - implements Greetings { +public static class GreeterStub extends + com.google.net.stubby.stub.AbstractStub + implements Greeter { ... } ``` @@ -283,21 +282,18 @@ tutorial for your chosen language (coming soon). Our server application has two classes: - a simple service implementation -[GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java). +[GreeterImpl.java](java/src/main/java/ex/grpc/GreeterImpl.java). - a server that hosts the service implementation and allows access over the -network: -[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java). +network: [GreeterServer.java](java/src/main/java/ex/grpc/GreeterServer.java). #### Service implementation -[GreetingsImpl.java](java/src/main/java/ex/grpc/GreetingsImpl.java) +[GreeterImpl.java](java/src/main/java/ex/grpc/GreeterImpl.java) actually implements our GreetingService's required behaviour. -As you can see, the class `GreetingsImpl` implements the interface -`GreetingsGrpc.Greetings` that we [generated](#generating) from -our proto -[IDL](proto/helloworld.proto) by implementing the method `hello`: +As you can see, the class `GreeterImpl` implements the interface +`GreeterGrpc.Greeter` that we [generated](#generating) from our proto ```java public void hello(Helloworld.HelloRequest req, @@ -324,9 +320,8 @@ and then specify that we've finished dealing with the RPC #### Server implementation -[GreetingsServer.java](java/src/main/java/ex/grpc/GreetingsServer.java) -shows the other main feature required to provide a gRPC service; making -the service +[GreeterServer.java](java/src/main/java/ex/grpc/GreeterServer.java) +shows the other main feature required to provide a gRPC service; making the service implementation available from the network. ```java @@ -334,7 +329,7 @@ implementation available from the network. ... private void start() throws Exception { server = NettyServerBuilder.forPort(port) - .addService(GreetingsGrpc.bindService(new GreetingsImpl())) + .addService(GreeterGrpc.bindService(new GreeterImpl())) .build(); server.startAsync(); server.awaitRunning(5, TimeUnit.SECONDS); @@ -342,10 +337,11 @@ implementation available from the network. ``` -Here we create an appropriate gRPC server, binding the `GreetingsService` + +Here we create an appropriate gRPC server, binding the `GreeterService` implementation that we created to a port. Then we start the server running: the server is now ready to receive -requests from `Greetings` service clients on our specified port. We'll cover +requests from `Greeter` service clients on our specified port. We'll cover how all this works in a bit more detail in our language-specific documentation. #### Build it @@ -362,9 +358,9 @@ We'll look at using a client to access the server in the next section. ### Writing a client Client-side gRPC is pretty simple. In this step, we'll use the generated code -to write a simple client that can access the `Greetings` server we created +to write a simple client that can access the `Greeter` server we created in the [previous section](#server). You can see the complete client code in -[GreetingsClient.java](java/src/main/java/ex/grpc/GreetingsClient.java). +[GreeterClient.java](java/src/main/java/ex/grpc/GreeterClient.java). Again, we're not going to go into much detail about how to implement a client; we'll leave that for the tutorial. @@ -378,13 +374,13 @@ want to connect to. Then we use the channel to construct the stub instance. ```java private final ChannelImpl channel; - private final GreetingGrpc.GreetingBlockingStub blockingStub; + private final GreeterGrpc.GreeterBlockingStub blockingStub; public HelloClient(String host, int port) { channel = NettyChannelBuilder.forAddress(host, port) .negotiationType(NegotiationType.PLAINTEXT) .build(); - blockingStub = GreetingGrpc.newBlockingStub(channel); + blockingStub = GreeterGrpc.newBlockingStub(channel); } ``` @@ -410,7 +406,7 @@ from which we can get our greeting. try { Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName(name).build(); - Helloworld.HelloReply reply = blockingStub.hello(request); + Helloworld.HelloReply reply = blockingStub.sayHello(request); logger.info("Greeting: " + reply.getMessage()); } catch (RuntimeException e) { logger.log(Level.WARNING, "RPC failed", e); @@ -436,13 +432,13 @@ We've added simple shell scripts to simplifying running the examples. Now that they are built, you can run the server with: ```sh -$ ./run_greetings_server.sh +$ ./run_greeter_server.sh ``` and in another terminal window confirm that it receives a message. ```sh -$ ./run_greetings_client.sh +$ ./run_greeter_client.sh ``` ### Adding another client @@ -452,8 +448,3 @@ between code in different languages. So far, we've just generated Java code from our `Greetings` service definition.... ###TODO: Section on Go client for same server - - - - - From 49f3ccdd012153c8c286f54baf2d4a925c1b4314 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Thu, 19 Feb 2015 11:09:19 -0800 Subject: [PATCH 065/576] Adds a helloworld sample in ruby. --- ruby/.gitignore | 15 +++++++++ ruby/Gemfile | 15 +++++++++ ruby/README.md | 35 +++++++++++++++++++ ruby/greeter.gemspec | 23 +++++++++++++ ruby/greeter_client.rb | 50 +++++++++++++++++++++++++++ ruby/greeter_server.rb | 60 +++++++++++++++++++++++++++++++++ ruby/lib/helloworld.rb | 18 ++++++++++ ruby/lib/helloworld_services.rb | 24 +++++++++++++ 8 files changed, 240 insertions(+) create mode 100644 ruby/.gitignore create mode 100644 ruby/Gemfile create mode 100644 ruby/README.md create mode 100644 ruby/greeter.gemspec create mode 100755 ruby/greeter_client.rb create mode 100755 ruby/greeter_server.rb create mode 100644 ruby/lib/helloworld.rb create mode 100644 ruby/lib/helloworld_services.rb diff --git a/ruby/.gitignore b/ruby/.gitignore new file mode 100644 index 00000000000..62fcb4fa943 --- /dev/null +++ b/ruby/.gitignore @@ -0,0 +1,15 @@ +/.bundle/ +/.yardoc +/Gemfile.lock +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ +*.bundle +*.so +*.o +*.a +mkmf.log +vendor diff --git a/ruby/Gemfile b/ruby/Gemfile new file mode 100644 index 00000000000..2d76038e09d --- /dev/null +++ b/ruby/Gemfile @@ -0,0 +1,15 @@ +# -*- ruby -*- +# encoding: utf-8 + +source 'https://rubygems.org/' + +# Update this to reflect the local installation of gRPC. +gem 'grpc', path: '/usr/local/google/repos/grpc/src/ruby' + +# TODO: fix this if/when the gRPC repo structure changes. +# +# At the moment it's not possible to use grpc Ruby via git/github reference +# +# git 'git@github.com:grpc/grpc.git' do +# gem 'grpc' +# end diff --git a/ruby/README.md b/ruby/README.md new file mode 100644 index 00000000000..668baf3eb71 --- /dev/null +++ b/ruby/README.md @@ -0,0 +1,35 @@ +gRPC Ruby Helloworld +==================== + +INSTALLATION PREREQUISITES +-------------------------- + +This requires Ruby 2.x, as the gRPC API surface uses keyword args. + +INSTALL +------- + +- Clone this repository. +- Follow the instructions in [INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL) to install the gRPC C core. +- *Temporary* Install gRPC for Ruby from source on your local machine and update path: to refer to it [Gemfile]. + - this is needed until the gRPC ruby gem is published +- Use bundler to install +```sh +$ # from this directory +$ gem install bundler && bundle install +``` + +USAGE +----- + +- Run the server +```sh +$ # from this directory +$ bundle exec ./greeter_server.rb & +``` + +- Run the client +```sh +$ # from this directory +$ bundle exec ./greeter_client.rb +``` diff --git a/ruby/greeter.gemspec b/ruby/greeter.gemspec new file mode 100644 index 00000000000..d0ccf32f7d5 --- /dev/null +++ b/ruby/greeter.gemspec @@ -0,0 +1,23 @@ +# -*- ruby -*- +# encoding: utf-8 + +Gem::Specification.new do |s| + s.name = 'grpc' + s.version = '0.0.0' + s.authors = ['gRPC Authors'] + s.email = 'temiola@google.com' + s.homepage = 'https://github.com/google/grpc-common' + s.summary = 'gRPC Ruby overview sample' + s.description = 'Demonstrates how' + + s.files = `git ls-files -- ruby/*`.split("\n") + s.executables = `git ls-files -- ruby/greeter*.rb`.split("\n").map do |f| + File.basename(f) + end + s.require_paths = ['lib'] + s.platform = Gem::Platform::RUBY + + s.add_dependency 'grpc', '~> 0.0.1' + + s.add_development_dependency 'bundler', '~> 1.7' +end diff --git a/ruby/greeter_client.rb b/ruby/greeter_client.rb new file mode 100755 index 00000000000..e6cb4bad33e --- /dev/null +++ b/ruby/greeter_client.rb @@ -0,0 +1,50 @@ +#!/usr/bin/env ruby + +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Sample app that connects to a Greeter service. +# +# Usage: $ path/to/greeter_client.rb + +this_dir = File.expand_path(File.dirname(__FILE__)) +lib_dir = File.join(this_dir, 'lib') +$LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir) + +require 'grpc' +require 'helloworld_services' + +def main + stub = Helloworld::Greeter::Stub.new('localhost:50051') + user = ARGV.size > 0 ? ARGV[0] : 'world' + message = stub.say_hello(Helloworld::HelloRequest.new(name: user)).message + p "Greeting: #{message}" +end + +main diff --git a/ruby/greeter_server.rb b/ruby/greeter_server.rb new file mode 100755 index 00000000000..eb1a6ab454c --- /dev/null +++ b/ruby/greeter_server.rb @@ -0,0 +1,60 @@ +#!/usr/bin/env ruby + +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Sample gRPC server that implements the Greeter::Helloworld service. +# +# Usage: $ path/to/greeter_server.rb + +this_dir = File.expand_path(File.dirname(__FILE__)) +lib_dir = File.join(this_dir, 'lib') +$LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir) + +require 'grpc' +require 'helloworld_services' + +# GreeterServer is simple server that implements the Helloworld Greeter server. +class GreeterServer < Helloworld::Greeter::Service + # say_hello implements the sayHello rpc method. + def say_hello(hello_req, _unused_call) + Helloworld::HelloReply.new(message: "Hello #{hello_req.name}") + end +end + +# main starts an RpcServer that receives requests to GreeterServer at the sample +# server port. +def main + s = GRPC::RpcServer.new + s.add_http2_port('0.0.0.0:50051') + s.handle(GreeterServer) + s.run +end + +main diff --git a/ruby/lib/helloworld.rb b/ruby/lib/helloworld.rb new file mode 100644 index 00000000000..82bdd78e2a4 --- /dev/null +++ b/ruby/lib/helloworld.rb @@ -0,0 +1,18 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: helloworld.proto + +require 'google/protobuf' + +Google::Protobuf::DescriptorPool.generated_pool.build do + add_message "helloworld.HelloRequest" do + optional :name, :string, 1 + end + add_message "helloworld.HelloReply" do + optional :message, :string, 1 + end +end + +module Helloworld + HelloRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("helloworld.HelloRequest").msgclass + HelloReply = Google::Protobuf::DescriptorPool.generated_pool.lookup("helloworld.HelloReply").msgclass +end diff --git a/ruby/lib/helloworld_services.rb b/ruby/lib/helloworld_services.rb new file mode 100644 index 00000000000..9bd528485af --- /dev/null +++ b/ruby/lib/helloworld_services.rb @@ -0,0 +1,24 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# Source: helloworld.proto for package 'helloworld' + +require 'grpc' +require 'helloworld' + +module Helloworld + module Greeter + + # TODO: add proto service documentation here + class Service + + include GRPC::GenericService + + self.marshal_class_method = :encode + self.unmarshal_class_method = :decode + self.service_name = 'helloworld.Greeter' + + rpc :sayHello, HelloRequest, HelloReply + end + + Stub = Service.rpc_stub_class + end +end From c1500a5abb97912618fe72bbf89a4a531ecbc453 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Thu, 19 Feb 2015 11:46:19 -0800 Subject: [PATCH 066/576] Minor corrections --- ruby/greeter.gemspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby/greeter.gemspec b/ruby/greeter.gemspec index d0ccf32f7d5..be1afae7de2 100644 --- a/ruby/greeter.gemspec +++ b/ruby/greeter.gemspec @@ -6,9 +6,9 @@ Gem::Specification.new do |s| s.version = '0.0.0' s.authors = ['gRPC Authors'] s.email = 'temiola@google.com' - s.homepage = 'https://github.com/google/grpc-common' + s.homepage = 'https://github.com/grpc/grpc-common' s.summary = 'gRPC Ruby overview sample' - s.description = 'Demonstrates how' + s.description = 'Simple demo of using gRPC from Ruby' s.files = `git ls-files -- ruby/*`.split("\n") s.executables = `git ls-files -- ruby/greeter*.rb`.split("\n").map do |f| From 7b68400fa42ad54fd35fe28d29e6415c5de35441 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Thu, 19 Feb 2015 12:52:26 -0800 Subject: [PATCH 067/576] Fixes the gem name. --- ruby/greeter.gemspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby/greeter.gemspec b/ruby/greeter.gemspec index be1afae7de2..795c84c0f5f 100644 --- a/ruby/greeter.gemspec +++ b/ruby/greeter.gemspec @@ -2,8 +2,8 @@ # encoding: utf-8 Gem::Specification.new do |s| - s.name = 'grpc' - s.version = '0.0.0' + s.name = 'grpc-greeter' + s.version = '0.1.0' s.authors = ['gRPC Authors'] s.email = 'temiola@google.com' s.homepage = 'https://github.com/grpc/grpc-common' From e89af55a86cd742a076463ee5a639212b029e511 Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Thu, 19 Feb 2015 13:33:04 -0800 Subject: [PATCH 068/576] Added node hello world example --- node/.gitignore | 3 ++ node/README.md | 30 ++++++++++++++++++++ node/greeter_client.js | 52 ++++++++++++++++++++++++++++++++++ node/greeter_server.js | 63 ++++++++++++++++++++++++++++++++++++++++++ node/helloworld.proto | 50 +++++++++++++++++++++++++++++++++ node/package.json | 7 +++++ 6 files changed, 205 insertions(+) create mode 100644 node/.gitignore create mode 100644 node/README.md create mode 100644 node/greeter_client.js create mode 100644 node/greeter_server.js create mode 100644 node/helloworld.proto create mode 100644 node/package.json diff --git a/node/.gitignore b/node/.gitignore new file mode 100644 index 00000000000..3d06f5db7b3 --- /dev/null +++ b/node/.gitignore @@ -0,0 +1,3 @@ +*~ +node_modules +npm-debug.log \ No newline at end of file diff --git a/node/README.md b/node/README.md new file mode 100644 index 00000000000..4b2c9026892 --- /dev/null +++ b/node/README.md @@ -0,0 +1,30 @@ +# gRPC Node.js Helloworld + +## INSTALLATION REQUIREMENTS + +This requires Node 10.x or greater. + +## INSTALL + + - Clone this repository + - Follow the instructions in [INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL) to install the gRPC C core. + - Run `npm install` to install dependencies + - If `grpc` is not found, clone the [gRPC](https://github.com/grpc/grpc) repository and run `npm install path/to/grpc/src/node`. + +## USAGE + + - Run the server + ```sh + $ # from this directory + $ nodejs ./greeter_server.js & + ``` + - Run the client + ```sh + $ # from this directory + $ nodejs ./greeter_client.js + ``` + +## NOTE + +This directory has a copy of `helloworld.proto` because it currently depends on +some Protocol Buffer 2.0 syntax that is deprecated in Protocol Buffer 3.0. diff --git a/node/greeter_client.js b/node/greeter_client.js new file mode 100644 index 00000000000..ab7050ab213 --- /dev/null +++ b/node/greeter_client.js @@ -0,0 +1,52 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +var PROTO_PATH = __dirname + '/helloworld.proto'; + +var grpc = require('grpc'); +var hello_proto = grpc.load(PROTO_PATH).helloworld; + +function main() { + var client = new hello_proto.Greeter('localhost:50051'); + var user; + if (process.argv.length >= 3) { + user = process.argv[2]; + } else { + user = 'world'; + } + client.sayHello({name: user}, function(err, response) { + console.log('Greeting:', response.message); + }); +} + +main(); diff --git a/node/greeter_server.js b/node/greeter_server.js new file mode 100644 index 00000000000..6d4183c0ced --- /dev/null +++ b/node/greeter_server.js @@ -0,0 +1,63 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +var PROTO_PATH = __dirname + '/helloworld.proto'; + +var grpc = require('grpc'); +var hello_proto = grpc.load(PROTO_PATH).helloworld; + +var Server = grpc.buildServer([hello_proto.Greeter.service]); + +/** + * Implements the sayHello RPC method. + */ +function sayHello(call, callback) { + callback(null, {message: 'Hello ' + call.request.name}); +} + +/** + * Starts an RPC server that receives requests for the Greeter service at the + * sample server port + */ +function main() { + var server = new Server({ + "helloworld.Greeter": { + sayHello: sayHello + } + }); + + server.bind('0.0.0.0:50051'); + server.listen(); +} + +main(); diff --git a/node/helloworld.proto b/node/helloworld.proto new file mode 100644 index 00000000000..e1f5700725a --- /dev/null +++ b/node/helloworld.proto @@ -0,0 +1,50 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +option java_package = "ex.grpc"; + +package helloworld; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc sayHello (HelloRequest) returns (HelloReply) {} +} + +// The request message containing the user's name. +message HelloRequest { + optional string name = 1; +} + +// The response message containing the greetings +message HelloReply { + optional string message = 1; +} diff --git a/node/package.json b/node/package.json new file mode 100644 index 00000000000..435654034fa --- /dev/null +++ b/node/package.json @@ -0,0 +1,7 @@ +{ + "name": "grpc-greeter", + "version": "0.1.0", + "dependencies": { + "grpc" : "~0.2.0" + } +} From ec8fa8339ed06df87c529f4900a03d8d234d0116 Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Thu, 19 Feb 2015 13:35:13 -0800 Subject: [PATCH 069/576] Fixed formatting --- node/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/node/README.md b/node/README.md index 4b2c9026892..57dc83ee3f3 100644 --- a/node/README.md +++ b/node/README.md @@ -14,11 +14,14 @@ This requires Node 10.x or greater. ## USAGE - Run the server + ```sh $ # from this directory $ nodejs ./greeter_server.js & ``` + - Run the client + ```sh $ # from this directory $ nodejs ./greeter_client.js From d95693724c45648f2f023cff29df11fc1d9910dd Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Thu, 19 Feb 2015 14:22:52 -0800 Subject: [PATCH 070/576] Add helloworld example in c++ --- cpp/helloworld/Makefile | 47 +++ cpp/helloworld/greeter_client.cc | 91 +++++ cpp/helloworld/greeter_server.cc | 84 ++++ cpp/helloworld/helloworld.pb.cc | 640 +++++++++++++++++++++++++++++++ cpp/helloworld/helloworld.pb.h | 359 +++++++++++++++++ 5 files changed, 1221 insertions(+) create mode 100644 cpp/helloworld/Makefile create mode 100644 cpp/helloworld/greeter_client.cc create mode 100644 cpp/helloworld/greeter_server.cc create mode 100644 cpp/helloworld/helloworld.pb.cc create mode 100644 cpp/helloworld/helloworld.pb.h diff --git a/cpp/helloworld/Makefile b/cpp/helloworld/Makefile new file mode 100644 index 00000000000..38f4ff081fd --- /dev/null +++ b/cpp/helloworld/Makefile @@ -0,0 +1,47 @@ +# +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +CC=g++ +CCFLAGS=-I/usr/local/include -std=c++11 +LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -ldl + +all: greeter_client greeter_server + +greeter_client: helloworld.pb.cc greeter_client.cc + $(CC) $(CCFLAGS) greeter_client.cc helloworld.pb.cc $(LDFLAGS) -o greeter_client.out + + +greeter_server: helloworld.pb.cc greeter_server.cc + $(CC) $(CCFLAGS) greeter_server.cc helloworld.pb.cc $(LDFLAGS) -o greeter_server.out + +clean: + rm *.out + diff --git a/cpp/helloworld/greeter_client.cc b/cpp/helloworld/greeter_client.cc new file mode 100644 index 00000000000..4a51f5eb382 --- /dev/null +++ b/cpp/helloworld/greeter_client.cc @@ -0,0 +1,91 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "helloworld.pb.h" + +using grpc::ChannelArguments; +using grpc::ChannelInterface; +using grpc::ClientContext; +using grpc::Status; +using helloworld::HelloRequest; +using helloworld::HelloReply; +using helloworld::Greeter; + +class GreeterClient { + public: + GreeterClient(std::shared_ptr channel) + : stub_(Greeter::NewStub(channel)) {} + + std::string SayHello(const std::string& user) { + HelloRequest request; + request.set_name(user); + HelloReply reply; + ClientContext context; + + Status status = stub_->sayHello(&context, request, &reply); + if (status.IsOk()) { + return reply.message(); + } else { + return "Rpc failed"; + } + } + + void Shutdown() { stub_.reset(); } + + private: + std::unique_ptr stub_; +}; + +int main(int argc, char** argv) { + grpc_init(); + + GreeterClient greeter( + grpc::CreateChannel("localhost:50051", ChannelArguments())); + std::string user("world"); + std::string reply = greeter.SayHello(user); + std::cout << "Greeter received: " << reply << std::endl; + + greeter.Shutdown(); + + grpc_shutdown(); +} diff --git a/cpp/helloworld/greeter_server.cc b/cpp/helloworld/greeter_server.cc new file mode 100644 index 00000000000..3a2ab60e892 --- /dev/null +++ b/cpp/helloworld/greeter_server.cc @@ -0,0 +1,84 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include "helloworld.pb.h" + +using grpc::Server; +using grpc::ServerBuilder; +using grpc::ServerContext; +using grpc::Status; +using helloworld::HelloRequest; +using helloworld::HelloReply; +using helloworld::Greeter; + +class GreeterServiceImpl final : public Greeter::Service { + Status sayHello(ServerContext* context, const HelloRequest* request, + HelloReply* reply) override { + std::string prefix("Hello "); + reply->set_message(prefix + request->name()); + return Status::OK; + } +}; + +void RunServer() { + std::string server_address("0.0.0.0:50051"); + GreeterServiceImpl service; + + ServerBuilder builder; + builder.AddPort(server_address); + builder.RegisterService(&service); + std::unique_ptr server(builder.BuildAndStart()); + std::cout << "Server listening on " << server_address << std::endl; + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(5)); + } +} + +int main(int argc, char** argv) { + grpc_init(); + + RunServer(); + + grpc_shutdown(); + return 0; +} diff --git a/cpp/helloworld/helloworld.pb.cc b/cpp/helloworld/helloworld.pb.cc new file mode 100644 index 00000000000..a5b82c5ed5b --- /dev/null +++ b/cpp/helloworld/helloworld.pb.cc @@ -0,0 +1,640 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: helloworld.proto + +#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION +#include "helloworld.pb.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// @@protoc_insertion_point(includes) + +namespace helloworld { + +namespace { + +const ::google::protobuf::Descriptor* HelloRequest_descriptor_ = NULL; +const ::google::protobuf::internal::GeneratedMessageReflection* + HelloRequest_reflection_ = NULL; +const ::google::protobuf::Descriptor* HelloReply_descriptor_ = NULL; +const ::google::protobuf::internal::GeneratedMessageReflection* + HelloReply_reflection_ = NULL; + +} // namespace + + +void protobuf_AssignDesc_helloworld_2eproto() { + protobuf_AddDesc_helloworld_2eproto(); + const ::google::protobuf::FileDescriptor* file = + ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( + "helloworld.proto"); + GOOGLE_CHECK(file != NULL); + HelloRequest_descriptor_ = file->message_type(0); + static const int HelloRequest_offsets_[1] = { + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloRequest, name_), + }; + HelloRequest_reflection_ = + ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( + HelloRequest_descriptor_, + HelloRequest::default_instance_, + HelloRequest_offsets_, + -1, + -1, + -1, + sizeof(HelloRequest), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloRequest, _internal_metadata_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloRequest, _is_default_instance_)); + HelloReply_descriptor_ = file->message_type(1); + static const int HelloReply_offsets_[1] = { + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloReply, message_), + }; + HelloReply_reflection_ = + ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( + HelloReply_descriptor_, + HelloReply::default_instance_, + HelloReply_offsets_, + -1, + -1, + -1, + sizeof(HelloReply), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloReply, _internal_metadata_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloReply, _is_default_instance_)); +} + +namespace { + +GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); +inline void protobuf_AssignDescriptorsOnce() { + ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, + &protobuf_AssignDesc_helloworld_2eproto); +} + +void protobuf_RegisterTypes(const ::std::string&) { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( + HelloRequest_descriptor_, &HelloRequest::default_instance()); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( + HelloReply_descriptor_, &HelloReply::default_instance()); +} + +} // namespace + +void protobuf_ShutdownFile_helloworld_2eproto() { + delete HelloRequest::default_instance_; + delete HelloRequest_reflection_; + delete HelloReply::default_instance_; + delete HelloReply_reflection_; +} + +void protobuf_AddDesc_helloworld_2eproto() { + static bool already_here = false; + if (already_here) return; + already_here = true; + GOOGLE_PROTOBUF_VERIFY_VERSION; + + ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( + "\n\020helloworld.proto\022\nhelloworld\"\034\n\014HelloR" + "equest\022\014\n\004name\030\001 \001(\t\"\035\n\nHelloReply\022\017\n\007me" + "ssage\030\001 \001(\t2I\n\007Greeter\022>\n\010sayHello\022\030.hel" + "loworld.HelloRequest\032\026.helloworld.HelloR" + "eply\"\000B\t\n\007ex.grpcb\006proto3", 185); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( + "helloworld.proto", &protobuf_RegisterTypes); + HelloRequest::default_instance_ = new HelloRequest(); + HelloReply::default_instance_ = new HelloReply(); + HelloRequest::default_instance_->InitAsDefaultInstance(); + HelloReply::default_instance_->InitAsDefaultInstance(); + ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_helloworld_2eproto); +} + +// Force AddDescriptors() to be called at static initialization time. +struct StaticDescriptorInitializer_helloworld_2eproto { + StaticDescriptorInitializer_helloworld_2eproto() { + protobuf_AddDesc_helloworld_2eproto(); + } +} static_descriptor_initializer_helloworld_2eproto_; + +namespace { + +static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD; +static void MergeFromFail(int line) { + GOOGLE_CHECK(false) << __FILE__ << ":" << line; +} + +} // namespace + + +// =================================================================== + +#ifndef _MSC_VER +const int HelloRequest::kNameFieldNumber; +#endif // !_MSC_VER + +HelloRequest::HelloRequest() + : ::google::protobuf::Message() , _internal_metadata_(NULL) { + SharedCtor(); + // @@protoc_insertion_point(constructor:helloworld.HelloRequest) +} + +void HelloRequest::InitAsDefaultInstance() { + _is_default_instance_ = true; +} + +HelloRequest::HelloRequest(const HelloRequest& from) + : ::google::protobuf::Message(), + _internal_metadata_(NULL) { + SharedCtor(); + MergeFrom(from); + // @@protoc_insertion_point(copy_constructor:helloworld.HelloRequest) +} + +void HelloRequest::SharedCtor() { + _is_default_instance_ = false; + ::google::protobuf::internal::GetEmptyString(); + _cached_size_ = 0; + name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} + +HelloRequest::~HelloRequest() { + // @@protoc_insertion_point(destructor:helloworld.HelloRequest) + SharedDtor(); +} + +void HelloRequest::SharedDtor() { + name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + if (this != default_instance_) { + } +} + +void HelloRequest::SetCachedSize(int size) const { + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); +} +const ::google::protobuf::Descriptor* HelloRequest::descriptor() { + protobuf_AssignDescriptorsOnce(); + return HelloRequest_descriptor_; +} + +const HelloRequest& HelloRequest::default_instance() { + if (default_instance_ == NULL) protobuf_AddDesc_helloworld_2eproto(); + return *default_instance_; +} + +HelloRequest* HelloRequest::default_instance_ = NULL; + +HelloRequest* HelloRequest::New(::google::protobuf::Arena* arena) const { + HelloRequest* n = new HelloRequest; + if (arena != NULL) { + arena->Own(n); + } + return n; +} + +void HelloRequest::Clear() { + name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} + +bool HelloRequest::MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure + ::google::protobuf::uint32 tag; + // @@protoc_insertion_point(parse_start:helloworld.HelloRequest) + for (;;) { + ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); + tag = p.first; + if (!p.second) goto handle_unusual; + switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + // optional string name = 1; + case 1: { + if (tag == 10) { + DO_(::google::protobuf::internal::WireFormatLite::ReadString( + input, this->mutable_name())); + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->name().data(), this->name().length(), + ::google::protobuf::internal::WireFormat::PARSE, + "helloworld.HelloRequest.name"); + } else { + goto handle_unusual; + } + if (input->ExpectAtEnd()) goto success; + break; + } + + default: { + handle_unusual: + if (tag == 0 || + ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == + ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { + goto success; + } + DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); + break; + } + } + } +success: + // @@protoc_insertion_point(parse_success:helloworld.HelloRequest) + return true; +failure: + // @@protoc_insertion_point(parse_failure:helloworld.HelloRequest) + return false; +#undef DO_ +} + +void HelloRequest::SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const { + // @@protoc_insertion_point(serialize_start:helloworld.HelloRequest) + // optional string name = 1; + if (this->name().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->name().data(), this->name().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "helloworld.HelloRequest.name"); + ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + 1, this->name(), output); + } + + // @@protoc_insertion_point(serialize_end:helloworld.HelloRequest) +} + +::google::protobuf::uint8* HelloRequest::SerializeWithCachedSizesToArray( + ::google::protobuf::uint8* target) const { + // @@protoc_insertion_point(serialize_to_array_start:helloworld.HelloRequest) + // optional string name = 1; + if (this->name().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->name().data(), this->name().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "helloworld.HelloRequest.name"); + target = + ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + 1, this->name(), target); + } + + // @@protoc_insertion_point(serialize_to_array_end:helloworld.HelloRequest) + return target; +} + +int HelloRequest::ByteSize() const { + int total_size = 0; + + // optional string name = 1; + if (this->name().size() > 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::StringSize( + this->name()); + } + + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = total_size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); + return total_size; +} + +void HelloRequest::MergeFrom(const ::google::protobuf::Message& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + const HelloRequest* source = + ::google::protobuf::internal::dynamic_cast_if_available( + &from); + if (source == NULL) { + ::google::protobuf::internal::ReflectionOps::Merge(from, this); + } else { + MergeFrom(*source); + } +} + +void HelloRequest::MergeFrom(const HelloRequest& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + if (from.name().size() > 0) { + + name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + } +} + +void HelloRequest::CopyFrom(const ::google::protobuf::Message& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +void HelloRequest::CopyFrom(const HelloRequest& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool HelloRequest::IsInitialized() const { + + return true; +} + +void HelloRequest::Swap(HelloRequest* other) { + if (other == this) return; + InternalSwap(other); +} +void HelloRequest::InternalSwap(HelloRequest* other) { + name_.Swap(&other->name_); + _internal_metadata_.Swap(&other->_internal_metadata_); + std::swap(_cached_size_, other->_cached_size_); +} + +::google::protobuf::Metadata HelloRequest::GetMetadata() const { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::Metadata metadata; + metadata.descriptor = HelloRequest_descriptor_; + metadata.reflection = HelloRequest_reflection_; + return metadata; +} + + +// =================================================================== + +#ifndef _MSC_VER +const int HelloReply::kMessageFieldNumber; +#endif // !_MSC_VER + +HelloReply::HelloReply() + : ::google::protobuf::Message() , _internal_metadata_(NULL) { + SharedCtor(); + // @@protoc_insertion_point(constructor:helloworld.HelloReply) +} + +void HelloReply::InitAsDefaultInstance() { + _is_default_instance_ = true; +} + +HelloReply::HelloReply(const HelloReply& from) + : ::google::protobuf::Message(), + _internal_metadata_(NULL) { + SharedCtor(); + MergeFrom(from); + // @@protoc_insertion_point(copy_constructor:helloworld.HelloReply) +} + +void HelloReply::SharedCtor() { + _is_default_instance_ = false; + ::google::protobuf::internal::GetEmptyString(); + _cached_size_ = 0; + message_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} + +HelloReply::~HelloReply() { + // @@protoc_insertion_point(destructor:helloworld.HelloReply) + SharedDtor(); +} + +void HelloReply::SharedDtor() { + message_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + if (this != default_instance_) { + } +} + +void HelloReply::SetCachedSize(int size) const { + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); +} +const ::google::protobuf::Descriptor* HelloReply::descriptor() { + protobuf_AssignDescriptorsOnce(); + return HelloReply_descriptor_; +} + +const HelloReply& HelloReply::default_instance() { + if (default_instance_ == NULL) protobuf_AddDesc_helloworld_2eproto(); + return *default_instance_; +} + +HelloReply* HelloReply::default_instance_ = NULL; + +HelloReply* HelloReply::New(::google::protobuf::Arena* arena) const { + HelloReply* n = new HelloReply; + if (arena != NULL) { + arena->Own(n); + } + return n; +} + +void HelloReply::Clear() { + message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} + +bool HelloReply::MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure + ::google::protobuf::uint32 tag; + // @@protoc_insertion_point(parse_start:helloworld.HelloReply) + for (;;) { + ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); + tag = p.first; + if (!p.second) goto handle_unusual; + switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + // optional string message = 1; + case 1: { + if (tag == 10) { + DO_(::google::protobuf::internal::WireFormatLite::ReadString( + input, this->mutable_message())); + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->message().data(), this->message().length(), + ::google::protobuf::internal::WireFormat::PARSE, + "helloworld.HelloReply.message"); + } else { + goto handle_unusual; + } + if (input->ExpectAtEnd()) goto success; + break; + } + + default: { + handle_unusual: + if (tag == 0 || + ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == + ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { + goto success; + } + DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); + break; + } + } + } +success: + // @@protoc_insertion_point(parse_success:helloworld.HelloReply) + return true; +failure: + // @@protoc_insertion_point(parse_failure:helloworld.HelloReply) + return false; +#undef DO_ +} + +void HelloReply::SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const { + // @@protoc_insertion_point(serialize_start:helloworld.HelloReply) + // optional string message = 1; + if (this->message().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->message().data(), this->message().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "helloworld.HelloReply.message"); + ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + 1, this->message(), output); + } + + // @@protoc_insertion_point(serialize_end:helloworld.HelloReply) +} + +::google::protobuf::uint8* HelloReply::SerializeWithCachedSizesToArray( + ::google::protobuf::uint8* target) const { + // @@protoc_insertion_point(serialize_to_array_start:helloworld.HelloReply) + // optional string message = 1; + if (this->message().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->message().data(), this->message().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "helloworld.HelloReply.message"); + target = + ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + 1, this->message(), target); + } + + // @@protoc_insertion_point(serialize_to_array_end:helloworld.HelloReply) + return target; +} + +int HelloReply::ByteSize() const { + int total_size = 0; + + // optional string message = 1; + if (this->message().size() > 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::StringSize( + this->message()); + } + + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = total_size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); + return total_size; +} + +void HelloReply::MergeFrom(const ::google::protobuf::Message& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + const HelloReply* source = + ::google::protobuf::internal::dynamic_cast_if_available( + &from); + if (source == NULL) { + ::google::protobuf::internal::ReflectionOps::Merge(from, this); + } else { + MergeFrom(*source); + } +} + +void HelloReply::MergeFrom(const HelloReply& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + if (from.message().size() > 0) { + + message_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.message_); + } +} + +void HelloReply::CopyFrom(const ::google::protobuf::Message& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +void HelloReply::CopyFrom(const HelloReply& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool HelloReply::IsInitialized() const { + + return true; +} + +void HelloReply::Swap(HelloReply* other) { + if (other == this) return; + InternalSwap(other); +} +void HelloReply::InternalSwap(HelloReply* other) { + message_.Swap(&other->message_); + _internal_metadata_.Swap(&other->_internal_metadata_); + std::swap(_cached_size_, other->_cached_size_); +} + +::google::protobuf::Metadata HelloReply::GetMetadata() const { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::Metadata metadata; + metadata.descriptor = HelloReply_descriptor_; + metadata.reflection = HelloReply_reflection_; + return metadata; +} + + +static const char* Greeter_method_names[] = { + "/helloworld.Greeter/sayHello", +}; + +Greeter::Stub* Greeter::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) { + Greeter::Stub* stub = new Greeter::Stub(); + stub->set_channel(channel); + return stub; +}; + +::grpc::Status Greeter::Stub::sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response) { + return ::grpc::BlockingUnaryCall(channel(),::grpc::RpcMethod(Greeter_method_names[0]), context, request, response); +} + +::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* Greeter::Stub::sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag) { + return new ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>(channel(), cq, ::grpc::RpcMethod(Greeter_method_names[0]), context, request, tag); +} + +Greeter::AsyncService::AsyncService(::grpc::CompletionQueue* cq) : ::grpc::AsynchronousService(cq, Greeter_method_names, 1) {} + +Greeter::Service::~Service() { + delete service_; +} + +::grpc::Status Greeter::Service::sayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloReply* response) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); +} + +void Greeter::AsyncService::RequestsayHello(::grpc::ServerContext* context, ::helloworld::HelloRequest* request, ::grpc::ServerAsyncResponseWriter< ::helloworld::HelloReply>* response, ::grpc::CompletionQueue* cq, void* tag) { + AsynchronousService::RequestAsyncUnary(0, context, request, response, cq, tag); +} + +::grpc::RpcService* Greeter::Service::service() { + if (service_ != nullptr) { + return service_; + } + service_ = new ::grpc::RpcService(); + service_->AddMethod(new ::grpc::RpcServiceMethod( + Greeter_method_names[0], + ::grpc::RpcMethod::NORMAL_RPC, + new ::grpc::RpcMethodHandler< Greeter::Service, ::helloworld::HelloRequest, ::helloworld::HelloReply>( + std::function< ::grpc::Status(Greeter::Service*, ::grpc::ServerContext*, const ::helloworld::HelloRequest*, ::helloworld::HelloReply*)>(&Greeter::Service::sayHello), this), + new ::helloworld::HelloRequest, new ::helloworld::HelloReply)); + return service_; +} + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace helloworld + +// @@protoc_insertion_point(global_scope) diff --git a/cpp/helloworld/helloworld.pb.h b/cpp/helloworld/helloworld.pb.h new file mode 100644 index 00000000000..f49adae84a8 --- /dev/null +++ b/cpp/helloworld/helloworld.pb.h @@ -0,0 +1,359 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: helloworld.proto + +#ifndef PROTOBUF_helloworld_2eproto__INCLUDED +#define PROTOBUF_helloworld_2eproto__INCLUDED + +#include + +#include + +#if GOOGLE_PROTOBUF_VERSION < 3000000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace grpc { +class CompletionQueue; +class ChannelInterface; +class RpcService; +class ServerContext; +template class ClientAsyncResponseReader; +template class ServerAsyncResponseWriter; +} // namespace grpc +// @@protoc_insertion_point(includes) + +namespace helloworld { + +// Internal implementation detail -- do not call these. +void protobuf_AddDesc_helloworld_2eproto(); +void protobuf_AssignDesc_helloworld_2eproto(); +void protobuf_ShutdownFile_helloworld_2eproto(); + +class HelloRequest; +class HelloReply; + +// =================================================================== + +class HelloRequest : public ::google::protobuf::Message { + public: + HelloRequest(); + virtual ~HelloRequest(); + + HelloRequest(const HelloRequest& from); + + inline HelloRequest& operator=(const HelloRequest& from) { + CopyFrom(from); + return *this; + } + + static const ::google::protobuf::Descriptor* descriptor(); + static const HelloRequest& default_instance(); + + void Swap(HelloRequest* other); + + // implements Message ---------------------------------------------- + + inline HelloRequest* New() const { return New(NULL); } + + HelloRequest* New(::google::protobuf::Arena* arena) const; + void CopyFrom(const ::google::protobuf::Message& from); + void MergeFrom(const ::google::protobuf::Message& from); + void CopyFrom(const HelloRequest& from); + void MergeFrom(const HelloRequest& from); + void Clear(); + bool IsInitialized() const; + + int ByteSize() const; + bool MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input); + void SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const; + ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; + int GetCachedSize() const { return _cached_size_; } + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const; + void InternalSwap(HelloRequest* other); + private: + inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); + } + inline void* MaybeArenaPtr() const { + return _internal_metadata_.raw_arena_ptr(); + } + public: + + ::google::protobuf::Metadata GetMetadata() const; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + // optional string name = 1; + inline void clear_name(); + static const int kNameFieldNumber = 1; + inline const ::std::string& name() const; + inline void set_name(const ::std::string& value); + inline void set_name(const char* value); + inline void set_name(const char* value, size_t size); + inline ::std::string* mutable_name(); + inline ::std::string* release_name(); + inline void set_allocated_name(::std::string* name); + + // @@protoc_insertion_point(class_scope:helloworld.HelloRequest) + private: + + ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; + bool _is_default_instance_; + ::google::protobuf::internal::ArenaStringPtr name_; + mutable int _cached_size_; + friend void protobuf_AddDesc_helloworld_2eproto(); + friend void protobuf_AssignDesc_helloworld_2eproto(); + friend void protobuf_ShutdownFile_helloworld_2eproto(); + + void InitAsDefaultInstance(); + static HelloRequest* default_instance_; +}; +// ------------------------------------------------------------------- + +class HelloReply : public ::google::protobuf::Message { + public: + HelloReply(); + virtual ~HelloReply(); + + HelloReply(const HelloReply& from); + + inline HelloReply& operator=(const HelloReply& from) { + CopyFrom(from); + return *this; + } + + static const ::google::protobuf::Descriptor* descriptor(); + static const HelloReply& default_instance(); + + void Swap(HelloReply* other); + + // implements Message ---------------------------------------------- + + inline HelloReply* New() const { return New(NULL); } + + HelloReply* New(::google::protobuf::Arena* arena) const; + void CopyFrom(const ::google::protobuf::Message& from); + void MergeFrom(const ::google::protobuf::Message& from); + void CopyFrom(const HelloReply& from); + void MergeFrom(const HelloReply& from); + void Clear(); + bool IsInitialized() const; + + int ByteSize() const; + bool MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input); + void SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const; + ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; + int GetCachedSize() const { return _cached_size_; } + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const; + void InternalSwap(HelloReply* other); + private: + inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); + } + inline void* MaybeArenaPtr() const { + return _internal_metadata_.raw_arena_ptr(); + } + public: + + ::google::protobuf::Metadata GetMetadata() const; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + // optional string message = 1; + inline void clear_message(); + static const int kMessageFieldNumber = 1; + inline const ::std::string& message() const; + inline void set_message(const ::std::string& value); + inline void set_message(const char* value); + inline void set_message(const char* value, size_t size); + inline ::std::string* mutable_message(); + inline ::std::string* release_message(); + inline void set_allocated_message(::std::string* message); + + // @@protoc_insertion_point(class_scope:helloworld.HelloReply) + private: + + ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; + bool _is_default_instance_; + ::google::protobuf::internal::ArenaStringPtr message_; + mutable int _cached_size_; + friend void protobuf_AddDesc_helloworld_2eproto(); + friend void protobuf_AssignDesc_helloworld_2eproto(); + friend void protobuf_ShutdownFile_helloworld_2eproto(); + + void InitAsDefaultInstance(); + static HelloReply* default_instance_; +}; +// =================================================================== + + +// =================================================================== + +// HelloRequest + +// optional string name = 1; +inline void HelloRequest::clear_name() { + name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline const ::std::string& HelloRequest::name() const { + // @@protoc_insertion_point(field_get:helloworld.HelloRequest.name) + return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void HelloRequest::set_name(const ::std::string& value) { + + name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + // @@protoc_insertion_point(field_set:helloworld.HelloRequest.name) +} +inline void HelloRequest::set_name(const char* value) { + + name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + // @@protoc_insertion_point(field_set_char:helloworld.HelloRequest.name) +} +inline void HelloRequest::set_name(const char* value, size_t size) { + + name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + ::std::string(reinterpret_cast(value), size)); + // @@protoc_insertion_point(field_set_pointer:helloworld.HelloRequest.name) +} +inline ::std::string* HelloRequest::mutable_name() { + + // @@protoc_insertion_point(field_mutable:helloworld.HelloRequest.name) + return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline ::std::string* HelloRequest::release_name() { + + return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void HelloRequest::set_allocated_name(::std::string* name) { + if (name != NULL) { + + } else { + + } + name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + // @@protoc_insertion_point(field_set_allocated:helloworld.HelloRequest.name) +} + +// ------------------------------------------------------------------- + +// HelloReply + +// optional string message = 1; +inline void HelloReply::clear_message() { + message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline const ::std::string& HelloReply::message() const { + // @@protoc_insertion_point(field_get:helloworld.HelloReply.message) + return message_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void HelloReply::set_message(const ::std::string& value) { + + message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + // @@protoc_insertion_point(field_set:helloworld.HelloReply.message) +} +inline void HelloReply::set_message(const char* value) { + + message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + // @@protoc_insertion_point(field_set_char:helloworld.HelloReply.message) +} +inline void HelloReply::set_message(const char* value, size_t size) { + + message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + ::std::string(reinterpret_cast(value), size)); + // @@protoc_insertion_point(field_set_pointer:helloworld.HelloReply.message) +} +inline ::std::string* HelloReply::mutable_message() { + + // @@protoc_insertion_point(field_mutable:helloworld.HelloReply.message) + return message_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline ::std::string* HelloReply::release_message() { + + return message_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void HelloReply::set_allocated_message(::std::string* message) { + if (message != NULL) { + + } else { + + } + message_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), message); + // @@protoc_insertion_point(field_set_allocated:helloworld.HelloReply.message) +} + + +class Greeter final { + public: + class Stub final : public ::grpc::InternalStub { + public: + ::grpc::Status sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response); + ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag); + }; + static Stub* NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + + class Service : public ::grpc::SynchronousService { + public: + Service() : service_(nullptr) {} + virtual ~Service(); + virtual ::grpc::Status sayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloReply* response); + ::grpc::RpcService* service() override final; + private: + ::grpc::RpcService* service_; + }; + class AsyncService final : public ::grpc::AsynchronousService { + public: + explicit AsyncService(::grpc::CompletionQueue* cq); + ~AsyncService() {}; + void RequestsayHello(::grpc::ServerContext* context, ::helloworld::HelloRequest* request, ::grpc::ServerAsyncResponseWriter< ::helloworld::HelloReply>* response, ::grpc::CompletionQueue* cq, void *tag); + }; +}; + +// @@protoc_insertion_point(namespace_scope) + +} // namespace helloworld + +#ifndef SWIG +namespace google { +namespace protobuf { + + +} // namespace protobuf +} // namespace google +#endif // SWIG + +// @@protoc_insertion_point(global_scope) + +#endif // PROTOBUF_helloworld_2eproto__INCLUDED From 72bc5647960e0ec6cc9e8b5889acdf68f346286f Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Thu, 19 Feb 2015 14:45:41 -0800 Subject: [PATCH 071/576] Resolve comments on makefile --- cpp/helloworld/Makefile | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/cpp/helloworld/Makefile b/cpp/helloworld/Makefile index 38f4ff081fd..7211aa5cbe2 100644 --- a/cpp/helloworld/Makefile +++ b/cpp/helloworld/Makefile @@ -29,19 +29,28 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -CC=g++ -CCFLAGS=-I/usr/local/include -std=c++11 -LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -ldl +CXX=g++ +CPPFLAGS=-I/usr/local/include -pthread +CXXFLAGS=-std=c++11 +LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl all: greeter_client greeter_server -greeter_client: helloworld.pb.cc greeter_client.cc - $(CC) $(CCFLAGS) greeter_client.cc helloworld.pb.cc $(LDFLAGS) -o greeter_client.out +helloworld.o: helloworld.pb.cc + $(CXX) -c $(CXXFLAGS) $^ +greeter_client.o: greeter_client.cc + $(CXX) -c $(CXXFLAGS) $^ -greeter_server: helloworld.pb.cc greeter_server.cc - $(CC) $(CCFLAGS) greeter_server.cc helloworld.pb.cc $(LDFLAGS) -o greeter_server.out +greeter_server.o: greeter_server.cc + $(CXX) -c $(CXXFLAGS) $^ + +greeter_client: helloworld.pb.o greeter_client.o + $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ + +greeter_server: helloworld.pb.o greeter_server.o + $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ clean: - rm *.out + rm -f *.o greeter_client greeter_server From 2e4032e14c5f0d6b6b40b85e8321ee752d84ecf3 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Thu, 19 Feb 2015 14:52:47 -0800 Subject: [PATCH 072/576] resolve comments --- cpp/helloworld/Makefile | 9 --------- 1 file changed, 9 deletions(-) diff --git a/cpp/helloworld/Makefile b/cpp/helloworld/Makefile index 7211aa5cbe2..b9579e0c96d 100644 --- a/cpp/helloworld/Makefile +++ b/cpp/helloworld/Makefile @@ -36,15 +36,6 @@ LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl all: greeter_client greeter_server -helloworld.o: helloworld.pb.cc - $(CXX) -c $(CXXFLAGS) $^ - -greeter_client.o: greeter_client.cc - $(CXX) -c $(CXXFLAGS) $^ - -greeter_server.o: greeter_server.cc - $(CXX) -c $(CXXFLAGS) $^ - greeter_client: helloworld.pb.o greeter_client.o $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ From f00df5bb8ac523a095ec7319e726697b3187af43 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Fri, 20 Feb 2015 11:50:29 +0000 Subject: [PATCH 073/576] Simple streaming example for overview --- protos/hellostreamingworld.proto | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 protos/hellostreamingworld.proto diff --git a/protos/hellostreamingworld.proto b/protos/hellostreamingworld.proto new file mode 100644 index 00000000000..ec8405c78b3 --- /dev/null +++ b/protos/hellostreamingworld.proto @@ -0,0 +1,53 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +option java_package = "ex.grpc"; + +package hellostreamingworld; + +// The greeting service definition. +service MultiGreeter { + // Sends multiple greetings + rpc sayHello (HelloRequest) returns (stream HelloReply) {} +} + +// The request message containing the user's name and how many greetings +// they want. +message HelloRequest { + string name = 1; + string num_greetings = 2; +} + +// A response message containing a greeting +message HelloReply { + string message = 1; +} + From 81580a97bbe5411e8576409a2b681a34a070a165 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 20 Feb 2015 03:47:37 -0800 Subject: [PATCH 074/576] Adds a helloworld sample in Go. --- go/README.md | 51 +++++++++++++++ go/greeter_client/main.go | 70 +++++++++++++++++++++ go/greeter_server/main.go | 65 ++++++++++++++++++++ go/helloworld/helloworld.pb.go | 109 +++++++++++++++++++++++++++++++++ 4 files changed, 295 insertions(+) create mode 100644 go/README.md create mode 100644 go/greeter_client/main.go create mode 100644 go/greeter_server/main.go create mode 100644 go/helloworld/helloworld.pb.go diff --git a/go/README.md b/go/README.md new file mode 100644 index 00000000000..df81915c9b7 --- /dev/null +++ b/go/README.md @@ -0,0 +1,51 @@ +gRPC Go Hello World +=================== + +PREREQUISITES +------------- + +- This requires Go 1.4.x +- Requires that [GOPATH is set](https://golang.org/doc/code.html#GOPATH) +```sh +$ go help gopath +$ # ensure the PATH contains $GOPATH/bin or $GOBIN +$ export PATH=PATH: +``` + +INSTALL +------- + +```sh +$ export GOPATH= +$ go install -u github.com/grpc-common/go/greeter_client +$ go install -u github.com/grpc-common/go/greeter_server +``` + +OPTIONAL - Rebuild the generated code +------------------------------------- + +1 First [install protoc](https://github.com/google/protobuf/blob/master/INSTALL.txt) + - For now, this needs to be installed from source + - This is will change once proto3 is officially released +2 Install the protoc Go plugin. +```sh +$ go install -a github.com/golang/protobuf/protoc-gen-go +$ # ensure the PATH contains $GOPATH/bin or $GOBIN +$ export PATH=PATH: +$ +$ # from ths dir; invoke protoc +$ protoc -I ../protos ../protos/helloworld.proto --go_out=plugins=grpc:. +``` + +TRY IT! +------- + +- Run the server +```sh +$ greeter_server & +``` + +- Run the client +```sh +$ greeter_client +``` diff --git a/go/greeter_client/main.go b/go/greeter_client/main.go new file mode 100644 index 00000000000..abe33c0e2ad --- /dev/null +++ b/go/greeter_client/main.go @@ -0,0 +1,70 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package main + +import ( + "log" + "os" + + pb "github.com/grpc-common/go/helloworld" + "golang.org/x/net/context" + "google.golang.org/grpc" +) + +const ( + address = "localhost:50051" + defaultName = "world" +) + +func main() { + // Set up a connection to the server. + var opts []grpc.DialOption + conn, err := grpc.Dial(address, opts...) + if err != nil { + log.Fatalf("did not connect: %v", err) + } + defer conn.Close() + + // Contact the server and print out its response. + name := defaultName + if len(os.Args) > 1 { + name = os.Args[1] + } + c := pb.NewGreeterClient(conn) + r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) + if err != nil { + log.Fatalf("could not greet: %v", err) + } + log.Printf("Greeting: %s", r.Message) +} diff --git a/go/greeter_server/main.go b/go/greeter_server/main.go new file mode 100644 index 00000000000..643524bde76 --- /dev/null +++ b/go/greeter_server/main.go @@ -0,0 +1,65 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package main + +import ( + "log" + "net" + + pb "github.com/grpc-common/go/helloworld" + "golang.org/x/net/context" + "google.golang.org/grpc" +) + +const ( + port = ":50051" +) + +// server is used to implement hellowrld.GreeterServer. +type server struct{} + +// SayHello implements helloworld.GreeterServer +func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { + return &pb.HelloReply{Message: "Hello " + in.Name}, nil +} + +func main() { + l, err := net.Listen("tcp", port) + if err != nil { + log.Fatalf("failed to listen: %v", err) + } + s := grpc.NewServer() + pb.RegisterGreeterServer(s, &server{}) + s.Serve(l) +} diff --git a/go/helloworld/helloworld.pb.go b/go/helloworld/helloworld.pb.go new file mode 100644 index 00000000000..399adda5eaf --- /dev/null +++ b/go/helloworld/helloworld.pb.go @@ -0,0 +1,109 @@ +// Code generated by protoc-gen-go. +// source: helloworld.proto +// DO NOT EDIT! + +/* +Package helloworld is a generated protocol buffer package. + +It is generated from these files: + helloworld.proto + +It has these top-level messages: + HelloRequest + HelloReply +*/ +package helloworld + +import proto "github.com/golang/protobuf/proto" + +import ( + context "golang.org/x/net/context" + grpc "google.golang.org/grpc" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal + +// The request message containing the user's name. +type HelloRequest struct { + Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` +} + +func (m *HelloRequest) Reset() { *m = HelloRequest{} } +func (m *HelloRequest) String() string { return proto.CompactTextString(m) } +func (*HelloRequest) ProtoMessage() {} + +// The response message containing the greetings +type HelloReply struct { + Message string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"` +} + +func (m *HelloReply) Reset() { *m = HelloReply{} } +func (m *HelloReply) String() string { return proto.CompactTextString(m) } +func (*HelloReply) ProtoMessage() {} + +func init() { +} + +// Client API for Greeter service + +type GreeterClient interface { + // Sends a greeting + SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) +} + +type greeterClient struct { + cc *grpc.ClientConn +} + +func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { + return &greeterClient{cc} +} + +func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { + out := new(HelloReply) + err := grpc.Invoke(ctx, "/helloworld.Greeter/sayHello", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// Server API for Greeter service + +type GreeterServer interface { + // Sends a greeting + SayHello(context.Context, *HelloRequest) (*HelloReply, error) +} + +func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { + s.RegisterService(&_Greeter_serviceDesc, srv) +} + +func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, buf []byte) (proto.Message, error) { + in := new(HelloRequest) + if err := proto.Unmarshal(buf, in); err != nil { + return nil, err + } + out, err := srv.(GreeterServer).SayHello(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +var _Greeter_serviceDesc = grpc.ServiceDesc{ + ServiceName: "helloworld.Greeter", + HandlerType: (*GreeterServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "sayHello", + Handler: _Greeter_SayHello_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, +} From ea8eb3c7030da5a4396eba646b5f5e6291413030 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 20 Feb 2015 07:48:04 -0800 Subject: [PATCH 075/576] Pushes the optional code-gen section to the bottom --- go/README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/go/README.md b/go/README.md index df81915c9b7..2bcb5ab0a91 100644 --- a/go/README.md +++ b/go/README.md @@ -21,8 +21,21 @@ $ go install -u github.com/grpc-common/go/greeter_client $ go install -u github.com/grpc-common/go/greeter_server ``` -OPTIONAL - Rebuild the generated code -------------------------------------- +TRY IT! +------- + +- Run the server +```sh +$ greeter_server & +``` + +- Run the client +```sh +$ greeter_client +``` + +OPTIONAL - Rebuilding the generated code +---------------------------------------- 1 First [install protoc](https://github.com/google/protobuf/blob/master/INSTALL.txt) - For now, this needs to be installed from source @@ -36,16 +49,3 @@ $ $ # from ths dir; invoke protoc $ protoc -I ../protos ../protos/helloworld.proto --go_out=plugins=grpc:. ``` - -TRY IT! -------- - -- Run the server -```sh -$ greeter_server & -``` - -- Run the client -```sh -$ greeter_client -``` From 4ee7225fbf09b1944dd2a4a31f35dae6f3929047 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 20 Feb 2015 08:14:34 -0800 Subject: [PATCH 076/576] Changed the documentation title --- go/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go/README.md b/go/README.md index 2bcb5ab0a91..d464b45d364 100644 --- a/go/README.md +++ b/go/README.md @@ -1,5 +1,5 @@ -gRPC Go Hello World -=================== +gRPC in 3 minutes (Go) +====================== PREREQUISITES ------------- From 7c7e9c339603652621184131daad9a50ca1d78a7 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Fri, 20 Feb 2015 10:34:02 -0800 Subject: [PATCH 077/576] Fork code from helloworld and generate code --- cpp/route_guide/Makefile | 47 + cpp/route_guide/route_guide.pb.cc | 1736 +++++++++++++++++++++++++ cpp/route_guide/route_guide.pb.h | 929 +++++++++++++ cpp/route_guide/route_guide_client.cc | 91 ++ cpp/route_guide/route_guide_server.cc | 84 ++ 5 files changed, 2887 insertions(+) create mode 100644 cpp/route_guide/Makefile create mode 100644 cpp/route_guide/route_guide.pb.cc create mode 100644 cpp/route_guide/route_guide.pb.h create mode 100644 cpp/route_guide/route_guide_client.cc create mode 100644 cpp/route_guide/route_guide_server.cc diff --git a/cpp/route_guide/Makefile b/cpp/route_guide/Makefile new file mode 100644 index 00000000000..b9579e0c96d --- /dev/null +++ b/cpp/route_guide/Makefile @@ -0,0 +1,47 @@ +# +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +CXX=g++ +CPPFLAGS=-I/usr/local/include -pthread +CXXFLAGS=-std=c++11 +LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl + +all: greeter_client greeter_server + +greeter_client: helloworld.pb.o greeter_client.o + $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ + +greeter_server: helloworld.pb.o greeter_server.o + $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ + +clean: + rm -f *.o greeter_client greeter_server + diff --git a/cpp/route_guide/route_guide.pb.cc b/cpp/route_guide/route_guide.pb.cc new file mode 100644 index 00000000000..6f4a1e70665 --- /dev/null +++ b/cpp/route_guide/route_guide.pb.cc @@ -0,0 +1,1736 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: route_guide.proto + +#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION +#include "route_guide.pb.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// @@protoc_insertion_point(includes) + +namespace examples { + +namespace { + +const ::google::protobuf::Descriptor* Point_descriptor_ = NULL; +const ::google::protobuf::internal::GeneratedMessageReflection* + Point_reflection_ = NULL; +const ::google::protobuf::Descriptor* Rectangle_descriptor_ = NULL; +const ::google::protobuf::internal::GeneratedMessageReflection* + Rectangle_reflection_ = NULL; +const ::google::protobuf::Descriptor* Feature_descriptor_ = NULL; +const ::google::protobuf::internal::GeneratedMessageReflection* + Feature_reflection_ = NULL; +const ::google::protobuf::Descriptor* RouteNote_descriptor_ = NULL; +const ::google::protobuf::internal::GeneratedMessageReflection* + RouteNote_reflection_ = NULL; +const ::google::protobuf::Descriptor* RouteSummary_descriptor_ = NULL; +const ::google::protobuf::internal::GeneratedMessageReflection* + RouteSummary_reflection_ = NULL; + +} // namespace + + +void protobuf_AssignDesc_route_5fguide_2eproto() { + protobuf_AddDesc_route_5fguide_2eproto(); + const ::google::protobuf::FileDescriptor* file = + ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( + "route_guide.proto"); + GOOGLE_CHECK(file != NULL); + Point_descriptor_ = file->message_type(0); + static const int Point_offsets_[2] = { + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, latitude_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, longitude_), + }; + Point_reflection_ = + ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( + Point_descriptor_, + Point::default_instance_, + Point_offsets_, + -1, + -1, + -1, + sizeof(Point), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _internal_metadata_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _is_default_instance_)); + Rectangle_descriptor_ = file->message_type(1); + static const int Rectangle_offsets_[2] = { + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, lo_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, hi_), + }; + Rectangle_reflection_ = + ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( + Rectangle_descriptor_, + Rectangle::default_instance_, + Rectangle_offsets_, + -1, + -1, + -1, + sizeof(Rectangle), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, _internal_metadata_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, _is_default_instance_)); + Feature_descriptor_ = file->message_type(2); + static const int Feature_offsets_[2] = { + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, name_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, location_), + }; + Feature_reflection_ = + ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( + Feature_descriptor_, + Feature::default_instance_, + Feature_offsets_, + -1, + -1, + -1, + sizeof(Feature), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, _internal_metadata_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, _is_default_instance_)); + RouteNote_descriptor_ = file->message_type(3); + static const int RouteNote_offsets_[2] = { + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, location_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, message_), + }; + RouteNote_reflection_ = + ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( + RouteNote_descriptor_, + RouteNote::default_instance_, + RouteNote_offsets_, + -1, + -1, + -1, + sizeof(RouteNote), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, _internal_metadata_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, _is_default_instance_)); + RouteSummary_descriptor_ = file->message_type(4); + static const int RouteSummary_offsets_[4] = { + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, point_count_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, feature_count_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, distance_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, elapsed_time_), + }; + RouteSummary_reflection_ = + ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( + RouteSummary_descriptor_, + RouteSummary::default_instance_, + RouteSummary_offsets_, + -1, + -1, + -1, + sizeof(RouteSummary), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, _internal_metadata_), + GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, _is_default_instance_)); +} + +namespace { + +GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); +inline void protobuf_AssignDescriptorsOnce() { + ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, + &protobuf_AssignDesc_route_5fguide_2eproto); +} + +void protobuf_RegisterTypes(const ::std::string&) { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( + Point_descriptor_, &Point::default_instance()); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( + Rectangle_descriptor_, &Rectangle::default_instance()); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( + Feature_descriptor_, &Feature::default_instance()); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( + RouteNote_descriptor_, &RouteNote::default_instance()); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( + RouteSummary_descriptor_, &RouteSummary::default_instance()); +} + +} // namespace + +void protobuf_ShutdownFile_route_5fguide_2eproto() { + delete Point::default_instance_; + delete Point_reflection_; + delete Rectangle::default_instance_; + delete Rectangle_reflection_; + delete Feature::default_instance_; + delete Feature_reflection_; + delete RouteNote::default_instance_; + delete RouteNote_reflection_; + delete RouteSummary::default_instance_; + delete RouteSummary_reflection_; +} + +void protobuf_AddDesc_route_5fguide_2eproto() { + static bool already_here = false; + if (already_here) return; + already_here = true; + GOOGLE_PROTOBUF_VERIFY_VERSION; + + ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( + "\n\021route_guide.proto\022\010examples\",\n\005Point\022\020" + "\n\010latitude\030\001 \001(\005\022\021\n\tlongitude\030\002 \001(\005\"E\n\tR" + "ectangle\022\033\n\002lo\030\001 \001(\0132\017.examples.Point\022\033\n" + "\002hi\030\002 \001(\0132\017.examples.Point\":\n\007Feature\022\014\n" + "\004name\030\001 \001(\t\022!\n\010location\030\002 \001(\0132\017.examples" + ".Point\"\?\n\tRouteNote\022!\n\010location\030\001 \001(\0132\017." + "examples.Point\022\017\n\007message\030\002 \001(\t\"b\n\014Route" + "Summary\022\023\n\013point_count\030\001 \001(\005\022\025\n\rfeature_" + "count\030\002 \001(\005\022\020\n\010distance\030\003 \001(\005\022\024\n\014elapsed" + "_time\030\004 \001(\0052\365\001\n\nRouteGuide\0222\n\nGetFeature" + "\022\017.examples.Point\032\021.examples.Feature\"\000\022:" + "\n\014ListFeatures\022\023.examples.Rectangle\032\021.ex" + "amples.Feature\"\0000\001\022:\n\013RecordRoute\022\017.exam" + "ples.Point\032\026.examples.RouteSummary\"\000(\001\022;" + "\n\tRouteChat\022\023.examples.RouteNote\032\023.examp" + "les.RouteNote\"\000(\0010\001B\t\n\007ex.grpcb\006proto3", 638); + ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( + "route_guide.proto", &protobuf_RegisterTypes); + Point::default_instance_ = new Point(); + Rectangle::default_instance_ = new Rectangle(); + Feature::default_instance_ = new Feature(); + RouteNote::default_instance_ = new RouteNote(); + RouteSummary::default_instance_ = new RouteSummary(); + Point::default_instance_->InitAsDefaultInstance(); + Rectangle::default_instance_->InitAsDefaultInstance(); + Feature::default_instance_->InitAsDefaultInstance(); + RouteNote::default_instance_->InitAsDefaultInstance(); + RouteSummary::default_instance_->InitAsDefaultInstance(); + ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_route_5fguide_2eproto); +} + +// Force AddDescriptors() to be called at static initialization time. +struct StaticDescriptorInitializer_route_5fguide_2eproto { + StaticDescriptorInitializer_route_5fguide_2eproto() { + protobuf_AddDesc_route_5fguide_2eproto(); + } +} static_descriptor_initializer_route_5fguide_2eproto_; + +namespace { + +static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD; +static void MergeFromFail(int line) { + GOOGLE_CHECK(false) << __FILE__ << ":" << line; +} + +} // namespace + + +// =================================================================== + +#ifndef _MSC_VER +const int Point::kLatitudeFieldNumber; +const int Point::kLongitudeFieldNumber; +#endif // !_MSC_VER + +Point::Point() + : ::google::protobuf::Message() , _internal_metadata_(NULL) { + SharedCtor(); + // @@protoc_insertion_point(constructor:examples.Point) +} + +void Point::InitAsDefaultInstance() { + _is_default_instance_ = true; +} + +Point::Point(const Point& from) + : ::google::protobuf::Message(), + _internal_metadata_(NULL) { + SharedCtor(); + MergeFrom(from); + // @@protoc_insertion_point(copy_constructor:examples.Point) +} + +void Point::SharedCtor() { + _is_default_instance_ = false; + _cached_size_ = 0; + latitude_ = 0; + longitude_ = 0; +} + +Point::~Point() { + // @@protoc_insertion_point(destructor:examples.Point) + SharedDtor(); +} + +void Point::SharedDtor() { + if (this != default_instance_) { + } +} + +void Point::SetCachedSize(int size) const { + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); +} +const ::google::protobuf::Descriptor* Point::descriptor() { + protobuf_AssignDescriptorsOnce(); + return Point_descriptor_; +} + +const Point& Point::default_instance() { + if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); + return *default_instance_; +} + +Point* Point::default_instance_ = NULL; + +Point* Point::New(::google::protobuf::Arena* arena) const { + Point* n = new Point; + if (arena != NULL) { + arena->Own(n); + } + return n; +} + +void Point::Clear() { +#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ + &reinterpret_cast(16)->f) - \ + reinterpret_cast(16)) + +#define ZR_(first, last) do { \ + size_t f = OFFSET_OF_FIELD_(first); \ + size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ + ::memset(&first, 0, n); \ + } while (0) + + ZR_(latitude_, longitude_); + +#undef OFFSET_OF_FIELD_ +#undef ZR_ + +} + +bool Point::MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure + ::google::protobuf::uint32 tag; + // @@protoc_insertion_point(parse_start:examples.Point) + for (;;) { + ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); + tag = p.first; + if (!p.second) goto handle_unusual; + switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + // optional int32 latitude = 1; + case 1: { + if (tag == 8) { + DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< + ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + input, &latitude_))); + + } else { + goto handle_unusual; + } + if (input->ExpectTag(16)) goto parse_longitude; + break; + } + + // optional int32 longitude = 2; + case 2: { + if (tag == 16) { + parse_longitude: + DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< + ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + input, &longitude_))); + + } else { + goto handle_unusual; + } + if (input->ExpectAtEnd()) goto success; + break; + } + + default: { + handle_unusual: + if (tag == 0 || + ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == + ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { + goto success; + } + DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); + break; + } + } + } +success: + // @@protoc_insertion_point(parse_success:examples.Point) + return true; +failure: + // @@protoc_insertion_point(parse_failure:examples.Point) + return false; +#undef DO_ +} + +void Point::SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const { + // @@protoc_insertion_point(serialize_start:examples.Point) + // optional int32 latitude = 1; + if (this->latitude() != 0) { + ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->latitude(), output); + } + + // optional int32 longitude = 2; + if (this->longitude() != 0) { + ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->longitude(), output); + } + + // @@protoc_insertion_point(serialize_end:examples.Point) +} + +::google::protobuf::uint8* Point::SerializeWithCachedSizesToArray( + ::google::protobuf::uint8* target) const { + // @@protoc_insertion_point(serialize_to_array_start:examples.Point) + // optional int32 latitude = 1; + if (this->latitude() != 0) { + target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->latitude(), target); + } + + // optional int32 longitude = 2; + if (this->longitude() != 0) { + target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->longitude(), target); + } + + // @@protoc_insertion_point(serialize_to_array_end:examples.Point) + return target; +} + +int Point::ByteSize() const { + int total_size = 0; + + // optional int32 latitude = 1; + if (this->latitude() != 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::Int32Size( + this->latitude()); + } + + // optional int32 longitude = 2; + if (this->longitude() != 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::Int32Size( + this->longitude()); + } + + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = total_size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); + return total_size; +} + +void Point::MergeFrom(const ::google::protobuf::Message& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + const Point* source = + ::google::protobuf::internal::dynamic_cast_if_available( + &from); + if (source == NULL) { + ::google::protobuf::internal::ReflectionOps::Merge(from, this); + } else { + MergeFrom(*source); + } +} + +void Point::MergeFrom(const Point& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + if (from.latitude() != 0) { + set_latitude(from.latitude()); + } + if (from.longitude() != 0) { + set_longitude(from.longitude()); + } +} + +void Point::CopyFrom(const ::google::protobuf::Message& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +void Point::CopyFrom(const Point& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool Point::IsInitialized() const { + + return true; +} + +void Point::Swap(Point* other) { + if (other == this) return; + InternalSwap(other); +} +void Point::InternalSwap(Point* other) { + std::swap(latitude_, other->latitude_); + std::swap(longitude_, other->longitude_); + _internal_metadata_.Swap(&other->_internal_metadata_); + std::swap(_cached_size_, other->_cached_size_); +} + +::google::protobuf::Metadata Point::GetMetadata() const { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::Metadata metadata; + metadata.descriptor = Point_descriptor_; + metadata.reflection = Point_reflection_; + return metadata; +} + + +// =================================================================== + +#ifndef _MSC_VER +const int Rectangle::kLoFieldNumber; +const int Rectangle::kHiFieldNumber; +#endif // !_MSC_VER + +Rectangle::Rectangle() + : ::google::protobuf::Message() , _internal_metadata_(NULL) { + SharedCtor(); + // @@protoc_insertion_point(constructor:examples.Rectangle) +} + +void Rectangle::InitAsDefaultInstance() { + _is_default_instance_ = true; + lo_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); + hi_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); +} + +Rectangle::Rectangle(const Rectangle& from) + : ::google::protobuf::Message(), + _internal_metadata_(NULL) { + SharedCtor(); + MergeFrom(from); + // @@protoc_insertion_point(copy_constructor:examples.Rectangle) +} + +void Rectangle::SharedCtor() { + _is_default_instance_ = false; + _cached_size_ = 0; + lo_ = NULL; + hi_ = NULL; +} + +Rectangle::~Rectangle() { + // @@protoc_insertion_point(destructor:examples.Rectangle) + SharedDtor(); +} + +void Rectangle::SharedDtor() { + if (this != default_instance_) { + delete lo_; + delete hi_; + } +} + +void Rectangle::SetCachedSize(int size) const { + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); +} +const ::google::protobuf::Descriptor* Rectangle::descriptor() { + protobuf_AssignDescriptorsOnce(); + return Rectangle_descriptor_; +} + +const Rectangle& Rectangle::default_instance() { + if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); + return *default_instance_; +} + +Rectangle* Rectangle::default_instance_ = NULL; + +Rectangle* Rectangle::New(::google::protobuf::Arena* arena) const { + Rectangle* n = new Rectangle; + if (arena != NULL) { + arena->Own(n); + } + return n; +} + +void Rectangle::Clear() { + if (lo_ != NULL) delete lo_; + lo_ = NULL; + if (hi_ != NULL) delete hi_; + hi_ = NULL; +} + +bool Rectangle::MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure + ::google::protobuf::uint32 tag; + // @@protoc_insertion_point(parse_start:examples.Rectangle) + for (;;) { + ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); + tag = p.first; + if (!p.second) goto handle_unusual; + switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + // optional .examples.Point lo = 1; + case 1: { + if (tag == 10) { + DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( + input, mutable_lo())); + } else { + goto handle_unusual; + } + if (input->ExpectTag(18)) goto parse_hi; + break; + } + + // optional .examples.Point hi = 2; + case 2: { + if (tag == 18) { + parse_hi: + DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( + input, mutable_hi())); + } else { + goto handle_unusual; + } + if (input->ExpectAtEnd()) goto success; + break; + } + + default: { + handle_unusual: + if (tag == 0 || + ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == + ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { + goto success; + } + DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); + break; + } + } + } +success: + // @@protoc_insertion_point(parse_success:examples.Rectangle) + return true; +failure: + // @@protoc_insertion_point(parse_failure:examples.Rectangle) + return false; +#undef DO_ +} + +void Rectangle::SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const { + // @@protoc_insertion_point(serialize_start:examples.Rectangle) + // optional .examples.Point lo = 1; + if (this->has_lo()) { + ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + 1, *this->lo_, output); + } + + // optional .examples.Point hi = 2; + if (this->has_hi()) { + ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + 2, *this->hi_, output); + } + + // @@protoc_insertion_point(serialize_end:examples.Rectangle) +} + +::google::protobuf::uint8* Rectangle::SerializeWithCachedSizesToArray( + ::google::protobuf::uint8* target) const { + // @@protoc_insertion_point(serialize_to_array_start:examples.Rectangle) + // optional .examples.Point lo = 1; + if (this->has_lo()) { + target = ::google::protobuf::internal::WireFormatLite:: + WriteMessageNoVirtualToArray( + 1, *this->lo_, target); + } + + // optional .examples.Point hi = 2; + if (this->has_hi()) { + target = ::google::protobuf::internal::WireFormatLite:: + WriteMessageNoVirtualToArray( + 2, *this->hi_, target); + } + + // @@protoc_insertion_point(serialize_to_array_end:examples.Rectangle) + return target; +} + +int Rectangle::ByteSize() const { + int total_size = 0; + + // optional .examples.Point lo = 1; + if (this->has_lo()) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( + *this->lo_); + } + + // optional .examples.Point hi = 2; + if (this->has_hi()) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( + *this->hi_); + } + + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = total_size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); + return total_size; +} + +void Rectangle::MergeFrom(const ::google::protobuf::Message& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + const Rectangle* source = + ::google::protobuf::internal::dynamic_cast_if_available( + &from); + if (source == NULL) { + ::google::protobuf::internal::ReflectionOps::Merge(from, this); + } else { + MergeFrom(*source); + } +} + +void Rectangle::MergeFrom(const Rectangle& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + if (from.has_lo()) { + mutable_lo()->::examples::Point::MergeFrom(from.lo()); + } + if (from.has_hi()) { + mutable_hi()->::examples::Point::MergeFrom(from.hi()); + } +} + +void Rectangle::CopyFrom(const ::google::protobuf::Message& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +void Rectangle::CopyFrom(const Rectangle& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool Rectangle::IsInitialized() const { + + return true; +} + +void Rectangle::Swap(Rectangle* other) { + if (other == this) return; + InternalSwap(other); +} +void Rectangle::InternalSwap(Rectangle* other) { + std::swap(lo_, other->lo_); + std::swap(hi_, other->hi_); + _internal_metadata_.Swap(&other->_internal_metadata_); + std::swap(_cached_size_, other->_cached_size_); +} + +::google::protobuf::Metadata Rectangle::GetMetadata() const { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::Metadata metadata; + metadata.descriptor = Rectangle_descriptor_; + metadata.reflection = Rectangle_reflection_; + return metadata; +} + + +// =================================================================== + +#ifndef _MSC_VER +const int Feature::kNameFieldNumber; +const int Feature::kLocationFieldNumber; +#endif // !_MSC_VER + +Feature::Feature() + : ::google::protobuf::Message() , _internal_metadata_(NULL) { + SharedCtor(); + // @@protoc_insertion_point(constructor:examples.Feature) +} + +void Feature::InitAsDefaultInstance() { + _is_default_instance_ = true; + location_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); +} + +Feature::Feature(const Feature& from) + : ::google::protobuf::Message(), + _internal_metadata_(NULL) { + SharedCtor(); + MergeFrom(from); + // @@protoc_insertion_point(copy_constructor:examples.Feature) +} + +void Feature::SharedCtor() { + _is_default_instance_ = false; + ::google::protobuf::internal::GetEmptyString(); + _cached_size_ = 0; + name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + location_ = NULL; +} + +Feature::~Feature() { + // @@protoc_insertion_point(destructor:examples.Feature) + SharedDtor(); +} + +void Feature::SharedDtor() { + name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + if (this != default_instance_) { + delete location_; + } +} + +void Feature::SetCachedSize(int size) const { + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); +} +const ::google::protobuf::Descriptor* Feature::descriptor() { + protobuf_AssignDescriptorsOnce(); + return Feature_descriptor_; +} + +const Feature& Feature::default_instance() { + if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); + return *default_instance_; +} + +Feature* Feature::default_instance_ = NULL; + +Feature* Feature::New(::google::protobuf::Arena* arena) const { + Feature* n = new Feature; + if (arena != NULL) { + arena->Own(n); + } + return n; +} + +void Feature::Clear() { + name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + if (location_ != NULL) delete location_; + location_ = NULL; +} + +bool Feature::MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure + ::google::protobuf::uint32 tag; + // @@protoc_insertion_point(parse_start:examples.Feature) + for (;;) { + ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); + tag = p.first; + if (!p.second) goto handle_unusual; + switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + // optional string name = 1; + case 1: { + if (tag == 10) { + DO_(::google::protobuf::internal::WireFormatLite::ReadString( + input, this->mutable_name())); + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->name().data(), this->name().length(), + ::google::protobuf::internal::WireFormat::PARSE, + "examples.Feature.name"); + } else { + goto handle_unusual; + } + if (input->ExpectTag(18)) goto parse_location; + break; + } + + // optional .examples.Point location = 2; + case 2: { + if (tag == 18) { + parse_location: + DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( + input, mutable_location())); + } else { + goto handle_unusual; + } + if (input->ExpectAtEnd()) goto success; + break; + } + + default: { + handle_unusual: + if (tag == 0 || + ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == + ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { + goto success; + } + DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); + break; + } + } + } +success: + // @@protoc_insertion_point(parse_success:examples.Feature) + return true; +failure: + // @@protoc_insertion_point(parse_failure:examples.Feature) + return false; +#undef DO_ +} + +void Feature::SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const { + // @@protoc_insertion_point(serialize_start:examples.Feature) + // optional string name = 1; + if (this->name().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->name().data(), this->name().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "examples.Feature.name"); + ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + 1, this->name(), output); + } + + // optional .examples.Point location = 2; + if (this->has_location()) { + ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + 2, *this->location_, output); + } + + // @@protoc_insertion_point(serialize_end:examples.Feature) +} + +::google::protobuf::uint8* Feature::SerializeWithCachedSizesToArray( + ::google::protobuf::uint8* target) const { + // @@protoc_insertion_point(serialize_to_array_start:examples.Feature) + // optional string name = 1; + if (this->name().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->name().data(), this->name().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "examples.Feature.name"); + target = + ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + 1, this->name(), target); + } + + // optional .examples.Point location = 2; + if (this->has_location()) { + target = ::google::protobuf::internal::WireFormatLite:: + WriteMessageNoVirtualToArray( + 2, *this->location_, target); + } + + // @@protoc_insertion_point(serialize_to_array_end:examples.Feature) + return target; +} + +int Feature::ByteSize() const { + int total_size = 0; + + // optional string name = 1; + if (this->name().size() > 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::StringSize( + this->name()); + } + + // optional .examples.Point location = 2; + if (this->has_location()) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( + *this->location_); + } + + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = total_size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); + return total_size; +} + +void Feature::MergeFrom(const ::google::protobuf::Message& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + const Feature* source = + ::google::protobuf::internal::dynamic_cast_if_available( + &from); + if (source == NULL) { + ::google::protobuf::internal::ReflectionOps::Merge(from, this); + } else { + MergeFrom(*source); + } +} + +void Feature::MergeFrom(const Feature& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + if (from.name().size() > 0) { + + name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); + } + if (from.has_location()) { + mutable_location()->::examples::Point::MergeFrom(from.location()); + } +} + +void Feature::CopyFrom(const ::google::protobuf::Message& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +void Feature::CopyFrom(const Feature& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool Feature::IsInitialized() const { + + return true; +} + +void Feature::Swap(Feature* other) { + if (other == this) return; + InternalSwap(other); +} +void Feature::InternalSwap(Feature* other) { + name_.Swap(&other->name_); + std::swap(location_, other->location_); + _internal_metadata_.Swap(&other->_internal_metadata_); + std::swap(_cached_size_, other->_cached_size_); +} + +::google::protobuf::Metadata Feature::GetMetadata() const { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::Metadata metadata; + metadata.descriptor = Feature_descriptor_; + metadata.reflection = Feature_reflection_; + return metadata; +} + + +// =================================================================== + +#ifndef _MSC_VER +const int RouteNote::kLocationFieldNumber; +const int RouteNote::kMessageFieldNumber; +#endif // !_MSC_VER + +RouteNote::RouteNote() + : ::google::protobuf::Message() , _internal_metadata_(NULL) { + SharedCtor(); + // @@protoc_insertion_point(constructor:examples.RouteNote) +} + +void RouteNote::InitAsDefaultInstance() { + _is_default_instance_ = true; + location_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); +} + +RouteNote::RouteNote(const RouteNote& from) + : ::google::protobuf::Message(), + _internal_metadata_(NULL) { + SharedCtor(); + MergeFrom(from); + // @@protoc_insertion_point(copy_constructor:examples.RouteNote) +} + +void RouteNote::SharedCtor() { + _is_default_instance_ = false; + ::google::protobuf::internal::GetEmptyString(); + _cached_size_ = 0; + location_ = NULL; + message_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} + +RouteNote::~RouteNote() { + // @@protoc_insertion_point(destructor:examples.RouteNote) + SharedDtor(); +} + +void RouteNote::SharedDtor() { + message_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + if (this != default_instance_) { + delete location_; + } +} + +void RouteNote::SetCachedSize(int size) const { + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); +} +const ::google::protobuf::Descriptor* RouteNote::descriptor() { + protobuf_AssignDescriptorsOnce(); + return RouteNote_descriptor_; +} + +const RouteNote& RouteNote::default_instance() { + if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); + return *default_instance_; +} + +RouteNote* RouteNote::default_instance_ = NULL; + +RouteNote* RouteNote::New(::google::protobuf::Arena* arena) const { + RouteNote* n = new RouteNote; + if (arena != NULL) { + arena->Own(n); + } + return n; +} + +void RouteNote::Clear() { + if (location_ != NULL) delete location_; + location_ = NULL; + message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} + +bool RouteNote::MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure + ::google::protobuf::uint32 tag; + // @@protoc_insertion_point(parse_start:examples.RouteNote) + for (;;) { + ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); + tag = p.first; + if (!p.second) goto handle_unusual; + switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + // optional .examples.Point location = 1; + case 1: { + if (tag == 10) { + DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( + input, mutable_location())); + } else { + goto handle_unusual; + } + if (input->ExpectTag(18)) goto parse_message; + break; + } + + // optional string message = 2; + case 2: { + if (tag == 18) { + parse_message: + DO_(::google::protobuf::internal::WireFormatLite::ReadString( + input, this->mutable_message())); + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->message().data(), this->message().length(), + ::google::protobuf::internal::WireFormat::PARSE, + "examples.RouteNote.message"); + } else { + goto handle_unusual; + } + if (input->ExpectAtEnd()) goto success; + break; + } + + default: { + handle_unusual: + if (tag == 0 || + ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == + ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { + goto success; + } + DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); + break; + } + } + } +success: + // @@protoc_insertion_point(parse_success:examples.RouteNote) + return true; +failure: + // @@protoc_insertion_point(parse_failure:examples.RouteNote) + return false; +#undef DO_ +} + +void RouteNote::SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const { + // @@protoc_insertion_point(serialize_start:examples.RouteNote) + // optional .examples.Point location = 1; + if (this->has_location()) { + ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( + 1, *this->location_, output); + } + + // optional string message = 2; + if (this->message().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->message().data(), this->message().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "examples.RouteNote.message"); + ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( + 2, this->message(), output); + } + + // @@protoc_insertion_point(serialize_end:examples.RouteNote) +} + +::google::protobuf::uint8* RouteNote::SerializeWithCachedSizesToArray( + ::google::protobuf::uint8* target) const { + // @@protoc_insertion_point(serialize_to_array_start:examples.RouteNote) + // optional .examples.Point location = 1; + if (this->has_location()) { + target = ::google::protobuf::internal::WireFormatLite:: + WriteMessageNoVirtualToArray( + 1, *this->location_, target); + } + + // optional string message = 2; + if (this->message().size() > 0) { + ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( + this->message().data(), this->message().length(), + ::google::protobuf::internal::WireFormat::SERIALIZE, + "examples.RouteNote.message"); + target = + ::google::protobuf::internal::WireFormatLite::WriteStringToArray( + 2, this->message(), target); + } + + // @@protoc_insertion_point(serialize_to_array_end:examples.RouteNote) + return target; +} + +int RouteNote::ByteSize() const { + int total_size = 0; + + // optional .examples.Point location = 1; + if (this->has_location()) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( + *this->location_); + } + + // optional string message = 2; + if (this->message().size() > 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::StringSize( + this->message()); + } + + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = total_size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); + return total_size; +} + +void RouteNote::MergeFrom(const ::google::protobuf::Message& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + const RouteNote* source = + ::google::protobuf::internal::dynamic_cast_if_available( + &from); + if (source == NULL) { + ::google::protobuf::internal::ReflectionOps::Merge(from, this); + } else { + MergeFrom(*source); + } +} + +void RouteNote::MergeFrom(const RouteNote& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + if (from.has_location()) { + mutable_location()->::examples::Point::MergeFrom(from.location()); + } + if (from.message().size() > 0) { + + message_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.message_); + } +} + +void RouteNote::CopyFrom(const ::google::protobuf::Message& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +void RouteNote::CopyFrom(const RouteNote& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool RouteNote::IsInitialized() const { + + return true; +} + +void RouteNote::Swap(RouteNote* other) { + if (other == this) return; + InternalSwap(other); +} +void RouteNote::InternalSwap(RouteNote* other) { + std::swap(location_, other->location_); + message_.Swap(&other->message_); + _internal_metadata_.Swap(&other->_internal_metadata_); + std::swap(_cached_size_, other->_cached_size_); +} + +::google::protobuf::Metadata RouteNote::GetMetadata() const { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::Metadata metadata; + metadata.descriptor = RouteNote_descriptor_; + metadata.reflection = RouteNote_reflection_; + return metadata; +} + + +// =================================================================== + +#ifndef _MSC_VER +const int RouteSummary::kPointCountFieldNumber; +const int RouteSummary::kFeatureCountFieldNumber; +const int RouteSummary::kDistanceFieldNumber; +const int RouteSummary::kElapsedTimeFieldNumber; +#endif // !_MSC_VER + +RouteSummary::RouteSummary() + : ::google::protobuf::Message() , _internal_metadata_(NULL) { + SharedCtor(); + // @@protoc_insertion_point(constructor:examples.RouteSummary) +} + +void RouteSummary::InitAsDefaultInstance() { + _is_default_instance_ = true; +} + +RouteSummary::RouteSummary(const RouteSummary& from) + : ::google::protobuf::Message(), + _internal_metadata_(NULL) { + SharedCtor(); + MergeFrom(from); + // @@protoc_insertion_point(copy_constructor:examples.RouteSummary) +} + +void RouteSummary::SharedCtor() { + _is_default_instance_ = false; + _cached_size_ = 0; + point_count_ = 0; + feature_count_ = 0; + distance_ = 0; + elapsed_time_ = 0; +} + +RouteSummary::~RouteSummary() { + // @@protoc_insertion_point(destructor:examples.RouteSummary) + SharedDtor(); +} + +void RouteSummary::SharedDtor() { + if (this != default_instance_) { + } +} + +void RouteSummary::SetCachedSize(int size) const { + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); +} +const ::google::protobuf::Descriptor* RouteSummary::descriptor() { + protobuf_AssignDescriptorsOnce(); + return RouteSummary_descriptor_; +} + +const RouteSummary& RouteSummary::default_instance() { + if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); + return *default_instance_; +} + +RouteSummary* RouteSummary::default_instance_ = NULL; + +RouteSummary* RouteSummary::New(::google::protobuf::Arena* arena) const { + RouteSummary* n = new RouteSummary; + if (arena != NULL) { + arena->Own(n); + } + return n; +} + +void RouteSummary::Clear() { +#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ + &reinterpret_cast(16)->f) - \ + reinterpret_cast(16)) + +#define ZR_(first, last) do { \ + size_t f = OFFSET_OF_FIELD_(first); \ + size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ + ::memset(&first, 0, n); \ + } while (0) + + ZR_(point_count_, elapsed_time_); + +#undef OFFSET_OF_FIELD_ +#undef ZR_ + +} + +bool RouteSummary::MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input) { +#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure + ::google::protobuf::uint32 tag; + // @@protoc_insertion_point(parse_start:examples.RouteSummary) + for (;;) { + ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); + tag = p.first; + if (!p.second) goto handle_unusual; + switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { + // optional int32 point_count = 1; + case 1: { + if (tag == 8) { + DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< + ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + input, &point_count_))); + + } else { + goto handle_unusual; + } + if (input->ExpectTag(16)) goto parse_feature_count; + break; + } + + // optional int32 feature_count = 2; + case 2: { + if (tag == 16) { + parse_feature_count: + DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< + ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + input, &feature_count_))); + + } else { + goto handle_unusual; + } + if (input->ExpectTag(24)) goto parse_distance; + break; + } + + // optional int32 distance = 3; + case 3: { + if (tag == 24) { + parse_distance: + DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< + ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + input, &distance_))); + + } else { + goto handle_unusual; + } + if (input->ExpectTag(32)) goto parse_elapsed_time; + break; + } + + // optional int32 elapsed_time = 4; + case 4: { + if (tag == 32) { + parse_elapsed_time: + DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< + ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( + input, &elapsed_time_))); + + } else { + goto handle_unusual; + } + if (input->ExpectAtEnd()) goto success; + break; + } + + default: { + handle_unusual: + if (tag == 0 || + ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == + ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { + goto success; + } + DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); + break; + } + } + } +success: + // @@protoc_insertion_point(parse_success:examples.RouteSummary) + return true; +failure: + // @@protoc_insertion_point(parse_failure:examples.RouteSummary) + return false; +#undef DO_ +} + +void RouteSummary::SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const { + // @@protoc_insertion_point(serialize_start:examples.RouteSummary) + // optional int32 point_count = 1; + if (this->point_count() != 0) { + ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->point_count(), output); + } + + // optional int32 feature_count = 2; + if (this->feature_count() != 0) { + ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->feature_count(), output); + } + + // optional int32 distance = 3; + if (this->distance() != 0) { + ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->distance(), output); + } + + // optional int32 elapsed_time = 4; + if (this->elapsed_time() != 0) { + ::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->elapsed_time(), output); + } + + // @@protoc_insertion_point(serialize_end:examples.RouteSummary) +} + +::google::protobuf::uint8* RouteSummary::SerializeWithCachedSizesToArray( + ::google::protobuf::uint8* target) const { + // @@protoc_insertion_point(serialize_to_array_start:examples.RouteSummary) + // optional int32 point_count = 1; + if (this->point_count() != 0) { + target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->point_count(), target); + } + + // optional int32 feature_count = 2; + if (this->feature_count() != 0) { + target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->feature_count(), target); + } + + // optional int32 distance = 3; + if (this->distance() != 0) { + target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->distance(), target); + } + + // optional int32 elapsed_time = 4; + if (this->elapsed_time() != 0) { + target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->elapsed_time(), target); + } + + // @@protoc_insertion_point(serialize_to_array_end:examples.RouteSummary) + return target; +} + +int RouteSummary::ByteSize() const { + int total_size = 0; + + // optional int32 point_count = 1; + if (this->point_count() != 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::Int32Size( + this->point_count()); + } + + // optional int32 feature_count = 2; + if (this->feature_count() != 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::Int32Size( + this->feature_count()); + } + + // optional int32 distance = 3; + if (this->distance() != 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::Int32Size( + this->distance()); + } + + // optional int32 elapsed_time = 4; + if (this->elapsed_time() != 0) { + total_size += 1 + + ::google::protobuf::internal::WireFormatLite::Int32Size( + this->elapsed_time()); + } + + GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); + _cached_size_ = total_size; + GOOGLE_SAFE_CONCURRENT_WRITES_END(); + return total_size; +} + +void RouteSummary::MergeFrom(const ::google::protobuf::Message& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + const RouteSummary* source = + ::google::protobuf::internal::dynamic_cast_if_available( + &from); + if (source == NULL) { + ::google::protobuf::internal::ReflectionOps::Merge(from, this); + } else { + MergeFrom(*source); + } +} + +void RouteSummary::MergeFrom(const RouteSummary& from) { + if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); + if (from.point_count() != 0) { + set_point_count(from.point_count()); + } + if (from.feature_count() != 0) { + set_feature_count(from.feature_count()); + } + if (from.distance() != 0) { + set_distance(from.distance()); + } + if (from.elapsed_time() != 0) { + set_elapsed_time(from.elapsed_time()); + } +} + +void RouteSummary::CopyFrom(const ::google::protobuf::Message& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +void RouteSummary::CopyFrom(const RouteSummary& from) { + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool RouteSummary::IsInitialized() const { + + return true; +} + +void RouteSummary::Swap(RouteSummary* other) { + if (other == this) return; + InternalSwap(other); +} +void RouteSummary::InternalSwap(RouteSummary* other) { + std::swap(point_count_, other->point_count_); + std::swap(feature_count_, other->feature_count_); + std::swap(distance_, other->distance_); + std::swap(elapsed_time_, other->elapsed_time_); + _internal_metadata_.Swap(&other->_internal_metadata_); + std::swap(_cached_size_, other->_cached_size_); +} + +::google::protobuf::Metadata RouteSummary::GetMetadata() const { + protobuf_AssignDescriptorsOnce(); + ::google::protobuf::Metadata metadata; + metadata.descriptor = RouteSummary_descriptor_; + metadata.reflection = RouteSummary_reflection_; + return metadata; +} + + +static const char* RouteGuide_method_names[] = { + "/examples.RouteGuide/GetFeature", + "/examples.RouteGuide/ListFeatures", + "/examples.RouteGuide/RecordRoute", + "/examples.RouteGuide/RouteChat", +}; + +RouteGuide::Stub* RouteGuide::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) { + RouteGuide::Stub* stub = new RouteGuide::Stub(); + stub->set_channel(channel); + return stub; +}; + +::grpc::Status RouteGuide::Stub::GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::examples::Feature* response) { + return ::grpc::BlockingUnaryCall(channel(),::grpc::RpcMethod(RouteGuide_method_names[0]), context, request, response); +} + +::grpc::ClientAsyncResponseReader< ::examples::Feature>* RouteGuide::Stub::GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::grpc::CompletionQueue* cq, void* tag) { + return new ::grpc::ClientAsyncResponseReader< ::examples::Feature>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[0]), context, request, tag); +} + +::grpc::ClientReader< ::examples::Feature>* RouteGuide::Stub::ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request) { + return new ::grpc::ClientReader< ::examples::Feature>(channel(),::grpc::RpcMethod(RouteGuide_method_names[1], ::grpc::RpcMethod::RpcType::SERVER_STREAMING), context, request); +} + +::grpc::ClientAsyncReader< ::examples::Feature>* RouteGuide::Stub::ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request, ::grpc::CompletionQueue* cq, void* tag) { + return new ::grpc::ClientAsyncReader< ::examples::Feature>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[1], ::grpc::RpcMethod::RpcType::SERVER_STREAMING), context, request, tag); +} + +::grpc::ClientWriter< ::examples::Point>* RouteGuide::Stub::RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response) { + return new ::grpc::ClientWriter< ::examples::Point>(channel(),::grpc::RpcMethod(RouteGuide_method_names[2], ::grpc::RpcMethod::RpcType::CLIENT_STREAMING), context, response); +} + +::grpc::ClientAsyncWriter< ::examples::Point>* RouteGuide::Stub::RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response, ::grpc::CompletionQueue* cq, void* tag) { + return new ::grpc::ClientAsyncWriter< ::examples::Point>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[2], ::grpc::RpcMethod::RpcType::CLIENT_STREAMING), context, response, tag); +} + +::grpc::ClientReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteGuide::Stub::RouteChat(::grpc::ClientContext* context) { + return new ::grpc::ClientReaderWriter< ::examples::RouteNote, ::examples::RouteNote>(channel(),::grpc::RpcMethod(RouteGuide_method_names[3], ::grpc::RpcMethod::RpcType::BIDI_STREAMING), context); +} + +::grpc::ClientAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteGuide::Stub::RouteChat(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return new ::grpc::ClientAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[3], ::grpc::RpcMethod::RpcType::BIDI_STREAMING), context, tag); +} + +RouteGuide::AsyncService::AsyncService(::grpc::CompletionQueue* cq) : ::grpc::AsynchronousService(cq, RouteGuide_method_names, 4) {} + +RouteGuide::Service::~Service() { + delete service_; +} + +::grpc::Status RouteGuide::Service::GetFeature(::grpc::ServerContext* context, const ::examples::Point* request, ::examples::Feature* response) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); +} + +void RouteGuide::AsyncService::RequestGetFeature(::grpc::ServerContext* context, ::examples::Point* request, ::grpc::ServerAsyncResponseWriter< ::examples::Feature>* response, ::grpc::CompletionQueue* cq, void* tag) { + AsynchronousService::RequestAsyncUnary(0, context, request, response, cq, tag); +} + +::grpc::Status RouteGuide::Service::ListFeatures(::grpc::ServerContext* context, const ::examples::Rectangle* request, ::grpc::ServerWriter< ::examples::Feature>* writer) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); +} + +void RouteGuide::AsyncService::RequestListFeatures(::grpc::ServerContext* context, ::examples::Rectangle* request, ::grpc::ServerAsyncWriter< ::examples::Feature>* writer, ::grpc::CompletionQueue* cq, void* tag) { + AsynchronousService::RequestServerStreaming(1, context, request, writer, cq, tag); +} + +::grpc::Status RouteGuide::Service::RecordRoute(::grpc::ServerContext* context, ::grpc::ServerReader< ::examples::Point>* reader, ::examples::RouteSummary* response) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); +} + +void RouteGuide::AsyncService::RequestRecordRoute(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< ::examples::RouteSummary, ::examples::Point>* reader, ::grpc::CompletionQueue* cq, void* tag) { + AsynchronousService::RequestClientStreaming(2, context, reader, cq, tag); +} + +::grpc::Status RouteGuide::Service::RouteChat(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); +} + +void RouteGuide::AsyncService::RequestRouteChat(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream, ::grpc::CompletionQueue* cq, void *tag) { + AsynchronousService::RequestBidiStreaming(3, context, stream, cq, tag); +} + +::grpc::RpcService* RouteGuide::Service::service() { + if (service_ != nullptr) { + return service_; + } + service_ = new ::grpc::RpcService(); + service_->AddMethod(new ::grpc::RpcServiceMethod( + RouteGuide_method_names[0], + ::grpc::RpcMethod::NORMAL_RPC, + new ::grpc::RpcMethodHandler< RouteGuide::Service, ::examples::Point, ::examples::Feature>( + std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, const ::examples::Point*, ::examples::Feature*)>(&RouteGuide::Service::GetFeature), this), + new ::examples::Point, new ::examples::Feature)); + service_->AddMethod(new ::grpc::RpcServiceMethod( + RouteGuide_method_names[1], + ::grpc::RpcMethod::SERVER_STREAMING, + new ::grpc::ServerStreamingHandler< RouteGuide::Service, ::examples::Rectangle, ::examples::Feature>( + std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, const ::examples::Rectangle*, ::grpc::ServerWriter< ::examples::Feature>*)>(&RouteGuide::Service::ListFeatures), this), + new ::examples::Rectangle, new ::examples::Feature)); + service_->AddMethod(new ::grpc::RpcServiceMethod( + RouteGuide_method_names[2], + ::grpc::RpcMethod::CLIENT_STREAMING, + new ::grpc::ClientStreamingHandler< RouteGuide::Service, ::examples::Point, ::examples::RouteSummary>( + std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, ::grpc::ServerReader< ::examples::Point>*, ::examples::RouteSummary*)>(&RouteGuide::Service::RecordRoute), this), + new ::examples::Point, new ::examples::RouteSummary)); + service_->AddMethod(new ::grpc::RpcServiceMethod( + RouteGuide_method_names[3], + ::grpc::RpcMethod::BIDI_STREAMING, + new ::grpc::BidiStreamingHandler< RouteGuide::Service, ::examples::RouteNote, ::examples::RouteNote>( + std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, ::grpc::ServerReaderWriter< ::examples::RouteNote, ::examples::RouteNote>*)>(&RouteGuide::Service::RouteChat), this), + new ::examples::RouteNote, new ::examples::RouteNote)); + return service_; +} + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace examples + +// @@protoc_insertion_point(global_scope) diff --git a/cpp/route_guide/route_guide.pb.h b/cpp/route_guide/route_guide.pb.h new file mode 100644 index 00000000000..7689003f0a9 --- /dev/null +++ b/cpp/route_guide/route_guide.pb.h @@ -0,0 +1,929 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: route_guide.proto + +#ifndef PROTOBUF_route_5fguide_2eproto__INCLUDED +#define PROTOBUF_route_5fguide_2eproto__INCLUDED + +#include + +#include + +#if GOOGLE_PROTOBUF_VERSION < 3000000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace grpc { +class CompletionQueue; +class ChannelInterface; +class RpcService; +class ServerContext; +template class ClientAsyncResponseReader; +template class ServerAsyncResponseWriter; +template class ClientWriter; +template class ServerReader; +template class ClientAsyncWriter; +template class ServerAsyncReader; +template class ClientReader; +template class ServerWriter; +template class ClientAsyncReader; +template class ServerAsyncWriter; +template +class ClientReaderWriter; +template +class ServerReaderWriter; +template +class ClientAsyncReaderWriter; +template +class ServerAsyncReaderWriter; +} // namespace grpc +// @@protoc_insertion_point(includes) + +namespace examples { + +// Internal implementation detail -- do not call these. +void protobuf_AddDesc_route_5fguide_2eproto(); +void protobuf_AssignDesc_route_5fguide_2eproto(); +void protobuf_ShutdownFile_route_5fguide_2eproto(); + +class Point; +class Rectangle; +class Feature; +class RouteNote; +class RouteSummary; + +// =================================================================== + +class Point : public ::google::protobuf::Message { + public: + Point(); + virtual ~Point(); + + Point(const Point& from); + + inline Point& operator=(const Point& from) { + CopyFrom(from); + return *this; + } + + static const ::google::protobuf::Descriptor* descriptor(); + static const Point& default_instance(); + + void Swap(Point* other); + + // implements Message ---------------------------------------------- + + inline Point* New() const { return New(NULL); } + + Point* New(::google::protobuf::Arena* arena) const; + void CopyFrom(const ::google::protobuf::Message& from); + void MergeFrom(const ::google::protobuf::Message& from); + void CopyFrom(const Point& from); + void MergeFrom(const Point& from); + void Clear(); + bool IsInitialized() const; + + int ByteSize() const; + bool MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input); + void SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const; + ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; + int GetCachedSize() const { return _cached_size_; } + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const; + void InternalSwap(Point* other); + private: + inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); + } + inline void* MaybeArenaPtr() const { + return _internal_metadata_.raw_arena_ptr(); + } + public: + + ::google::protobuf::Metadata GetMetadata() const; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + // optional int32 latitude = 1; + inline void clear_latitude(); + static const int kLatitudeFieldNumber = 1; + inline ::google::protobuf::int32 latitude() const; + inline void set_latitude(::google::protobuf::int32 value); + + // optional int32 longitude = 2; + inline void clear_longitude(); + static const int kLongitudeFieldNumber = 2; + inline ::google::protobuf::int32 longitude() const; + inline void set_longitude(::google::protobuf::int32 value); + + // @@protoc_insertion_point(class_scope:examples.Point) + private: + + ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; + bool _is_default_instance_; + ::google::protobuf::int32 latitude_; + ::google::protobuf::int32 longitude_; + mutable int _cached_size_; + friend void protobuf_AddDesc_route_5fguide_2eproto(); + friend void protobuf_AssignDesc_route_5fguide_2eproto(); + friend void protobuf_ShutdownFile_route_5fguide_2eproto(); + + void InitAsDefaultInstance(); + static Point* default_instance_; +}; +// ------------------------------------------------------------------- + +class Rectangle : public ::google::protobuf::Message { + public: + Rectangle(); + virtual ~Rectangle(); + + Rectangle(const Rectangle& from); + + inline Rectangle& operator=(const Rectangle& from) { + CopyFrom(from); + return *this; + } + + static const ::google::protobuf::Descriptor* descriptor(); + static const Rectangle& default_instance(); + + void Swap(Rectangle* other); + + // implements Message ---------------------------------------------- + + inline Rectangle* New() const { return New(NULL); } + + Rectangle* New(::google::protobuf::Arena* arena) const; + void CopyFrom(const ::google::protobuf::Message& from); + void MergeFrom(const ::google::protobuf::Message& from); + void CopyFrom(const Rectangle& from); + void MergeFrom(const Rectangle& from); + void Clear(); + bool IsInitialized() const; + + int ByteSize() const; + bool MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input); + void SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const; + ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; + int GetCachedSize() const { return _cached_size_; } + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const; + void InternalSwap(Rectangle* other); + private: + inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); + } + inline void* MaybeArenaPtr() const { + return _internal_metadata_.raw_arena_ptr(); + } + public: + + ::google::protobuf::Metadata GetMetadata() const; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + // optional .examples.Point lo = 1; + inline bool has_lo() const; + inline void clear_lo(); + static const int kLoFieldNumber = 1; + inline const ::examples::Point& lo() const; + inline ::examples::Point* mutable_lo(); + inline ::examples::Point* release_lo(); + inline void set_allocated_lo(::examples::Point* lo); + + // optional .examples.Point hi = 2; + inline bool has_hi() const; + inline void clear_hi(); + static const int kHiFieldNumber = 2; + inline const ::examples::Point& hi() const; + inline ::examples::Point* mutable_hi(); + inline ::examples::Point* release_hi(); + inline void set_allocated_hi(::examples::Point* hi); + + // @@protoc_insertion_point(class_scope:examples.Rectangle) + private: + + ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; + bool _is_default_instance_; + ::examples::Point* lo_; + ::examples::Point* hi_; + mutable int _cached_size_; + friend void protobuf_AddDesc_route_5fguide_2eproto(); + friend void protobuf_AssignDesc_route_5fguide_2eproto(); + friend void protobuf_ShutdownFile_route_5fguide_2eproto(); + + void InitAsDefaultInstance(); + static Rectangle* default_instance_; +}; +// ------------------------------------------------------------------- + +class Feature : public ::google::protobuf::Message { + public: + Feature(); + virtual ~Feature(); + + Feature(const Feature& from); + + inline Feature& operator=(const Feature& from) { + CopyFrom(from); + return *this; + } + + static const ::google::protobuf::Descriptor* descriptor(); + static const Feature& default_instance(); + + void Swap(Feature* other); + + // implements Message ---------------------------------------------- + + inline Feature* New() const { return New(NULL); } + + Feature* New(::google::protobuf::Arena* arena) const; + void CopyFrom(const ::google::protobuf::Message& from); + void MergeFrom(const ::google::protobuf::Message& from); + void CopyFrom(const Feature& from); + void MergeFrom(const Feature& from); + void Clear(); + bool IsInitialized() const; + + int ByteSize() const; + bool MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input); + void SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const; + ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; + int GetCachedSize() const { return _cached_size_; } + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const; + void InternalSwap(Feature* other); + private: + inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); + } + inline void* MaybeArenaPtr() const { + return _internal_metadata_.raw_arena_ptr(); + } + public: + + ::google::protobuf::Metadata GetMetadata() const; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + // optional string name = 1; + inline void clear_name(); + static const int kNameFieldNumber = 1; + inline const ::std::string& name() const; + inline void set_name(const ::std::string& value); + inline void set_name(const char* value); + inline void set_name(const char* value, size_t size); + inline ::std::string* mutable_name(); + inline ::std::string* release_name(); + inline void set_allocated_name(::std::string* name); + + // optional .examples.Point location = 2; + inline bool has_location() const; + inline void clear_location(); + static const int kLocationFieldNumber = 2; + inline const ::examples::Point& location() const; + inline ::examples::Point* mutable_location(); + inline ::examples::Point* release_location(); + inline void set_allocated_location(::examples::Point* location); + + // @@protoc_insertion_point(class_scope:examples.Feature) + private: + + ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; + bool _is_default_instance_; + ::google::protobuf::internal::ArenaStringPtr name_; + ::examples::Point* location_; + mutable int _cached_size_; + friend void protobuf_AddDesc_route_5fguide_2eproto(); + friend void protobuf_AssignDesc_route_5fguide_2eproto(); + friend void protobuf_ShutdownFile_route_5fguide_2eproto(); + + void InitAsDefaultInstance(); + static Feature* default_instance_; +}; +// ------------------------------------------------------------------- + +class RouteNote : public ::google::protobuf::Message { + public: + RouteNote(); + virtual ~RouteNote(); + + RouteNote(const RouteNote& from); + + inline RouteNote& operator=(const RouteNote& from) { + CopyFrom(from); + return *this; + } + + static const ::google::protobuf::Descriptor* descriptor(); + static const RouteNote& default_instance(); + + void Swap(RouteNote* other); + + // implements Message ---------------------------------------------- + + inline RouteNote* New() const { return New(NULL); } + + RouteNote* New(::google::protobuf::Arena* arena) const; + void CopyFrom(const ::google::protobuf::Message& from); + void MergeFrom(const ::google::protobuf::Message& from); + void CopyFrom(const RouteNote& from); + void MergeFrom(const RouteNote& from); + void Clear(); + bool IsInitialized() const; + + int ByteSize() const; + bool MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input); + void SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const; + ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; + int GetCachedSize() const { return _cached_size_; } + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const; + void InternalSwap(RouteNote* other); + private: + inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); + } + inline void* MaybeArenaPtr() const { + return _internal_metadata_.raw_arena_ptr(); + } + public: + + ::google::protobuf::Metadata GetMetadata() const; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + // optional .examples.Point location = 1; + inline bool has_location() const; + inline void clear_location(); + static const int kLocationFieldNumber = 1; + inline const ::examples::Point& location() const; + inline ::examples::Point* mutable_location(); + inline ::examples::Point* release_location(); + inline void set_allocated_location(::examples::Point* location); + + // optional string message = 2; + inline void clear_message(); + static const int kMessageFieldNumber = 2; + inline const ::std::string& message() const; + inline void set_message(const ::std::string& value); + inline void set_message(const char* value); + inline void set_message(const char* value, size_t size); + inline ::std::string* mutable_message(); + inline ::std::string* release_message(); + inline void set_allocated_message(::std::string* message); + + // @@protoc_insertion_point(class_scope:examples.RouteNote) + private: + + ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; + bool _is_default_instance_; + ::examples::Point* location_; + ::google::protobuf::internal::ArenaStringPtr message_; + mutable int _cached_size_; + friend void protobuf_AddDesc_route_5fguide_2eproto(); + friend void protobuf_AssignDesc_route_5fguide_2eproto(); + friend void protobuf_ShutdownFile_route_5fguide_2eproto(); + + void InitAsDefaultInstance(); + static RouteNote* default_instance_; +}; +// ------------------------------------------------------------------- + +class RouteSummary : public ::google::protobuf::Message { + public: + RouteSummary(); + virtual ~RouteSummary(); + + RouteSummary(const RouteSummary& from); + + inline RouteSummary& operator=(const RouteSummary& from) { + CopyFrom(from); + return *this; + } + + static const ::google::protobuf::Descriptor* descriptor(); + static const RouteSummary& default_instance(); + + void Swap(RouteSummary* other); + + // implements Message ---------------------------------------------- + + inline RouteSummary* New() const { return New(NULL); } + + RouteSummary* New(::google::protobuf::Arena* arena) const; + void CopyFrom(const ::google::protobuf::Message& from); + void MergeFrom(const ::google::protobuf::Message& from); + void CopyFrom(const RouteSummary& from); + void MergeFrom(const RouteSummary& from); + void Clear(); + bool IsInitialized() const; + + int ByteSize() const; + bool MergePartialFromCodedStream( + ::google::protobuf::io::CodedInputStream* input); + void SerializeWithCachedSizes( + ::google::protobuf::io::CodedOutputStream* output) const; + ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; + int GetCachedSize() const { return _cached_size_; } + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const; + void InternalSwap(RouteSummary* other); + private: + inline ::google::protobuf::Arena* GetArenaNoVirtual() const { + return _internal_metadata_.arena(); + } + inline void* MaybeArenaPtr() const { + return _internal_metadata_.raw_arena_ptr(); + } + public: + + ::google::protobuf::Metadata GetMetadata() const; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + // optional int32 point_count = 1; + inline void clear_point_count(); + static const int kPointCountFieldNumber = 1; + inline ::google::protobuf::int32 point_count() const; + inline void set_point_count(::google::protobuf::int32 value); + + // optional int32 feature_count = 2; + inline void clear_feature_count(); + static const int kFeatureCountFieldNumber = 2; + inline ::google::protobuf::int32 feature_count() const; + inline void set_feature_count(::google::protobuf::int32 value); + + // optional int32 distance = 3; + inline void clear_distance(); + static const int kDistanceFieldNumber = 3; + inline ::google::protobuf::int32 distance() const; + inline void set_distance(::google::protobuf::int32 value); + + // optional int32 elapsed_time = 4; + inline void clear_elapsed_time(); + static const int kElapsedTimeFieldNumber = 4; + inline ::google::protobuf::int32 elapsed_time() const; + inline void set_elapsed_time(::google::protobuf::int32 value); + + // @@protoc_insertion_point(class_scope:examples.RouteSummary) + private: + + ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; + bool _is_default_instance_; + ::google::protobuf::int32 point_count_; + ::google::protobuf::int32 feature_count_; + ::google::protobuf::int32 distance_; + ::google::protobuf::int32 elapsed_time_; + mutable int _cached_size_; + friend void protobuf_AddDesc_route_5fguide_2eproto(); + friend void protobuf_AssignDesc_route_5fguide_2eproto(); + friend void protobuf_ShutdownFile_route_5fguide_2eproto(); + + void InitAsDefaultInstance(); + static RouteSummary* default_instance_; +}; +// =================================================================== + + +// =================================================================== + +// Point + +// optional int32 latitude = 1; +inline void Point::clear_latitude() { + latitude_ = 0; +} +inline ::google::protobuf::int32 Point::latitude() const { + // @@protoc_insertion_point(field_get:examples.Point.latitude) + return latitude_; +} +inline void Point::set_latitude(::google::protobuf::int32 value) { + + latitude_ = value; + // @@protoc_insertion_point(field_set:examples.Point.latitude) +} + +// optional int32 longitude = 2; +inline void Point::clear_longitude() { + longitude_ = 0; +} +inline ::google::protobuf::int32 Point::longitude() const { + // @@protoc_insertion_point(field_get:examples.Point.longitude) + return longitude_; +} +inline void Point::set_longitude(::google::protobuf::int32 value) { + + longitude_ = value; + // @@protoc_insertion_point(field_set:examples.Point.longitude) +} + +// ------------------------------------------------------------------- + +// Rectangle + +// optional .examples.Point lo = 1; +inline bool Rectangle::has_lo() const { + return !_is_default_instance_ && lo_ != NULL; +} +inline void Rectangle::clear_lo() { + if (lo_ != NULL) delete lo_; + lo_ = NULL; +} +inline const ::examples::Point& Rectangle::lo() const { + // @@protoc_insertion_point(field_get:examples.Rectangle.lo) + return lo_ != NULL ? *lo_ : *default_instance_->lo_; +} +inline ::examples::Point* Rectangle::mutable_lo() { + + if (lo_ == NULL) { + lo_ = new ::examples::Point; + } + // @@protoc_insertion_point(field_mutable:examples.Rectangle.lo) + return lo_; +} +inline ::examples::Point* Rectangle::release_lo() { + + ::examples::Point* temp = lo_; + lo_ = NULL; + return temp; +} +inline void Rectangle::set_allocated_lo(::examples::Point* lo) { + delete lo_; + lo_ = lo; + if (lo) { + + } else { + + } + // @@protoc_insertion_point(field_set_allocated:examples.Rectangle.lo) +} + +// optional .examples.Point hi = 2; +inline bool Rectangle::has_hi() const { + return !_is_default_instance_ && hi_ != NULL; +} +inline void Rectangle::clear_hi() { + if (hi_ != NULL) delete hi_; + hi_ = NULL; +} +inline const ::examples::Point& Rectangle::hi() const { + // @@protoc_insertion_point(field_get:examples.Rectangle.hi) + return hi_ != NULL ? *hi_ : *default_instance_->hi_; +} +inline ::examples::Point* Rectangle::mutable_hi() { + + if (hi_ == NULL) { + hi_ = new ::examples::Point; + } + // @@protoc_insertion_point(field_mutable:examples.Rectangle.hi) + return hi_; +} +inline ::examples::Point* Rectangle::release_hi() { + + ::examples::Point* temp = hi_; + hi_ = NULL; + return temp; +} +inline void Rectangle::set_allocated_hi(::examples::Point* hi) { + delete hi_; + hi_ = hi; + if (hi) { + + } else { + + } + // @@protoc_insertion_point(field_set_allocated:examples.Rectangle.hi) +} + +// ------------------------------------------------------------------- + +// Feature + +// optional string name = 1; +inline void Feature::clear_name() { + name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline const ::std::string& Feature::name() const { + // @@protoc_insertion_point(field_get:examples.Feature.name) + return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void Feature::set_name(const ::std::string& value) { + + name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + // @@protoc_insertion_point(field_set:examples.Feature.name) +} +inline void Feature::set_name(const char* value) { + + name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + // @@protoc_insertion_point(field_set_char:examples.Feature.name) +} +inline void Feature::set_name(const char* value, size_t size) { + + name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + ::std::string(reinterpret_cast(value), size)); + // @@protoc_insertion_point(field_set_pointer:examples.Feature.name) +} +inline ::std::string* Feature::mutable_name() { + + // @@protoc_insertion_point(field_mutable:examples.Feature.name) + return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline ::std::string* Feature::release_name() { + + return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void Feature::set_allocated_name(::std::string* name) { + if (name != NULL) { + + } else { + + } + name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + // @@protoc_insertion_point(field_set_allocated:examples.Feature.name) +} + +// optional .examples.Point location = 2; +inline bool Feature::has_location() const { + return !_is_default_instance_ && location_ != NULL; +} +inline void Feature::clear_location() { + if (location_ != NULL) delete location_; + location_ = NULL; +} +inline const ::examples::Point& Feature::location() const { + // @@protoc_insertion_point(field_get:examples.Feature.location) + return location_ != NULL ? *location_ : *default_instance_->location_; +} +inline ::examples::Point* Feature::mutable_location() { + + if (location_ == NULL) { + location_ = new ::examples::Point; + } + // @@protoc_insertion_point(field_mutable:examples.Feature.location) + return location_; +} +inline ::examples::Point* Feature::release_location() { + + ::examples::Point* temp = location_; + location_ = NULL; + return temp; +} +inline void Feature::set_allocated_location(::examples::Point* location) { + delete location_; + location_ = location; + if (location) { + + } else { + + } + // @@protoc_insertion_point(field_set_allocated:examples.Feature.location) +} + +// ------------------------------------------------------------------- + +// RouteNote + +// optional .examples.Point location = 1; +inline bool RouteNote::has_location() const { + return !_is_default_instance_ && location_ != NULL; +} +inline void RouteNote::clear_location() { + if (location_ != NULL) delete location_; + location_ = NULL; +} +inline const ::examples::Point& RouteNote::location() const { + // @@protoc_insertion_point(field_get:examples.RouteNote.location) + return location_ != NULL ? *location_ : *default_instance_->location_; +} +inline ::examples::Point* RouteNote::mutable_location() { + + if (location_ == NULL) { + location_ = new ::examples::Point; + } + // @@protoc_insertion_point(field_mutable:examples.RouteNote.location) + return location_; +} +inline ::examples::Point* RouteNote::release_location() { + + ::examples::Point* temp = location_; + location_ = NULL; + return temp; +} +inline void RouteNote::set_allocated_location(::examples::Point* location) { + delete location_; + location_ = location; + if (location) { + + } else { + + } + // @@protoc_insertion_point(field_set_allocated:examples.RouteNote.location) +} + +// optional string message = 2; +inline void RouteNote::clear_message() { + message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline const ::std::string& RouteNote::message() const { + // @@protoc_insertion_point(field_get:examples.RouteNote.message) + return message_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void RouteNote::set_message(const ::std::string& value) { + + message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + // @@protoc_insertion_point(field_set:examples.RouteNote.message) +} +inline void RouteNote::set_message(const char* value) { + + message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); + // @@protoc_insertion_point(field_set_char:examples.RouteNote.message) +} +inline void RouteNote::set_message(const char* value, size_t size) { + + message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), + ::std::string(reinterpret_cast(value), size)); + // @@protoc_insertion_point(field_set_pointer:examples.RouteNote.message) +} +inline ::std::string* RouteNote::mutable_message() { + + // @@protoc_insertion_point(field_mutable:examples.RouteNote.message) + return message_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline ::std::string* RouteNote::release_message() { + + return message_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); +} +inline void RouteNote::set_allocated_message(::std::string* message) { + if (message != NULL) { + + } else { + + } + message_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), message); + // @@protoc_insertion_point(field_set_allocated:examples.RouteNote.message) +} + +// ------------------------------------------------------------------- + +// RouteSummary + +// optional int32 point_count = 1; +inline void RouteSummary::clear_point_count() { + point_count_ = 0; +} +inline ::google::protobuf::int32 RouteSummary::point_count() const { + // @@protoc_insertion_point(field_get:examples.RouteSummary.point_count) + return point_count_; +} +inline void RouteSummary::set_point_count(::google::protobuf::int32 value) { + + point_count_ = value; + // @@protoc_insertion_point(field_set:examples.RouteSummary.point_count) +} + +// optional int32 feature_count = 2; +inline void RouteSummary::clear_feature_count() { + feature_count_ = 0; +} +inline ::google::protobuf::int32 RouteSummary::feature_count() const { + // @@protoc_insertion_point(field_get:examples.RouteSummary.feature_count) + return feature_count_; +} +inline void RouteSummary::set_feature_count(::google::protobuf::int32 value) { + + feature_count_ = value; + // @@protoc_insertion_point(field_set:examples.RouteSummary.feature_count) +} + +// optional int32 distance = 3; +inline void RouteSummary::clear_distance() { + distance_ = 0; +} +inline ::google::protobuf::int32 RouteSummary::distance() const { + // @@protoc_insertion_point(field_get:examples.RouteSummary.distance) + return distance_; +} +inline void RouteSummary::set_distance(::google::protobuf::int32 value) { + + distance_ = value; + // @@protoc_insertion_point(field_set:examples.RouteSummary.distance) +} + +// optional int32 elapsed_time = 4; +inline void RouteSummary::clear_elapsed_time() { + elapsed_time_ = 0; +} +inline ::google::protobuf::int32 RouteSummary::elapsed_time() const { + // @@protoc_insertion_point(field_get:examples.RouteSummary.elapsed_time) + return elapsed_time_; +} +inline void RouteSummary::set_elapsed_time(::google::protobuf::int32 value) { + + elapsed_time_ = value; + // @@protoc_insertion_point(field_set:examples.RouteSummary.elapsed_time) +} + + +class RouteGuide final { + public: + class Stub final : public ::grpc::InternalStub { + public: + ::grpc::Status GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::examples::Feature* response); + ::grpc::ClientAsyncResponseReader< ::examples::Feature>* GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::grpc::CompletionQueue* cq, void* tag); + ::grpc::ClientReader< ::examples::Feature>* ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request); + ::grpc::ClientAsyncReader< ::examples::Feature>* ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request, ::grpc::CompletionQueue* cq, void* tag); + ::grpc::ClientWriter< ::examples::Point>* RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response); + ::grpc::ClientAsyncWriter< ::examples::Point>* RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response, ::grpc::CompletionQueue* cq, void* tag); + ::grpc::ClientReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteChat(::grpc::ClientContext* context); + ::grpc::ClientAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteChat(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag); + }; + static Stub* NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + + class Service : public ::grpc::SynchronousService { + public: + Service() : service_(nullptr) {} + virtual ~Service(); + virtual ::grpc::Status GetFeature(::grpc::ServerContext* context, const ::examples::Point* request, ::examples::Feature* response); + virtual ::grpc::Status ListFeatures(::grpc::ServerContext* context, const ::examples::Rectangle* request, ::grpc::ServerWriter< ::examples::Feature>* writer); + virtual ::grpc::Status RecordRoute(::grpc::ServerContext* context, ::grpc::ServerReader< ::examples::Point>* reader, ::examples::RouteSummary* response); + virtual ::grpc::Status RouteChat(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream); + ::grpc::RpcService* service() override final; + private: + ::grpc::RpcService* service_; + }; + class AsyncService final : public ::grpc::AsynchronousService { + public: + explicit AsyncService(::grpc::CompletionQueue* cq); + ~AsyncService() {}; + void RequestGetFeature(::grpc::ServerContext* context, ::examples::Point* request, ::grpc::ServerAsyncResponseWriter< ::examples::Feature>* response, ::grpc::CompletionQueue* cq, void *tag); + void RequestListFeatures(::grpc::ServerContext* context, ::examples::Rectangle* request, ::grpc::ServerAsyncWriter< ::examples::Feature>* writer, ::grpc::CompletionQueue* cq, void *tag); + void RequestRecordRoute(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< ::examples::RouteSummary, ::examples::Point>* reader, ::grpc::CompletionQueue* cq, void *tag); + void RequestRouteChat(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream, ::grpc::CompletionQueue* cq, void *tag); + }; +}; + +// @@protoc_insertion_point(namespace_scope) + +} // namespace examples + +#ifndef SWIG +namespace google { +namespace protobuf { + + +} // namespace protobuf +} // namespace google +#endif // SWIG + +// @@protoc_insertion_point(global_scope) + +#endif // PROTOBUF_route_5fguide_2eproto__INCLUDED diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc new file mode 100644 index 00000000000..4a51f5eb382 --- /dev/null +++ b/cpp/route_guide/route_guide_client.cc @@ -0,0 +1,91 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "helloworld.pb.h" + +using grpc::ChannelArguments; +using grpc::ChannelInterface; +using grpc::ClientContext; +using grpc::Status; +using helloworld::HelloRequest; +using helloworld::HelloReply; +using helloworld::Greeter; + +class GreeterClient { + public: + GreeterClient(std::shared_ptr channel) + : stub_(Greeter::NewStub(channel)) {} + + std::string SayHello(const std::string& user) { + HelloRequest request; + request.set_name(user); + HelloReply reply; + ClientContext context; + + Status status = stub_->sayHello(&context, request, &reply); + if (status.IsOk()) { + return reply.message(); + } else { + return "Rpc failed"; + } + } + + void Shutdown() { stub_.reset(); } + + private: + std::unique_ptr stub_; +}; + +int main(int argc, char** argv) { + grpc_init(); + + GreeterClient greeter( + grpc::CreateChannel("localhost:50051", ChannelArguments())); + std::string user("world"); + std::string reply = greeter.SayHello(user); + std::cout << "Greeter received: " << reply << std::endl; + + greeter.Shutdown(); + + grpc_shutdown(); +} diff --git a/cpp/route_guide/route_guide_server.cc b/cpp/route_guide/route_guide_server.cc new file mode 100644 index 00000000000..3a2ab60e892 --- /dev/null +++ b/cpp/route_guide/route_guide_server.cc @@ -0,0 +1,84 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include "helloworld.pb.h" + +using grpc::Server; +using grpc::ServerBuilder; +using grpc::ServerContext; +using grpc::Status; +using helloworld::HelloRequest; +using helloworld::HelloReply; +using helloworld::Greeter; + +class GreeterServiceImpl final : public Greeter::Service { + Status sayHello(ServerContext* context, const HelloRequest* request, + HelloReply* reply) override { + std::string prefix("Hello "); + reply->set_message(prefix + request->name()); + return Status::OK; + } +}; + +void RunServer() { + std::string server_address("0.0.0.0:50051"); + GreeterServiceImpl service; + + ServerBuilder builder; + builder.AddPort(server_address); + builder.RegisterService(&service); + std::unique_ptr server(builder.BuildAndStart()); + std::cout << "Server listening on " << server_address << std::endl; + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(5)); + } +} + +int main(int argc, char** argv) { + grpc_init(); + + RunServer(); + + grpc_shutdown(); + return 0; +} From 600d70cd8dbebd1ef86cad1d1ba0faf600002250 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Fri, 20 Feb 2015 10:50:46 -0800 Subject: [PATCH 078/576] change proto README cpp node ruby --- README.md | 6 +++--- cpp/helloworld/greeter_client.cc | 2 +- cpp/helloworld/greeter_server.cc | 2 +- cpp/helloworld/helloworld.pb.cc | 14 +++++++------- cpp/helloworld/helloworld.pb.h | 8 ++++---- node/greeter_client.js | 2 +- node/greeter_server.js | 6 +++--- node/helloworld.proto | 2 +- protos/helloworld.proto | 2 +- ruby/greeter_server.rb | 2 +- ruby/lib/helloworld_services.rb | 2 +- 11 files changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 3a2fb8d7d1e..c48007a1cbd 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,7 @@ package helloworld; // The greeting service definition. service Greeter { // Sends a greeting - rpc sayHello (HelloRequest) returns (HelloReply) {} + rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. @@ -254,7 +254,7 @@ which contains (along with some other useful code): ```java public static interface Greeter { - public void sayHello(ex.grpc.Helloworld.HelloRequest request, + public void SayHello(ex.grpc.Helloworld.HelloRequest request, com.google.net.stubby.stub.StreamObserver responseObserver); } @@ -405,7 +405,7 @@ from which we can get our greeting. try { Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName(name).build(); - Helloworld.HelloReply reply = blockingStub.sayHello(request); + Helloworld.HelloReply reply = blockingStub.SayHello(request); logger.info("Greeting: " + reply.getMessage()); } catch (RuntimeException e) { logger.log(Level.WARNING, "RPC failed", e); diff --git a/cpp/helloworld/greeter_client.cc b/cpp/helloworld/greeter_client.cc index 4a51f5eb382..3c2bbc20747 100644 --- a/cpp/helloworld/greeter_client.cc +++ b/cpp/helloworld/greeter_client.cc @@ -62,7 +62,7 @@ class GreeterClient { HelloReply reply; ClientContext context; - Status status = stub_->sayHello(&context, request, &reply); + Status status = stub_->SayHello(&context, request, &reply); if (status.IsOk()) { return reply.message(); } else { diff --git a/cpp/helloworld/greeter_server.cc b/cpp/helloworld/greeter_server.cc index 3a2ab60e892..01a0bf242dd 100644 --- a/cpp/helloworld/greeter_server.cc +++ b/cpp/helloworld/greeter_server.cc @@ -52,7 +52,7 @@ using helloworld::HelloReply; using helloworld::Greeter; class GreeterServiceImpl final : public Greeter::Service { - Status sayHello(ServerContext* context, const HelloRequest* request, + Status SayHello(ServerContext* context, const HelloRequest* request, HelloReply* reply) override { std::string prefix("Hello "); reply->set_message(prefix + request->name()); diff --git a/cpp/helloworld/helloworld.pb.cc b/cpp/helloworld/helloworld.pb.cc index a5b82c5ed5b..9540f2c94c1 100644 --- a/cpp/helloworld/helloworld.pb.cc +++ b/cpp/helloworld/helloworld.pb.cc @@ -109,7 +109,7 @@ void protobuf_AddDesc_helloworld_2eproto() { ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\020helloworld.proto\022\nhelloworld\"\034\n\014HelloR" "equest\022\014\n\004name\030\001 \001(\t\"\035\n\nHelloReply\022\017\n\007me" - "ssage\030\001 \001(\t2I\n\007Greeter\022>\n\010sayHello\022\030.hel" + "ssage\030\001 \001(\t2I\n\007Greeter\022>\n\010SayHello\022\030.hel" "loworld.HelloRequest\032\026.helloworld.HelloR" "eply\"\000B\t\n\007ex.grpcb\006proto3", 185); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( @@ -587,7 +587,7 @@ void HelloReply::InternalSwap(HelloReply* other) { static const char* Greeter_method_names[] = { - "/helloworld.Greeter/sayHello", + "/helloworld.Greeter/SayHello", }; Greeter::Stub* Greeter::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) { @@ -596,11 +596,11 @@ Greeter::Stub* Greeter::NewStub(const std::shared_ptr< ::grpc::ChannelInterface> return stub; }; -::grpc::Status Greeter::Stub::sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response) { +::grpc::Status Greeter::Stub::SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response) { return ::grpc::BlockingUnaryCall(channel(),::grpc::RpcMethod(Greeter_method_names[0]), context, request, response); } -::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* Greeter::Stub::sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag) { +::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* Greeter::Stub::SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag) { return new ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>(channel(), cq, ::grpc::RpcMethod(Greeter_method_names[0]), context, request, tag); } @@ -610,11 +610,11 @@ Greeter::Service::~Service() { delete service_; } -::grpc::Status Greeter::Service::sayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloReply* response) { +::grpc::Status Greeter::Service::SayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloReply* response) { return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); } -void Greeter::AsyncService::RequestsayHello(::grpc::ServerContext* context, ::helloworld::HelloRequest* request, ::grpc::ServerAsyncResponseWriter< ::helloworld::HelloReply>* response, ::grpc::CompletionQueue* cq, void* tag) { +void Greeter::AsyncService::RequestSayHello(::grpc::ServerContext* context, ::helloworld::HelloRequest* request, ::grpc::ServerAsyncResponseWriter< ::helloworld::HelloReply>* response, ::grpc::CompletionQueue* cq, void* tag) { AsynchronousService::RequestAsyncUnary(0, context, request, response, cq, tag); } @@ -627,7 +627,7 @@ void Greeter::AsyncService::RequestsayHello(::grpc::ServerContext* context, ::he Greeter_method_names[0], ::grpc::RpcMethod::NORMAL_RPC, new ::grpc::RpcMethodHandler< Greeter::Service, ::helloworld::HelloRequest, ::helloworld::HelloReply>( - std::function< ::grpc::Status(Greeter::Service*, ::grpc::ServerContext*, const ::helloworld::HelloRequest*, ::helloworld::HelloReply*)>(&Greeter::Service::sayHello), this), + std::function< ::grpc::Status(Greeter::Service*, ::grpc::ServerContext*, const ::helloworld::HelloRequest*, ::helloworld::HelloReply*)>(&Greeter::Service::SayHello), this), new ::helloworld::HelloRequest, new ::helloworld::HelloReply)); return service_; } diff --git a/cpp/helloworld/helloworld.pb.h b/cpp/helloworld/helloworld.pb.h index f49adae84a8..1eb870166af 100644 --- a/cpp/helloworld/helloworld.pb.h +++ b/cpp/helloworld/helloworld.pb.h @@ -319,8 +319,8 @@ class Greeter final { public: class Stub final : public ::grpc::InternalStub { public: - ::grpc::Status sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response); - ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* sayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag); + ::grpc::Status SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response); + ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag); }; static Stub* NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); @@ -328,7 +328,7 @@ class Greeter final { public: Service() : service_(nullptr) {} virtual ~Service(); - virtual ::grpc::Status sayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloReply* response); + virtual ::grpc::Status SayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloReply* response); ::grpc::RpcService* service() override final; private: ::grpc::RpcService* service_; @@ -337,7 +337,7 @@ class Greeter final { public: explicit AsyncService(::grpc::CompletionQueue* cq); ~AsyncService() {}; - void RequestsayHello(::grpc::ServerContext* context, ::helloworld::HelloRequest* request, ::grpc::ServerAsyncResponseWriter< ::helloworld::HelloReply>* response, ::grpc::CompletionQueue* cq, void *tag); + void RequestSayHello(::grpc::ServerContext* context, ::helloworld::HelloRequest* request, ::grpc::ServerAsyncResponseWriter< ::helloworld::HelloReply>* response, ::grpc::CompletionQueue* cq, void *tag); }; }; diff --git a/node/greeter_client.js b/node/greeter_client.js index ab7050ab213..db45afca77a 100644 --- a/node/greeter_client.js +++ b/node/greeter_client.js @@ -44,7 +44,7 @@ function main() { } else { user = 'world'; } - client.sayHello({name: user}, function(err, response) { + client.SayHello({name: user}, function(err, response) { console.log('Greeting:', response.message); }); } diff --git a/node/greeter_server.js b/node/greeter_server.js index 6d4183c0ced..fa95cea2e9a 100644 --- a/node/greeter_server.js +++ b/node/greeter_server.js @@ -39,9 +39,9 @@ var hello_proto = grpc.load(PROTO_PATH).helloworld; var Server = grpc.buildServer([hello_proto.Greeter.service]); /** - * Implements the sayHello RPC method. + * Implements the SayHello RPC method. */ -function sayHello(call, callback) { +function SayHello(call, callback) { callback(null, {message: 'Hello ' + call.request.name}); } @@ -52,7 +52,7 @@ function sayHello(call, callback) { function main() { var server = new Server({ "helloworld.Greeter": { - sayHello: sayHello + SayHello: SayHello } }); diff --git a/node/helloworld.proto b/node/helloworld.proto index e1f5700725a..a52c947f895 100644 --- a/node/helloworld.proto +++ b/node/helloworld.proto @@ -36,7 +36,7 @@ package helloworld; // The greeting service definition. service Greeter { // Sends a greeting - rpc sayHello (HelloRequest) returns (HelloReply) {} + rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. diff --git a/protos/helloworld.proto b/protos/helloworld.proto index 4781fb48304..f9abd3d87f7 100644 --- a/protos/helloworld.proto +++ b/protos/helloworld.proto @@ -36,7 +36,7 @@ package helloworld; // The greeting service definition. service Greeter { // Sends a greeting - rpc sayHello (HelloRequest) returns (HelloReply) {} + rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. diff --git a/ruby/greeter_server.rb b/ruby/greeter_server.rb index eb1a6ab454c..d4f9cf7d0f8 100755 --- a/ruby/greeter_server.rb +++ b/ruby/greeter_server.rb @@ -42,7 +42,7 @@ require 'helloworld_services' # GreeterServer is simple server that implements the Helloworld Greeter server. class GreeterServer < Helloworld::Greeter::Service - # say_hello implements the sayHello rpc method. + # say_hello implements the SayHello rpc method. def say_hello(hello_req, _unused_call) Helloworld::HelloReply.new(message: "Hello #{hello_req.name}") end diff --git a/ruby/lib/helloworld_services.rb b/ruby/lib/helloworld_services.rb index 9bd528485af..7da45ebc6b2 100644 --- a/ruby/lib/helloworld_services.rb +++ b/ruby/lib/helloworld_services.rb @@ -16,7 +16,7 @@ module Helloworld self.unmarshal_class_method = :decode self.service_name = 'helloworld.Greeter' - rpc :sayHello, HelloRequest, HelloReply + rpc :SayHello, HelloRequest, HelloReply end Stub = Service.rpc_stub_class From bfad7921e122d83549f0b0947737273904bcc17f Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Fri, 20 Feb 2015 11:30:46 -0800 Subject: [PATCH 079/576] makefile change --- cpp/route_guide/Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cpp/route_guide/Makefile b/cpp/route_guide/Makefile index b9579e0c96d..444841f8b8d 100644 --- a/cpp/route_guide/Makefile +++ b/cpp/route_guide/Makefile @@ -34,14 +34,14 @@ CPPFLAGS=-I/usr/local/include -pthread CXXFLAGS=-std=c++11 LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl -all: greeter_client greeter_server +all: route_guide_client route_guide_server -greeter_client: helloworld.pb.o greeter_client.o +route_guide_client: route_guide.pb.o route_guide_client.o $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ -greeter_server: helloworld.pb.o greeter_server.o +route_guide_server: route_guide.pb.o route_guide_server.o $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ clean: - rm -f *.o greeter_client greeter_server + rm -f *.o route_guide_client route_guide_server From 3440548d83452321d72e2b93992c298f999f1359 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Fri, 20 Feb 2015 11:35:20 -0800 Subject: [PATCH 080/576] revert js changes. --- node/greeter_client.js | 2 +- node/greeter_server.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/node/greeter_client.js b/node/greeter_client.js index db45afca77a..ab7050ab213 100644 --- a/node/greeter_client.js +++ b/node/greeter_client.js @@ -44,7 +44,7 @@ function main() { } else { user = 'world'; } - client.SayHello({name: user}, function(err, response) { + client.sayHello({name: user}, function(err, response) { console.log('Greeting:', response.message); }); } diff --git a/node/greeter_server.js b/node/greeter_server.js index fa95cea2e9a..2fb95f0f90e 100644 --- a/node/greeter_server.js +++ b/node/greeter_server.js @@ -41,7 +41,7 @@ var Server = grpc.buildServer([hello_proto.Greeter.service]); /** * Implements the SayHello RPC method. */ -function SayHello(call, callback) { +function sayHello(call, callback) { callback(null, {message: 'Hello ' + call.request.name}); } @@ -52,7 +52,7 @@ function SayHello(call, callback) { function main() { var server = new Server({ "helloworld.Greeter": { - SayHello: SayHello + sayHello: sayHello } }); From b7538ee7554fde3e5225db379c816ed78f4c93f7 Mon Sep 17 00:00:00 2001 From: "Nicolas \"Pixel\" Noble" Date: Fri, 20 Feb 2015 22:56:43 +0100 Subject: [PATCH 081/576] Improving user experience. --- cpp/helloworld/Makefile | 79 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 71 insertions(+), 8 deletions(-) diff --git a/cpp/helloworld/Makefile b/cpp/helloworld/Makefile index b9579e0c96d..83f2ad49044 100644 --- a/cpp/helloworld/Makefile +++ b/cpp/helloworld/Makefile @@ -29,19 +29,82 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -CXX=g++ -CPPFLAGS=-I/usr/local/include -pthread -CXXFLAGS=-std=c++11 -LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl +CXX = g++ +CPPFLAGS = -I/usr/local/include -pthread +CXXFLAGS = -std=c++11 +LDFLAGS = -L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl +PROTOC = protoc +GRPC_CPP_PLUGIN = grpc_cpp_plugin +GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)` -all: greeter_client greeter_server +PROTOS_PATH = ../../protos + +vpath %.proto $(PROTOS_PATH) + +all: system-check greeter_client greeter_server greeter_client: helloworld.pb.o greeter_client.o - $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ + $(CXX) $^ $(LDFLAGS) -o $@ greeter_server: helloworld.pb.o greeter_server.o - $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ + $(CXX) $^ $(LDFLAGS) -o $@ + +%.pb.cc: %.proto + $(PROTOC) -I $(PROTOS_PATH) --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $< clean: - rm -f *.o greeter_client greeter_server + rm -f *.o *.pb.cc *.pb.h greeter_client greeter_server + + +# The following is to test your system and ensure a smoother experience. +# They are by no means necessary to actually compile a grpc-enabled software. + +PROTOC_CMD = which $(PROTOC) +PROTOC_CHECK_CMD = $(PROTOC) --version | grep -q libprotoc.3 +PLUGIN_CHECK_CMD = which $(GRPC_CPP_PLUGIN) +HAS_PROTOC = $(shell $(PROTOC_CMD) > /dev/null && echo true || echo false) +ifeq ($(HAS_PROTOC),true) +HAS_VALID_PROTOC = $(shell $(PROTOC_CHECK_CMD) 2> /dev/null && echo true || echo false) +endif +HAS_PLUGIN = $(shell $(PLUGIN_CHECK_CMD) > /dev/null && echo true || echo false) + +SYSTEM_OK = false +ifeq ($(HAS_VALID_PROTOC),true) +ifeq ($(HAS_PLUGIN),true) +SYSTEM_OK = true +endif +endif +system-check: +ifneq ($(HAS_VALID_PROTOC),true) + @echo " DEPENDENCY ERROR" + @echo + @echo "You don't have protoc 3.0.0 installed in your path." + @echo "Please install Google protocol buffers 3.0.0 and its compiler." + @echo "You can find it here:" + @echo + @echo " https://github.com/google/protobuf/releases/tag/v3.0.0-alpha-1" + @echo + @echo "Here is what I get when trying to evaluate your version of protoc:" + @echo + -$(PROTOC) --version + @echo + @echo +endif +ifneq ($(HAS_PLUGIN),true) + @echo " DEPENDENCY ERROR" + @echo + @echo "You don't have the grpc c++ protobuf plugin installed in your path." + @echo "Please install grpc. You can find it here:" + @echo + @echo " https://github.com/grpc/grpc" + @echo + @echo "Here is what I get when trying to detect if you have the plugin:" + @echo + -which $(GRPC_CPP_PLUGIN) + @echo + @echo +endif +ifneq ($(SYSTEM_OK),true) + @false +endif From 8c0464dcf64507d028601abe97e003720c656922 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 20 Feb 2015 14:19:31 -0800 Subject: [PATCH 082/576] Fixes var name --- go/greeter_server/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go/greeter_server/main.go b/go/greeter_server/main.go index 643524bde76..231f5c607ba 100644 --- a/go/greeter_server/main.go +++ b/go/greeter_server/main.go @@ -55,11 +55,11 @@ func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloRe } func main() { - l, err := net.Listen("tcp", port) + lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) - s.Serve(l) + s.Serve(lis) } From bc0c2dcc6b91e56eaacab5990106450d0560d542 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Fri, 20 Feb 2015 15:24:56 -0800 Subject: [PATCH 083/576] Created new top-level README_NEW --- README_NEW.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 README_NEW.md diff --git a/README_NEW.md b/README_NEW.md new file mode 100644 index 00000000000..583136bc0dd --- /dev/null +++ b/README_NEW.md @@ -0,0 +1,8 @@ + +# Please pick your language to proceed: +### [C++](https://github.com/grpc/grpc-common/tree/master/cpp) +### [Java](https://github.com/grpc/grpc-common/tree/master/java) +### [Python](https://github.com/grpc/grpc-common/tree/master/python) +### [Go](https://github.com/grpc/grpc-common/tree/master/go) +### [ruby](https://github.com/grpc/grpc-common/tree/master/ruby) +### [Node.js](https://github.com/grpc/grpc-common/tree/master/node) From 3a5592ce1ebfe3af2169b05827d5b9eee6ad8067 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Fri, 20 Feb 2015 15:32:42 -0800 Subject: [PATCH 084/576] Created cpp/README --- cpp/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 cpp/README.md diff --git a/cpp/README.md b/cpp/README.md new file mode 100644 index 00000000000..376a3731c30 --- /dev/null +++ b/cpp/README.md @@ -0,0 +1,8 @@ +#gRPC C++ Getting started + +First you need to install gRPC on your system. Follow the instructions here: +[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/INSTALL). + +After installing, you can proceed to the [gRPC C++ Hello World tutorial](https://github.com/grpc/grpc-common/cpp/helloworld). + +A more detailed tutorial is coming soon. From aa6c5fd7769cf2d398852153e9c89bbe5a0e0b4e Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Fri, 20 Feb 2015 15:41:55 -0800 Subject: [PATCH 085/576] Fixed broken link --- cpp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/README.md b/cpp/README.md index 376a3731c30..a95bd3c8f0e 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -1,7 +1,7 @@ #gRPC C++ Getting started First you need to install gRPC on your system. Follow the instructions here: -[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/INSTALL). +[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). After installing, you can proceed to the [gRPC C++ Hello World tutorial](https://github.com/grpc/grpc-common/cpp/helloworld). From 5621545e4c66fabec705284c6bfa86d0223bb0a8 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Fri, 20 Feb 2015 16:01:15 -0800 Subject: [PATCH 086/576] Finish of a dummy client/server pair --- cpp/route_guide/Makefile | 79 +- cpp/route_guide/route_guide.pb.cc | 1736 ------------------------- cpp/route_guide/route_guide.pb.h | 929 ------------- cpp/route_guide/route_guide_client.cc | 99 +- cpp/route_guide/route_guide_server.cc | 37 +- 5 files changed, 177 insertions(+), 2703 deletions(-) delete mode 100644 cpp/route_guide/route_guide.pb.cc delete mode 100644 cpp/route_guide/route_guide.pb.h diff --git a/cpp/route_guide/Makefile b/cpp/route_guide/Makefile index 444841f8b8d..fae9a9d284a 100644 --- a/cpp/route_guide/Makefile +++ b/cpp/route_guide/Makefile @@ -29,19 +29,82 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -CXX=g++ -CPPFLAGS=-I/usr/local/include -pthread -CXXFLAGS=-std=c++11 -LDFLAGS=-L/usr/local/lib -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl +CXX = g++ +CPPFLAGS = -I/usr/local/include -pthread +CXXFLAGS = -std=c++11 +LDFLAGS = -L/usr/local/lib -lgpr -lgrpc -lgrpc++ -lprotobuf -lpthread -ldl +PROTOC = protoc +GRPC_CPP_PLUGIN = grpc_cpp_plugin +GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)` -all: route_guide_client route_guide_server +PROTOS_PATH = ../../protos + +vpath %.proto $(PROTOS_PATH) + +all: system-check route_guide_client route_guide_server route_guide_client: route_guide.pb.o route_guide_client.o - $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ + $(CXX) $^ $(LDFLAGS) -o $@ route_guide_server: route_guide.pb.o route_guide_server.o - $(CXX) $(CPPFLAGS) $^ $(LDFLAGS) -o $@ + $(CXX) $^ $(LDFLAGS) -o $@ + +%.pb.cc: %.proto + $(PROTOC) -I $(PROTOS_PATH) --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $< clean: - rm -f *.o route_guide_client route_guide_server + rm -f *.o *.pb.cc *.pb.h route_guide_client route_guide_server + + +# The following is to test your system and ensure a smoother experience. +# They are by no means necessary to actually compile a grpc-enabled software. + +PROTOC_CMD = which $(PROTOC) +PROTOC_CHECK_CMD = $(PROTOC) --version | grep -q libprotoc.3 +PLUGIN_CHECK_CMD = which $(GRPC_CPP_PLUGIN) +HAS_PROTOC = $(shell $(PROTOC_CMD) > /dev/null && echo true || echo false) +ifeq ($(HAS_PROTOC),true) +HAS_VALID_PROTOC = $(shell $(PROTOC_CHECK_CMD) 2> /dev/null && echo true || echo false) +endif +HAS_PLUGIN = $(shell $(PLUGIN_CHECK_CMD) > /dev/null && echo true || echo false) + +SYSTEM_OK = false +ifeq ($(HAS_VALID_PROTOC),true) +ifeq ($(HAS_PLUGIN),true) +SYSTEM_OK = true +endif +endif +system-check: +ifneq ($(HAS_VALID_PROTOC),true) + @echo " DEPENDENCY ERROR" + @echo + @echo "You don't have protoc 3.0.0 installed in your path." + @echo "Please install Google protocol buffers 3.0.0 and its compiler." + @echo "You can find it here:" + @echo + @echo " https://github.com/google/protobuf/releases/tag/v3.0.0-alpha-1" + @echo + @echo "Here is what I get when trying to evaluate your version of protoc:" + @echo + -$(PROTOC) --version + @echo + @echo +endif +ifneq ($(HAS_PLUGIN),true) + @echo " DEPENDENCY ERROR" + @echo + @echo "You don't have the grpc c++ protobuf plugin installed in your path." + @echo "Please install grpc. You can find it here:" + @echo + @echo " https://github.com/grpc/grpc" + @echo + @echo "Here is what I get when trying to detect if you have the plugin:" + @echo + -which $(GRPC_CPP_PLUGIN) + @echo + @echo +endif +ifneq ($(SYSTEM_OK),true) + @false +endif diff --git a/cpp/route_guide/route_guide.pb.cc b/cpp/route_guide/route_guide.pb.cc deleted file mode 100644 index 6f4a1e70665..00000000000 --- a/cpp/route_guide/route_guide.pb.cc +++ /dev/null @@ -1,1736 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: route_guide.proto - -#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION -#include "route_guide.pb.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace examples { - -namespace { - -const ::google::protobuf::Descriptor* Point_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Point_reflection_ = NULL; -const ::google::protobuf::Descriptor* Rectangle_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Rectangle_reflection_ = NULL; -const ::google::protobuf::Descriptor* Feature_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Feature_reflection_ = NULL; -const ::google::protobuf::Descriptor* RouteNote_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - RouteNote_reflection_ = NULL; -const ::google::protobuf::Descriptor* RouteSummary_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - RouteSummary_reflection_ = NULL; - -} // namespace - - -void protobuf_AssignDesc_route_5fguide_2eproto() { - protobuf_AddDesc_route_5fguide_2eproto(); - const ::google::protobuf::FileDescriptor* file = - ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( - "route_guide.proto"); - GOOGLE_CHECK(file != NULL); - Point_descriptor_ = file->message_type(0); - static const int Point_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, latitude_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, longitude_), - }; - Point_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - Point_descriptor_, - Point::default_instance_, - Point_offsets_, - -1, - -1, - -1, - sizeof(Point), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _is_default_instance_)); - Rectangle_descriptor_ = file->message_type(1); - static const int Rectangle_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, lo_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, hi_), - }; - Rectangle_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - Rectangle_descriptor_, - Rectangle::default_instance_, - Rectangle_offsets_, - -1, - -1, - -1, - sizeof(Rectangle), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Rectangle, _is_default_instance_)); - Feature_descriptor_ = file->message_type(2); - static const int Feature_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, location_), - }; - Feature_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - Feature_descriptor_, - Feature::default_instance_, - Feature_offsets_, - -1, - -1, - -1, - sizeof(Feature), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Feature, _is_default_instance_)); - RouteNote_descriptor_ = file->message_type(3); - static const int RouteNote_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, location_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, message_), - }; - RouteNote_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - RouteNote_descriptor_, - RouteNote::default_instance_, - RouteNote_offsets_, - -1, - -1, - -1, - sizeof(RouteNote), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteNote, _is_default_instance_)); - RouteSummary_descriptor_ = file->message_type(4); - static const int RouteSummary_offsets_[4] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, point_count_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, feature_count_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, distance_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, elapsed_time_), - }; - RouteSummary_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - RouteSummary_descriptor_, - RouteSummary::default_instance_, - RouteSummary_offsets_, - -1, - -1, - -1, - sizeof(RouteSummary), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, _internal_metadata_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RouteSummary, _is_default_instance_)); -} - -namespace { - -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); -inline void protobuf_AssignDescriptorsOnce() { - ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, - &protobuf_AssignDesc_route_5fguide_2eproto); -} - -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Point_descriptor_, &Point::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Rectangle_descriptor_, &Rectangle::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Feature_descriptor_, &Feature::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - RouteNote_descriptor_, &RouteNote::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - RouteSummary_descriptor_, &RouteSummary::default_instance()); -} - -} // namespace - -void protobuf_ShutdownFile_route_5fguide_2eproto() { - delete Point::default_instance_; - delete Point_reflection_; - delete Rectangle::default_instance_; - delete Rectangle_reflection_; - delete Feature::default_instance_; - delete Feature_reflection_; - delete RouteNote::default_instance_; - delete RouteNote_reflection_; - delete RouteSummary::default_instance_; - delete RouteSummary_reflection_; -} - -void protobuf_AddDesc_route_5fguide_2eproto() { - static bool already_here = false; - if (already_here) return; - already_here = true; - GOOGLE_PROTOBUF_VERIFY_VERSION; - - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - "\n\021route_guide.proto\022\010examples\",\n\005Point\022\020" - "\n\010latitude\030\001 \001(\005\022\021\n\tlongitude\030\002 \001(\005\"E\n\tR" - "ectangle\022\033\n\002lo\030\001 \001(\0132\017.examples.Point\022\033\n" - "\002hi\030\002 \001(\0132\017.examples.Point\":\n\007Feature\022\014\n" - "\004name\030\001 \001(\t\022!\n\010location\030\002 \001(\0132\017.examples" - ".Point\"\?\n\tRouteNote\022!\n\010location\030\001 \001(\0132\017." - "examples.Point\022\017\n\007message\030\002 \001(\t\"b\n\014Route" - "Summary\022\023\n\013point_count\030\001 \001(\005\022\025\n\rfeature_" - "count\030\002 \001(\005\022\020\n\010distance\030\003 \001(\005\022\024\n\014elapsed" - "_time\030\004 \001(\0052\365\001\n\nRouteGuide\0222\n\nGetFeature" - "\022\017.examples.Point\032\021.examples.Feature\"\000\022:" - "\n\014ListFeatures\022\023.examples.Rectangle\032\021.ex" - "amples.Feature\"\0000\001\022:\n\013RecordRoute\022\017.exam" - "ples.Point\032\026.examples.RouteSummary\"\000(\001\022;" - "\n\tRouteChat\022\023.examples.RouteNote\032\023.examp" - "les.RouteNote\"\000(\0010\001B\t\n\007ex.grpcb\006proto3", 638); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "route_guide.proto", &protobuf_RegisterTypes); - Point::default_instance_ = new Point(); - Rectangle::default_instance_ = new Rectangle(); - Feature::default_instance_ = new Feature(); - RouteNote::default_instance_ = new RouteNote(); - RouteSummary::default_instance_ = new RouteSummary(); - Point::default_instance_->InitAsDefaultInstance(); - Rectangle::default_instance_->InitAsDefaultInstance(); - Feature::default_instance_->InitAsDefaultInstance(); - RouteNote::default_instance_->InitAsDefaultInstance(); - RouteSummary::default_instance_->InitAsDefaultInstance(); - ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_route_5fguide_2eproto); -} - -// Force AddDescriptors() to be called at static initialization time. -struct StaticDescriptorInitializer_route_5fguide_2eproto { - StaticDescriptorInitializer_route_5fguide_2eproto() { - protobuf_AddDesc_route_5fguide_2eproto(); - } -} static_descriptor_initializer_route_5fguide_2eproto_; - -namespace { - -static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD; -static void MergeFromFail(int line) { - GOOGLE_CHECK(false) << __FILE__ << ":" << line; -} - -} // namespace - - -// =================================================================== - -#ifndef _MSC_VER -const int Point::kLatitudeFieldNumber; -const int Point::kLongitudeFieldNumber; -#endif // !_MSC_VER - -Point::Point() - : ::google::protobuf::Message() , _internal_metadata_(NULL) { - SharedCtor(); - // @@protoc_insertion_point(constructor:examples.Point) -} - -void Point::InitAsDefaultInstance() { - _is_default_instance_ = true; -} - -Point::Point(const Point& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:examples.Point) -} - -void Point::SharedCtor() { - _is_default_instance_ = false; - _cached_size_ = 0; - latitude_ = 0; - longitude_ = 0; -} - -Point::~Point() { - // @@protoc_insertion_point(destructor:examples.Point) - SharedDtor(); -} - -void Point::SharedDtor() { - if (this != default_instance_) { - } -} - -void Point::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Point::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Point_descriptor_; -} - -const Point& Point::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); - return *default_instance_; -} - -Point* Point::default_instance_ = NULL; - -Point* Point::New(::google::protobuf::Arena* arena) const { - Point* n = new Point; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void Point::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(latitude_, longitude_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - -} - -bool Point::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:examples.Point) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional int32 latitude = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &latitude_))); - - } else { - goto handle_unusual; - } - if (input->ExpectTag(16)) goto parse_longitude; - break; - } - - // optional int32 longitude = 2; - case 2: { - if (tag == 16) { - parse_longitude: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &longitude_))); - - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:examples.Point) - return true; -failure: - // @@protoc_insertion_point(parse_failure:examples.Point) - return false; -#undef DO_ -} - -void Point::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:examples.Point) - // optional int32 latitude = 1; - if (this->latitude() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->latitude(), output); - } - - // optional int32 longitude = 2; - if (this->longitude() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->longitude(), output); - } - - // @@protoc_insertion_point(serialize_end:examples.Point) -} - -::google::protobuf::uint8* Point::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:examples.Point) - // optional int32 latitude = 1; - if (this->latitude() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->latitude(), target); - } - - // optional int32 longitude = 2; - if (this->longitude() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->longitude(), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:examples.Point) - return target; -} - -int Point::ByteSize() const { - int total_size = 0; - - // optional int32 latitude = 1; - if (this->latitude() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->latitude()); - } - - // optional int32 longitude = 2; - if (this->longitude() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->longitude()); - } - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Point::MergeFrom(const ::google::protobuf::Message& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const Point* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Point::MergeFrom(const Point& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - if (from.latitude() != 0) { - set_latitude(from.latitude()); - } - if (from.longitude() != 0) { - set_longitude(from.longitude()); - } -} - -void Point::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Point::CopyFrom(const Point& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Point::IsInitialized() const { - - return true; -} - -void Point::Swap(Point* other) { - if (other == this) return; - InternalSwap(other); -} -void Point::InternalSwap(Point* other) { - std::swap(latitude_, other->latitude_); - std::swap(longitude_, other->longitude_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata Point::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Point_descriptor_; - metadata.reflection = Point_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Rectangle::kLoFieldNumber; -const int Rectangle::kHiFieldNumber; -#endif // !_MSC_VER - -Rectangle::Rectangle() - : ::google::protobuf::Message() , _internal_metadata_(NULL) { - SharedCtor(); - // @@protoc_insertion_point(constructor:examples.Rectangle) -} - -void Rectangle::InitAsDefaultInstance() { - _is_default_instance_ = true; - lo_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); - hi_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); -} - -Rectangle::Rectangle(const Rectangle& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:examples.Rectangle) -} - -void Rectangle::SharedCtor() { - _is_default_instance_ = false; - _cached_size_ = 0; - lo_ = NULL; - hi_ = NULL; -} - -Rectangle::~Rectangle() { - // @@protoc_insertion_point(destructor:examples.Rectangle) - SharedDtor(); -} - -void Rectangle::SharedDtor() { - if (this != default_instance_) { - delete lo_; - delete hi_; - } -} - -void Rectangle::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Rectangle::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Rectangle_descriptor_; -} - -const Rectangle& Rectangle::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); - return *default_instance_; -} - -Rectangle* Rectangle::default_instance_ = NULL; - -Rectangle* Rectangle::New(::google::protobuf::Arena* arena) const { - Rectangle* n = new Rectangle; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void Rectangle::Clear() { - if (lo_ != NULL) delete lo_; - lo_ = NULL; - if (hi_ != NULL) delete hi_; - hi_ = NULL; -} - -bool Rectangle::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:examples.Rectangle) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional .examples.Point lo = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_lo())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_hi; - break; - } - - // optional .examples.Point hi = 2; - case 2: { - if (tag == 18) { - parse_hi: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_hi())); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:examples.Rectangle) - return true; -failure: - // @@protoc_insertion_point(parse_failure:examples.Rectangle) - return false; -#undef DO_ -} - -void Rectangle::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:examples.Rectangle) - // optional .examples.Point lo = 1; - if (this->has_lo()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 1, *this->lo_, output); - } - - // optional .examples.Point hi = 2; - if (this->has_hi()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, *this->hi_, output); - } - - // @@protoc_insertion_point(serialize_end:examples.Rectangle) -} - -::google::protobuf::uint8* Rectangle::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:examples.Rectangle) - // optional .examples.Point lo = 1; - if (this->has_lo()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 1, *this->lo_, target); - } - - // optional .examples.Point hi = 2; - if (this->has_hi()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 2, *this->hi_, target); - } - - // @@protoc_insertion_point(serialize_to_array_end:examples.Rectangle) - return target; -} - -int Rectangle::ByteSize() const { - int total_size = 0; - - // optional .examples.Point lo = 1; - if (this->has_lo()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *this->lo_); - } - - // optional .examples.Point hi = 2; - if (this->has_hi()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *this->hi_); - } - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Rectangle::MergeFrom(const ::google::protobuf::Message& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const Rectangle* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Rectangle::MergeFrom(const Rectangle& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - if (from.has_lo()) { - mutable_lo()->::examples::Point::MergeFrom(from.lo()); - } - if (from.has_hi()) { - mutable_hi()->::examples::Point::MergeFrom(from.hi()); - } -} - -void Rectangle::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Rectangle::CopyFrom(const Rectangle& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Rectangle::IsInitialized() const { - - return true; -} - -void Rectangle::Swap(Rectangle* other) { - if (other == this) return; - InternalSwap(other); -} -void Rectangle::InternalSwap(Rectangle* other) { - std::swap(lo_, other->lo_); - std::swap(hi_, other->hi_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata Rectangle::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Rectangle_descriptor_; - metadata.reflection = Rectangle_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Feature::kNameFieldNumber; -const int Feature::kLocationFieldNumber; -#endif // !_MSC_VER - -Feature::Feature() - : ::google::protobuf::Message() , _internal_metadata_(NULL) { - SharedCtor(); - // @@protoc_insertion_point(constructor:examples.Feature) -} - -void Feature::InitAsDefaultInstance() { - _is_default_instance_ = true; - location_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); -} - -Feature::Feature(const Feature& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:examples.Feature) -} - -void Feature::SharedCtor() { - _is_default_instance_ = false; - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - location_ = NULL; -} - -Feature::~Feature() { - // @@protoc_insertion_point(destructor:examples.Feature) - SharedDtor(); -} - -void Feature::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (this != default_instance_) { - delete location_; - } -} - -void Feature::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Feature::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Feature_descriptor_; -} - -const Feature& Feature::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); - return *default_instance_; -} - -Feature* Feature::default_instance_ = NULL; - -Feature* Feature::New(::google::protobuf::Arena* arena) const { - Feature* n = new Feature; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void Feature::Clear() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (location_ != NULL) delete location_; - location_ = NULL; -} - -bool Feature::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:examples.Feature) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE, - "examples.Feature.name"); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_location; - break; - } - - // optional .examples.Point location = 2; - case 2: { - if (tag == 18) { - parse_location: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_location())); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:examples.Feature) - return true; -failure: - // @@protoc_insertion_point(parse_failure:examples.Feature) - return false; -#undef DO_ -} - -void Feature::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:examples.Feature) - // optional string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "examples.Feature.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // optional .examples.Point location = 2; - if (this->has_location()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, *this->location_, output); - } - - // @@protoc_insertion_point(serialize_end:examples.Feature) -} - -::google::protobuf::uint8* Feature::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:examples.Feature) - // optional string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "examples.Feature.name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional .examples.Point location = 2; - if (this->has_location()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 2, *this->location_, target); - } - - // @@protoc_insertion_point(serialize_to_array_end:examples.Feature) - return target; -} - -int Feature::ByteSize() const { - int total_size = 0; - - // optional string name = 1; - if (this->name().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional .examples.Point location = 2; - if (this->has_location()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *this->location_); - } - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Feature::MergeFrom(const ::google::protobuf::Message& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const Feature* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Feature::MergeFrom(const Feature& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - if (from.name().size() > 0) { - - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - if (from.has_location()) { - mutable_location()->::examples::Point::MergeFrom(from.location()); - } -} - -void Feature::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Feature::CopyFrom(const Feature& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Feature::IsInitialized() const { - - return true; -} - -void Feature::Swap(Feature* other) { - if (other == this) return; - InternalSwap(other); -} -void Feature::InternalSwap(Feature* other) { - name_.Swap(&other->name_); - std::swap(location_, other->location_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata Feature::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Feature_descriptor_; - metadata.reflection = Feature_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int RouteNote::kLocationFieldNumber; -const int RouteNote::kMessageFieldNumber; -#endif // !_MSC_VER - -RouteNote::RouteNote() - : ::google::protobuf::Message() , _internal_metadata_(NULL) { - SharedCtor(); - // @@protoc_insertion_point(constructor:examples.RouteNote) -} - -void RouteNote::InitAsDefaultInstance() { - _is_default_instance_ = true; - location_ = const_cast< ::examples::Point*>(&::examples::Point::default_instance()); -} - -RouteNote::RouteNote(const RouteNote& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:examples.RouteNote) -} - -void RouteNote::SharedCtor() { - _is_default_instance_ = false; - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - location_ = NULL; - message_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -RouteNote::~RouteNote() { - // @@protoc_insertion_point(destructor:examples.RouteNote) - SharedDtor(); -} - -void RouteNote::SharedDtor() { - message_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (this != default_instance_) { - delete location_; - } -} - -void RouteNote::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* RouteNote::descriptor() { - protobuf_AssignDescriptorsOnce(); - return RouteNote_descriptor_; -} - -const RouteNote& RouteNote::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); - return *default_instance_; -} - -RouteNote* RouteNote::default_instance_ = NULL; - -RouteNote* RouteNote::New(::google::protobuf::Arena* arena) const { - RouteNote* n = new RouteNote; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void RouteNote::Clear() { - if (location_ != NULL) delete location_; - location_ = NULL; - message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -bool RouteNote::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:examples.RouteNote) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional .examples.Point location = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_location())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_message; - break; - } - - // optional string message = 2; - case 2: { - if (tag == 18) { - parse_message: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_message())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->message().data(), this->message().length(), - ::google::protobuf::internal::WireFormat::PARSE, - "examples.RouteNote.message"); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:examples.RouteNote) - return true; -failure: - // @@protoc_insertion_point(parse_failure:examples.RouteNote) - return false; -#undef DO_ -} - -void RouteNote::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:examples.RouteNote) - // optional .examples.Point location = 1; - if (this->has_location()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 1, *this->location_, output); - } - - // optional string message = 2; - if (this->message().size() > 0) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->message().data(), this->message().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "examples.RouteNote.message"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->message(), output); - } - - // @@protoc_insertion_point(serialize_end:examples.RouteNote) -} - -::google::protobuf::uint8* RouteNote::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:examples.RouteNote) - // optional .examples.Point location = 1; - if (this->has_location()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 1, *this->location_, target); - } - - // optional string message = 2; - if (this->message().size() > 0) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->message().data(), this->message().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "examples.RouteNote.message"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->message(), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:examples.RouteNote) - return target; -} - -int RouteNote::ByteSize() const { - int total_size = 0; - - // optional .examples.Point location = 1; - if (this->has_location()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *this->location_); - } - - // optional string message = 2; - if (this->message().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->message()); - } - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void RouteNote::MergeFrom(const ::google::protobuf::Message& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const RouteNote* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void RouteNote::MergeFrom(const RouteNote& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - if (from.has_location()) { - mutable_location()->::examples::Point::MergeFrom(from.location()); - } - if (from.message().size() > 0) { - - message_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.message_); - } -} - -void RouteNote::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void RouteNote::CopyFrom(const RouteNote& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool RouteNote::IsInitialized() const { - - return true; -} - -void RouteNote::Swap(RouteNote* other) { - if (other == this) return; - InternalSwap(other); -} -void RouteNote::InternalSwap(RouteNote* other) { - std::swap(location_, other->location_); - message_.Swap(&other->message_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata RouteNote::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = RouteNote_descriptor_; - metadata.reflection = RouteNote_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int RouteSummary::kPointCountFieldNumber; -const int RouteSummary::kFeatureCountFieldNumber; -const int RouteSummary::kDistanceFieldNumber; -const int RouteSummary::kElapsedTimeFieldNumber; -#endif // !_MSC_VER - -RouteSummary::RouteSummary() - : ::google::protobuf::Message() , _internal_metadata_(NULL) { - SharedCtor(); - // @@protoc_insertion_point(constructor:examples.RouteSummary) -} - -void RouteSummary::InitAsDefaultInstance() { - _is_default_instance_ = true; -} - -RouteSummary::RouteSummary(const RouteSummary& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:examples.RouteSummary) -} - -void RouteSummary::SharedCtor() { - _is_default_instance_ = false; - _cached_size_ = 0; - point_count_ = 0; - feature_count_ = 0; - distance_ = 0; - elapsed_time_ = 0; -} - -RouteSummary::~RouteSummary() { - // @@protoc_insertion_point(destructor:examples.RouteSummary) - SharedDtor(); -} - -void RouteSummary::SharedDtor() { - if (this != default_instance_) { - } -} - -void RouteSummary::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* RouteSummary::descriptor() { - protobuf_AssignDescriptorsOnce(); - return RouteSummary_descriptor_; -} - -const RouteSummary& RouteSummary::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_route_5fguide_2eproto(); - return *default_instance_; -} - -RouteSummary* RouteSummary::default_instance_ = NULL; - -RouteSummary* RouteSummary::New(::google::protobuf::Arena* arena) const { - RouteSummary* n = new RouteSummary; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void RouteSummary::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(point_count_, elapsed_time_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - -} - -bool RouteSummary::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:examples.RouteSummary) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional int32 point_count = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &point_count_))); - - } else { - goto handle_unusual; - } - if (input->ExpectTag(16)) goto parse_feature_count; - break; - } - - // optional int32 feature_count = 2; - case 2: { - if (tag == 16) { - parse_feature_count: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &feature_count_))); - - } else { - goto handle_unusual; - } - if (input->ExpectTag(24)) goto parse_distance; - break; - } - - // optional int32 distance = 3; - case 3: { - if (tag == 24) { - parse_distance: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &distance_))); - - } else { - goto handle_unusual; - } - if (input->ExpectTag(32)) goto parse_elapsed_time; - break; - } - - // optional int32 elapsed_time = 4; - case 4: { - if (tag == 32) { - parse_elapsed_time: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &elapsed_time_))); - - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:examples.RouteSummary) - return true; -failure: - // @@protoc_insertion_point(parse_failure:examples.RouteSummary) - return false; -#undef DO_ -} - -void RouteSummary::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:examples.RouteSummary) - // optional int32 point_count = 1; - if (this->point_count() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->point_count(), output); - } - - // optional int32 feature_count = 2; - if (this->feature_count() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->feature_count(), output); - } - - // optional int32 distance = 3; - if (this->distance() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->distance(), output); - } - - // optional int32 elapsed_time = 4; - if (this->elapsed_time() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->elapsed_time(), output); - } - - // @@protoc_insertion_point(serialize_end:examples.RouteSummary) -} - -::google::protobuf::uint8* RouteSummary::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:examples.RouteSummary) - // optional int32 point_count = 1; - if (this->point_count() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->point_count(), target); - } - - // optional int32 feature_count = 2; - if (this->feature_count() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->feature_count(), target); - } - - // optional int32 distance = 3; - if (this->distance() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->distance(), target); - } - - // optional int32 elapsed_time = 4; - if (this->elapsed_time() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->elapsed_time(), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:examples.RouteSummary) - return target; -} - -int RouteSummary::ByteSize() const { - int total_size = 0; - - // optional int32 point_count = 1; - if (this->point_count() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->point_count()); - } - - // optional int32 feature_count = 2; - if (this->feature_count() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->feature_count()); - } - - // optional int32 distance = 3; - if (this->distance() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->distance()); - } - - // optional int32 elapsed_time = 4; - if (this->elapsed_time() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->elapsed_time()); - } - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void RouteSummary::MergeFrom(const ::google::protobuf::Message& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const RouteSummary* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void RouteSummary::MergeFrom(const RouteSummary& from) { - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - if (from.point_count() != 0) { - set_point_count(from.point_count()); - } - if (from.feature_count() != 0) { - set_feature_count(from.feature_count()); - } - if (from.distance() != 0) { - set_distance(from.distance()); - } - if (from.elapsed_time() != 0) { - set_elapsed_time(from.elapsed_time()); - } -} - -void RouteSummary::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void RouteSummary::CopyFrom(const RouteSummary& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool RouteSummary::IsInitialized() const { - - return true; -} - -void RouteSummary::Swap(RouteSummary* other) { - if (other == this) return; - InternalSwap(other); -} -void RouteSummary::InternalSwap(RouteSummary* other) { - std::swap(point_count_, other->point_count_); - std::swap(feature_count_, other->feature_count_); - std::swap(distance_, other->distance_); - std::swap(elapsed_time_, other->elapsed_time_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata RouteSummary::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = RouteSummary_descriptor_; - metadata.reflection = RouteSummary_reflection_; - return metadata; -} - - -static const char* RouteGuide_method_names[] = { - "/examples.RouteGuide/GetFeature", - "/examples.RouteGuide/ListFeatures", - "/examples.RouteGuide/RecordRoute", - "/examples.RouteGuide/RouteChat", -}; - -RouteGuide::Stub* RouteGuide::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) { - RouteGuide::Stub* stub = new RouteGuide::Stub(); - stub->set_channel(channel); - return stub; -}; - -::grpc::Status RouteGuide::Stub::GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::examples::Feature* response) { - return ::grpc::BlockingUnaryCall(channel(),::grpc::RpcMethod(RouteGuide_method_names[0]), context, request, response); -} - -::grpc::ClientAsyncResponseReader< ::examples::Feature>* RouteGuide::Stub::GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::grpc::CompletionQueue* cq, void* tag) { - return new ::grpc::ClientAsyncResponseReader< ::examples::Feature>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[0]), context, request, tag); -} - -::grpc::ClientReader< ::examples::Feature>* RouteGuide::Stub::ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request) { - return new ::grpc::ClientReader< ::examples::Feature>(channel(),::grpc::RpcMethod(RouteGuide_method_names[1], ::grpc::RpcMethod::RpcType::SERVER_STREAMING), context, request); -} - -::grpc::ClientAsyncReader< ::examples::Feature>* RouteGuide::Stub::ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request, ::grpc::CompletionQueue* cq, void* tag) { - return new ::grpc::ClientAsyncReader< ::examples::Feature>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[1], ::grpc::RpcMethod::RpcType::SERVER_STREAMING), context, request, tag); -} - -::grpc::ClientWriter< ::examples::Point>* RouteGuide::Stub::RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response) { - return new ::grpc::ClientWriter< ::examples::Point>(channel(),::grpc::RpcMethod(RouteGuide_method_names[2], ::grpc::RpcMethod::RpcType::CLIENT_STREAMING), context, response); -} - -::grpc::ClientAsyncWriter< ::examples::Point>* RouteGuide::Stub::RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response, ::grpc::CompletionQueue* cq, void* tag) { - return new ::grpc::ClientAsyncWriter< ::examples::Point>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[2], ::grpc::RpcMethod::RpcType::CLIENT_STREAMING), context, response, tag); -} - -::grpc::ClientReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteGuide::Stub::RouteChat(::grpc::ClientContext* context) { - return new ::grpc::ClientReaderWriter< ::examples::RouteNote, ::examples::RouteNote>(channel(),::grpc::RpcMethod(RouteGuide_method_names[3], ::grpc::RpcMethod::RpcType::BIDI_STREAMING), context); -} - -::grpc::ClientAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteGuide::Stub::RouteChat(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { - return new ::grpc::ClientAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>(channel(), cq, ::grpc::RpcMethod(RouteGuide_method_names[3], ::grpc::RpcMethod::RpcType::BIDI_STREAMING), context, tag); -} - -RouteGuide::AsyncService::AsyncService(::grpc::CompletionQueue* cq) : ::grpc::AsynchronousService(cq, RouteGuide_method_names, 4) {} - -RouteGuide::Service::~Service() { - delete service_; -} - -::grpc::Status RouteGuide::Service::GetFeature(::grpc::ServerContext* context, const ::examples::Point* request, ::examples::Feature* response) { - return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); -} - -void RouteGuide::AsyncService::RequestGetFeature(::grpc::ServerContext* context, ::examples::Point* request, ::grpc::ServerAsyncResponseWriter< ::examples::Feature>* response, ::grpc::CompletionQueue* cq, void* tag) { - AsynchronousService::RequestAsyncUnary(0, context, request, response, cq, tag); -} - -::grpc::Status RouteGuide::Service::ListFeatures(::grpc::ServerContext* context, const ::examples::Rectangle* request, ::grpc::ServerWriter< ::examples::Feature>* writer) { - return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); -} - -void RouteGuide::AsyncService::RequestListFeatures(::grpc::ServerContext* context, ::examples::Rectangle* request, ::grpc::ServerAsyncWriter< ::examples::Feature>* writer, ::grpc::CompletionQueue* cq, void* tag) { - AsynchronousService::RequestServerStreaming(1, context, request, writer, cq, tag); -} - -::grpc::Status RouteGuide::Service::RecordRoute(::grpc::ServerContext* context, ::grpc::ServerReader< ::examples::Point>* reader, ::examples::RouteSummary* response) { - return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); -} - -void RouteGuide::AsyncService::RequestRecordRoute(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< ::examples::RouteSummary, ::examples::Point>* reader, ::grpc::CompletionQueue* cq, void* tag) { - AsynchronousService::RequestClientStreaming(2, context, reader, cq, tag); -} - -::grpc::Status RouteGuide::Service::RouteChat(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream) { - return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED); -} - -void RouteGuide::AsyncService::RequestRouteChat(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream, ::grpc::CompletionQueue* cq, void *tag) { - AsynchronousService::RequestBidiStreaming(3, context, stream, cq, tag); -} - -::grpc::RpcService* RouteGuide::Service::service() { - if (service_ != nullptr) { - return service_; - } - service_ = new ::grpc::RpcService(); - service_->AddMethod(new ::grpc::RpcServiceMethod( - RouteGuide_method_names[0], - ::grpc::RpcMethod::NORMAL_RPC, - new ::grpc::RpcMethodHandler< RouteGuide::Service, ::examples::Point, ::examples::Feature>( - std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, const ::examples::Point*, ::examples::Feature*)>(&RouteGuide::Service::GetFeature), this), - new ::examples::Point, new ::examples::Feature)); - service_->AddMethod(new ::grpc::RpcServiceMethod( - RouteGuide_method_names[1], - ::grpc::RpcMethod::SERVER_STREAMING, - new ::grpc::ServerStreamingHandler< RouteGuide::Service, ::examples::Rectangle, ::examples::Feature>( - std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, const ::examples::Rectangle*, ::grpc::ServerWriter< ::examples::Feature>*)>(&RouteGuide::Service::ListFeatures), this), - new ::examples::Rectangle, new ::examples::Feature)); - service_->AddMethod(new ::grpc::RpcServiceMethod( - RouteGuide_method_names[2], - ::grpc::RpcMethod::CLIENT_STREAMING, - new ::grpc::ClientStreamingHandler< RouteGuide::Service, ::examples::Point, ::examples::RouteSummary>( - std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, ::grpc::ServerReader< ::examples::Point>*, ::examples::RouteSummary*)>(&RouteGuide::Service::RecordRoute), this), - new ::examples::Point, new ::examples::RouteSummary)); - service_->AddMethod(new ::grpc::RpcServiceMethod( - RouteGuide_method_names[3], - ::grpc::RpcMethod::BIDI_STREAMING, - new ::grpc::BidiStreamingHandler< RouteGuide::Service, ::examples::RouteNote, ::examples::RouteNote>( - std::function< ::grpc::Status(RouteGuide::Service*, ::grpc::ServerContext*, ::grpc::ServerReaderWriter< ::examples::RouteNote, ::examples::RouteNote>*)>(&RouteGuide::Service::RouteChat), this), - new ::examples::RouteNote, new ::examples::RouteNote)); - return service_; -} - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace examples - -// @@protoc_insertion_point(global_scope) diff --git a/cpp/route_guide/route_guide.pb.h b/cpp/route_guide/route_guide.pb.h deleted file mode 100644 index 7689003f0a9..00000000000 --- a/cpp/route_guide/route_guide.pb.h +++ /dev/null @@ -1,929 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: route_guide.proto - -#ifndef PROTOBUF_route_5fguide_2eproto__INCLUDED -#define PROTOBUF_route_5fguide_2eproto__INCLUDED - -#include - -#include - -#if GOOGLE_PROTOBUF_VERSION < 3000000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace grpc { -class CompletionQueue; -class ChannelInterface; -class RpcService; -class ServerContext; -template class ClientAsyncResponseReader; -template class ServerAsyncResponseWriter; -template class ClientWriter; -template class ServerReader; -template class ClientAsyncWriter; -template class ServerAsyncReader; -template class ClientReader; -template class ServerWriter; -template class ClientAsyncReader; -template class ServerAsyncWriter; -template -class ClientReaderWriter; -template -class ServerReaderWriter; -template -class ClientAsyncReaderWriter; -template -class ServerAsyncReaderWriter; -} // namespace grpc -// @@protoc_insertion_point(includes) - -namespace examples { - -// Internal implementation detail -- do not call these. -void protobuf_AddDesc_route_5fguide_2eproto(); -void protobuf_AssignDesc_route_5fguide_2eproto(); -void protobuf_ShutdownFile_route_5fguide_2eproto(); - -class Point; -class Rectangle; -class Feature; -class RouteNote; -class RouteSummary; - -// =================================================================== - -class Point : public ::google::protobuf::Message { - public: - Point(); - virtual ~Point(); - - Point(const Point& from); - - inline Point& operator=(const Point& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Point& default_instance(); - - void Swap(Point* other); - - // implements Message ---------------------------------------------- - - inline Point* New() const { return New(NULL); } - - Point* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Point& from); - void MergeFrom(const Point& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(Point* other); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional int32 latitude = 1; - inline void clear_latitude(); - static const int kLatitudeFieldNumber = 1; - inline ::google::protobuf::int32 latitude() const; - inline void set_latitude(::google::protobuf::int32 value); - - // optional int32 longitude = 2; - inline void clear_longitude(); - static const int kLongitudeFieldNumber = 2; - inline ::google::protobuf::int32 longitude() const; - inline void set_longitude(::google::protobuf::int32 value); - - // @@protoc_insertion_point(class_scope:examples.Point) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - bool _is_default_instance_; - ::google::protobuf::int32 latitude_; - ::google::protobuf::int32 longitude_; - mutable int _cached_size_; - friend void protobuf_AddDesc_route_5fguide_2eproto(); - friend void protobuf_AssignDesc_route_5fguide_2eproto(); - friend void protobuf_ShutdownFile_route_5fguide_2eproto(); - - void InitAsDefaultInstance(); - static Point* default_instance_; -}; -// ------------------------------------------------------------------- - -class Rectangle : public ::google::protobuf::Message { - public: - Rectangle(); - virtual ~Rectangle(); - - Rectangle(const Rectangle& from); - - inline Rectangle& operator=(const Rectangle& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Rectangle& default_instance(); - - void Swap(Rectangle* other); - - // implements Message ---------------------------------------------- - - inline Rectangle* New() const { return New(NULL); } - - Rectangle* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Rectangle& from); - void MergeFrom(const Rectangle& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(Rectangle* other); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional .examples.Point lo = 1; - inline bool has_lo() const; - inline void clear_lo(); - static const int kLoFieldNumber = 1; - inline const ::examples::Point& lo() const; - inline ::examples::Point* mutable_lo(); - inline ::examples::Point* release_lo(); - inline void set_allocated_lo(::examples::Point* lo); - - // optional .examples.Point hi = 2; - inline bool has_hi() const; - inline void clear_hi(); - static const int kHiFieldNumber = 2; - inline const ::examples::Point& hi() const; - inline ::examples::Point* mutable_hi(); - inline ::examples::Point* release_hi(); - inline void set_allocated_hi(::examples::Point* hi); - - // @@protoc_insertion_point(class_scope:examples.Rectangle) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - bool _is_default_instance_; - ::examples::Point* lo_; - ::examples::Point* hi_; - mutable int _cached_size_; - friend void protobuf_AddDesc_route_5fguide_2eproto(); - friend void protobuf_AssignDesc_route_5fguide_2eproto(); - friend void protobuf_ShutdownFile_route_5fguide_2eproto(); - - void InitAsDefaultInstance(); - static Rectangle* default_instance_; -}; -// ------------------------------------------------------------------- - -class Feature : public ::google::protobuf::Message { - public: - Feature(); - virtual ~Feature(); - - Feature(const Feature& from); - - inline Feature& operator=(const Feature& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Feature& default_instance(); - - void Swap(Feature* other); - - // implements Message ---------------------------------------------- - - inline Feature* New() const { return New(NULL); } - - Feature* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Feature& from); - void MergeFrom(const Feature& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(Feature* other); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - inline ::std::string* release_name(); - inline void set_allocated_name(::std::string* name); - - // optional .examples.Point location = 2; - inline bool has_location() const; - inline void clear_location(); - static const int kLocationFieldNumber = 2; - inline const ::examples::Point& location() const; - inline ::examples::Point* mutable_location(); - inline ::examples::Point* release_location(); - inline void set_allocated_location(::examples::Point* location); - - // @@protoc_insertion_point(class_scope:examples.Feature) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - bool _is_default_instance_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::examples::Point* location_; - mutable int _cached_size_; - friend void protobuf_AddDesc_route_5fguide_2eproto(); - friend void protobuf_AssignDesc_route_5fguide_2eproto(); - friend void protobuf_ShutdownFile_route_5fguide_2eproto(); - - void InitAsDefaultInstance(); - static Feature* default_instance_; -}; -// ------------------------------------------------------------------- - -class RouteNote : public ::google::protobuf::Message { - public: - RouteNote(); - virtual ~RouteNote(); - - RouteNote(const RouteNote& from); - - inline RouteNote& operator=(const RouteNote& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const RouteNote& default_instance(); - - void Swap(RouteNote* other); - - // implements Message ---------------------------------------------- - - inline RouteNote* New() const { return New(NULL); } - - RouteNote* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const RouteNote& from); - void MergeFrom(const RouteNote& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(RouteNote* other); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional .examples.Point location = 1; - inline bool has_location() const; - inline void clear_location(); - static const int kLocationFieldNumber = 1; - inline const ::examples::Point& location() const; - inline ::examples::Point* mutable_location(); - inline ::examples::Point* release_location(); - inline void set_allocated_location(::examples::Point* location); - - // optional string message = 2; - inline void clear_message(); - static const int kMessageFieldNumber = 2; - inline const ::std::string& message() const; - inline void set_message(const ::std::string& value); - inline void set_message(const char* value); - inline void set_message(const char* value, size_t size); - inline ::std::string* mutable_message(); - inline ::std::string* release_message(); - inline void set_allocated_message(::std::string* message); - - // @@protoc_insertion_point(class_scope:examples.RouteNote) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - bool _is_default_instance_; - ::examples::Point* location_; - ::google::protobuf::internal::ArenaStringPtr message_; - mutable int _cached_size_; - friend void protobuf_AddDesc_route_5fguide_2eproto(); - friend void protobuf_AssignDesc_route_5fguide_2eproto(); - friend void protobuf_ShutdownFile_route_5fguide_2eproto(); - - void InitAsDefaultInstance(); - static RouteNote* default_instance_; -}; -// ------------------------------------------------------------------- - -class RouteSummary : public ::google::protobuf::Message { - public: - RouteSummary(); - virtual ~RouteSummary(); - - RouteSummary(const RouteSummary& from); - - inline RouteSummary& operator=(const RouteSummary& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const RouteSummary& default_instance(); - - void Swap(RouteSummary* other); - - // implements Message ---------------------------------------------- - - inline RouteSummary* New() const { return New(NULL); } - - RouteSummary* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const RouteSummary& from); - void MergeFrom(const RouteSummary& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(RouteSummary* other); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional int32 point_count = 1; - inline void clear_point_count(); - static const int kPointCountFieldNumber = 1; - inline ::google::protobuf::int32 point_count() const; - inline void set_point_count(::google::protobuf::int32 value); - - // optional int32 feature_count = 2; - inline void clear_feature_count(); - static const int kFeatureCountFieldNumber = 2; - inline ::google::protobuf::int32 feature_count() const; - inline void set_feature_count(::google::protobuf::int32 value); - - // optional int32 distance = 3; - inline void clear_distance(); - static const int kDistanceFieldNumber = 3; - inline ::google::protobuf::int32 distance() const; - inline void set_distance(::google::protobuf::int32 value); - - // optional int32 elapsed_time = 4; - inline void clear_elapsed_time(); - static const int kElapsedTimeFieldNumber = 4; - inline ::google::protobuf::int32 elapsed_time() const; - inline void set_elapsed_time(::google::protobuf::int32 value); - - // @@protoc_insertion_point(class_scope:examples.RouteSummary) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - bool _is_default_instance_; - ::google::protobuf::int32 point_count_; - ::google::protobuf::int32 feature_count_; - ::google::protobuf::int32 distance_; - ::google::protobuf::int32 elapsed_time_; - mutable int _cached_size_; - friend void protobuf_AddDesc_route_5fguide_2eproto(); - friend void protobuf_AssignDesc_route_5fguide_2eproto(); - friend void protobuf_ShutdownFile_route_5fguide_2eproto(); - - void InitAsDefaultInstance(); - static RouteSummary* default_instance_; -}; -// =================================================================== - - -// =================================================================== - -// Point - -// optional int32 latitude = 1; -inline void Point::clear_latitude() { - latitude_ = 0; -} -inline ::google::protobuf::int32 Point::latitude() const { - // @@protoc_insertion_point(field_get:examples.Point.latitude) - return latitude_; -} -inline void Point::set_latitude(::google::protobuf::int32 value) { - - latitude_ = value; - // @@protoc_insertion_point(field_set:examples.Point.latitude) -} - -// optional int32 longitude = 2; -inline void Point::clear_longitude() { - longitude_ = 0; -} -inline ::google::protobuf::int32 Point::longitude() const { - // @@protoc_insertion_point(field_get:examples.Point.longitude) - return longitude_; -} -inline void Point::set_longitude(::google::protobuf::int32 value) { - - longitude_ = value; - // @@protoc_insertion_point(field_set:examples.Point.longitude) -} - -// ------------------------------------------------------------------- - -// Rectangle - -// optional .examples.Point lo = 1; -inline bool Rectangle::has_lo() const { - return !_is_default_instance_ && lo_ != NULL; -} -inline void Rectangle::clear_lo() { - if (lo_ != NULL) delete lo_; - lo_ = NULL; -} -inline const ::examples::Point& Rectangle::lo() const { - // @@protoc_insertion_point(field_get:examples.Rectangle.lo) - return lo_ != NULL ? *lo_ : *default_instance_->lo_; -} -inline ::examples::Point* Rectangle::mutable_lo() { - - if (lo_ == NULL) { - lo_ = new ::examples::Point; - } - // @@protoc_insertion_point(field_mutable:examples.Rectangle.lo) - return lo_; -} -inline ::examples::Point* Rectangle::release_lo() { - - ::examples::Point* temp = lo_; - lo_ = NULL; - return temp; -} -inline void Rectangle::set_allocated_lo(::examples::Point* lo) { - delete lo_; - lo_ = lo; - if (lo) { - - } else { - - } - // @@protoc_insertion_point(field_set_allocated:examples.Rectangle.lo) -} - -// optional .examples.Point hi = 2; -inline bool Rectangle::has_hi() const { - return !_is_default_instance_ && hi_ != NULL; -} -inline void Rectangle::clear_hi() { - if (hi_ != NULL) delete hi_; - hi_ = NULL; -} -inline const ::examples::Point& Rectangle::hi() const { - // @@protoc_insertion_point(field_get:examples.Rectangle.hi) - return hi_ != NULL ? *hi_ : *default_instance_->hi_; -} -inline ::examples::Point* Rectangle::mutable_hi() { - - if (hi_ == NULL) { - hi_ = new ::examples::Point; - } - // @@protoc_insertion_point(field_mutable:examples.Rectangle.hi) - return hi_; -} -inline ::examples::Point* Rectangle::release_hi() { - - ::examples::Point* temp = hi_; - hi_ = NULL; - return temp; -} -inline void Rectangle::set_allocated_hi(::examples::Point* hi) { - delete hi_; - hi_ = hi; - if (hi) { - - } else { - - } - // @@protoc_insertion_point(field_set_allocated:examples.Rectangle.hi) -} - -// ------------------------------------------------------------------- - -// Feature - -// optional string name = 1; -inline void Feature::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& Feature::name() const { - // @@protoc_insertion_point(field_get:examples.Feature.name) - return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void Feature::set_name(const ::std::string& value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:examples.Feature.name) -} -inline void Feature::set_name(const char* value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:examples.Feature.name) -} -inline void Feature::set_name(const char* value, size_t size) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:examples.Feature.name) -} -inline ::std::string* Feature::mutable_name() { - - // @@protoc_insertion_point(field_mutable:examples.Feature.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* Feature::release_name() { - - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void Feature::set_allocated_name(::std::string* name) { - if (name != NULL) { - - } else { - - } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); - // @@protoc_insertion_point(field_set_allocated:examples.Feature.name) -} - -// optional .examples.Point location = 2; -inline bool Feature::has_location() const { - return !_is_default_instance_ && location_ != NULL; -} -inline void Feature::clear_location() { - if (location_ != NULL) delete location_; - location_ = NULL; -} -inline const ::examples::Point& Feature::location() const { - // @@protoc_insertion_point(field_get:examples.Feature.location) - return location_ != NULL ? *location_ : *default_instance_->location_; -} -inline ::examples::Point* Feature::mutable_location() { - - if (location_ == NULL) { - location_ = new ::examples::Point; - } - // @@protoc_insertion_point(field_mutable:examples.Feature.location) - return location_; -} -inline ::examples::Point* Feature::release_location() { - - ::examples::Point* temp = location_; - location_ = NULL; - return temp; -} -inline void Feature::set_allocated_location(::examples::Point* location) { - delete location_; - location_ = location; - if (location) { - - } else { - - } - // @@protoc_insertion_point(field_set_allocated:examples.Feature.location) -} - -// ------------------------------------------------------------------- - -// RouteNote - -// optional .examples.Point location = 1; -inline bool RouteNote::has_location() const { - return !_is_default_instance_ && location_ != NULL; -} -inline void RouteNote::clear_location() { - if (location_ != NULL) delete location_; - location_ = NULL; -} -inline const ::examples::Point& RouteNote::location() const { - // @@protoc_insertion_point(field_get:examples.RouteNote.location) - return location_ != NULL ? *location_ : *default_instance_->location_; -} -inline ::examples::Point* RouteNote::mutable_location() { - - if (location_ == NULL) { - location_ = new ::examples::Point; - } - // @@protoc_insertion_point(field_mutable:examples.RouteNote.location) - return location_; -} -inline ::examples::Point* RouteNote::release_location() { - - ::examples::Point* temp = location_; - location_ = NULL; - return temp; -} -inline void RouteNote::set_allocated_location(::examples::Point* location) { - delete location_; - location_ = location; - if (location) { - - } else { - - } - // @@protoc_insertion_point(field_set_allocated:examples.RouteNote.location) -} - -// optional string message = 2; -inline void RouteNote::clear_message() { - message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& RouteNote::message() const { - // @@protoc_insertion_point(field_get:examples.RouteNote.message) - return message_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void RouteNote::set_message(const ::std::string& value) { - - message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:examples.RouteNote.message) -} -inline void RouteNote::set_message(const char* value) { - - message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:examples.RouteNote.message) -} -inline void RouteNote::set_message(const char* value, size_t size) { - - message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:examples.RouteNote.message) -} -inline ::std::string* RouteNote::mutable_message() { - - // @@protoc_insertion_point(field_mutable:examples.RouteNote.message) - return message_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* RouteNote::release_message() { - - return message_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void RouteNote::set_allocated_message(::std::string* message) { - if (message != NULL) { - - } else { - - } - message_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), message); - // @@protoc_insertion_point(field_set_allocated:examples.RouteNote.message) -} - -// ------------------------------------------------------------------- - -// RouteSummary - -// optional int32 point_count = 1; -inline void RouteSummary::clear_point_count() { - point_count_ = 0; -} -inline ::google::protobuf::int32 RouteSummary::point_count() const { - // @@protoc_insertion_point(field_get:examples.RouteSummary.point_count) - return point_count_; -} -inline void RouteSummary::set_point_count(::google::protobuf::int32 value) { - - point_count_ = value; - // @@protoc_insertion_point(field_set:examples.RouteSummary.point_count) -} - -// optional int32 feature_count = 2; -inline void RouteSummary::clear_feature_count() { - feature_count_ = 0; -} -inline ::google::protobuf::int32 RouteSummary::feature_count() const { - // @@protoc_insertion_point(field_get:examples.RouteSummary.feature_count) - return feature_count_; -} -inline void RouteSummary::set_feature_count(::google::protobuf::int32 value) { - - feature_count_ = value; - // @@protoc_insertion_point(field_set:examples.RouteSummary.feature_count) -} - -// optional int32 distance = 3; -inline void RouteSummary::clear_distance() { - distance_ = 0; -} -inline ::google::protobuf::int32 RouteSummary::distance() const { - // @@protoc_insertion_point(field_get:examples.RouteSummary.distance) - return distance_; -} -inline void RouteSummary::set_distance(::google::protobuf::int32 value) { - - distance_ = value; - // @@protoc_insertion_point(field_set:examples.RouteSummary.distance) -} - -// optional int32 elapsed_time = 4; -inline void RouteSummary::clear_elapsed_time() { - elapsed_time_ = 0; -} -inline ::google::protobuf::int32 RouteSummary::elapsed_time() const { - // @@protoc_insertion_point(field_get:examples.RouteSummary.elapsed_time) - return elapsed_time_; -} -inline void RouteSummary::set_elapsed_time(::google::protobuf::int32 value) { - - elapsed_time_ = value; - // @@protoc_insertion_point(field_set:examples.RouteSummary.elapsed_time) -} - - -class RouteGuide final { - public: - class Stub final : public ::grpc::InternalStub { - public: - ::grpc::Status GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::examples::Feature* response); - ::grpc::ClientAsyncResponseReader< ::examples::Feature>* GetFeature(::grpc::ClientContext* context, const ::examples::Point& request, ::grpc::CompletionQueue* cq, void* tag); - ::grpc::ClientReader< ::examples::Feature>* ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request); - ::grpc::ClientAsyncReader< ::examples::Feature>* ListFeatures(::grpc::ClientContext* context, const ::examples::Rectangle& request, ::grpc::CompletionQueue* cq, void* tag); - ::grpc::ClientWriter< ::examples::Point>* RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response); - ::grpc::ClientAsyncWriter< ::examples::Point>* RecordRoute(::grpc::ClientContext* context, ::examples::RouteSummary* response, ::grpc::CompletionQueue* cq, void* tag); - ::grpc::ClientReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteChat(::grpc::ClientContext* context); - ::grpc::ClientAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* RouteChat(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag); - }; - static Stub* NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); - - class Service : public ::grpc::SynchronousService { - public: - Service() : service_(nullptr) {} - virtual ~Service(); - virtual ::grpc::Status GetFeature(::grpc::ServerContext* context, const ::examples::Point* request, ::examples::Feature* response); - virtual ::grpc::Status ListFeatures(::grpc::ServerContext* context, const ::examples::Rectangle* request, ::grpc::ServerWriter< ::examples::Feature>* writer); - virtual ::grpc::Status RecordRoute(::grpc::ServerContext* context, ::grpc::ServerReader< ::examples::Point>* reader, ::examples::RouteSummary* response); - virtual ::grpc::Status RouteChat(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream); - ::grpc::RpcService* service() override final; - private: - ::grpc::RpcService* service_; - }; - class AsyncService final : public ::grpc::AsynchronousService { - public: - explicit AsyncService(::grpc::CompletionQueue* cq); - ~AsyncService() {}; - void RequestGetFeature(::grpc::ServerContext* context, ::examples::Point* request, ::grpc::ServerAsyncResponseWriter< ::examples::Feature>* response, ::grpc::CompletionQueue* cq, void *tag); - void RequestListFeatures(::grpc::ServerContext* context, ::examples::Rectangle* request, ::grpc::ServerAsyncWriter< ::examples::Feature>* writer, ::grpc::CompletionQueue* cq, void *tag); - void RequestRecordRoute(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< ::examples::RouteSummary, ::examples::Point>* reader, ::grpc::CompletionQueue* cq, void *tag); - void RequestRouteChat(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::examples::RouteNote, ::examples::RouteNote>* stream, ::grpc::CompletionQueue* cq, void *tag); - }; -}; - -// @@protoc_insertion_point(namespace_scope) - -} // namespace examples - -#ifndef SWIG -namespace google { -namespace protobuf { - - -} // namespace protobuf -} // namespace google -#endif // SWIG - -// @@protoc_insertion_point(global_scope) - -#endif // PROTOBUF_route_5fguide_2eproto__INCLUDED diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 4a51f5eb382..65ca3af7d41 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -41,51 +41,110 @@ #include #include #include -#include "helloworld.pb.h" +#include +#include "route_guide.pb.h" using grpc::ChannelArguments; using grpc::ChannelInterface; using grpc::ClientContext; +using grpc::ClientReader; +using grpc::ClientReaderWriter; +using grpc::ClientWriter; using grpc::Status; -using helloworld::HelloRequest; -using helloworld::HelloReply; -using helloworld::Greeter; +using examples::Point; +using examples::Feature; +using examples::Rectangle; +using examples::RouteSummary; +using examples::RouteNote; +using examples::RouteGuide; -class GreeterClient { +class RouteGuideClient { public: - GreeterClient(std::shared_ptr channel) - : stub_(Greeter::NewStub(channel)) {} + RouteGuideClient(std::shared_ptr channel) + : stub_(RouteGuide::NewStub(channel)) {} - std::string SayHello(const std::string& user) { - HelloRequest request; - request.set_name(user); - HelloReply reply; + void GetFeature() { + Point point; + Feature feature; ClientContext context; - Status status = stub_->sayHello(&context, request, &reply); + Status status = stub_->GetFeature(&context, point, &feature); if (status.IsOk()) { - return reply.message(); + std::cout << "GetFeature rpc succeeded." << std::endl; } else { - return "Rpc failed"; + std::cout << "GetFeature rpc failed." << std::endl; + } + } + + void ListFeatures() { + Rectangle rect; + Feature feature; + ClientContext context; + + std::unique_ptr > reader( + stub_->ListFeatures(&context, rect)); + while (reader->Read(&feature)) { + std::cout << "Received feature" << std::endl; + } + Status status = reader->Finish(); + if (status.IsOk()) { + std::cout << "ListFeatures rpc succeeded." << std::endl; + } else { + std::cout << "ListFeatures rpc failed." << std::endl; + } + } + + void RecordRoute() { + Point point; + RouteSummary summary; + ClientContext context; + + std::unique_ptr > writer( + stub_->RecordRoute(&context, &summary)); + writer->WritesDone(); + Status status = writer->Finish(); + if (status.IsOk()) { + std::cout << "RecordRoute rpc succeeded." << std::endl; + } else { + std::cout << "RecordRoute rpc failed." << std::endl; + } + } + + void RouteChat() { + RouteNote server_note; + ClientContext context; + + std::unique_ptr > stream( + stub_->RouteChat(&context)); + stream->WritesDone(); + while (stream->Read(&server_note)) { + } + Status status = stream->Finish(); + if (status.IsOk()) { + std::cout << "RouteChat rpc succeeded." << std::endl; + } else { + std::cout << "RouteChat rpc failed." << std::endl; } } void Shutdown() { stub_.reset(); } private: - std::unique_ptr stub_; + std::unique_ptr stub_; }; int main(int argc, char** argv) { grpc_init(); - GreeterClient greeter( + RouteGuideClient guide( grpc::CreateChannel("localhost:50051", ChannelArguments())); - std::string user("world"); - std::string reply = greeter.SayHello(user); - std::cout << "Greeter received: " << reply << std::endl; - greeter.Shutdown(); + guide.GetFeature(); + guide.ListFeatures(); + guide.RecordRoute(); + guide.RouteChat(); + + guide.Shutdown(); grpc_shutdown(); } diff --git a/cpp/route_guide/route_guide_server.cc b/cpp/route_guide/route_guide_server.cc index 3a2ab60e892..718afbae2a8 100644 --- a/cpp/route_guide/route_guide_server.cc +++ b/cpp/route_guide/route_guide_server.cc @@ -41,28 +41,45 @@ #include #include #include -#include "helloworld.pb.h" +#include +#include "route_guide.pb.h" using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; +using grpc::ServerReader; +using grpc::ServerReaderWriter; +using grpc::ServerWriter; using grpc::Status; -using helloworld::HelloRequest; -using helloworld::HelloReply; -using helloworld::Greeter; +using examples::Point; +using examples::Feature; +using examples::Rectangle; +using examples::RouteSummary; +using examples::RouteNote; +using examples::RouteGuide; -class GreeterServiceImpl final : public Greeter::Service { - Status sayHello(ServerContext* context, const HelloRequest* request, - HelloReply* reply) override { - std::string prefix("Hello "); - reply->set_message(prefix + request->name()); +class RouteGuideImpl final : public RouteGuide::Service { + Status GetFeature(ServerContext* context, const Point* point, + Feature* feature) override { + return Status::OK; + } + Status ListFeatures(ServerContext* context, const Rectangle* rectangle, + ServerWriter* writer) override { + return Status::OK; + } + Status RecordRoute(ServerContext* context, ServerReader* reader, + RouteSummary* summary) override { + return Status::OK; + } + Status RouteChat(ServerContext* context, + ServerReaderWriter* stream) override { return Status::OK; } }; void RunServer() { std::string server_address("0.0.0.0:50051"); - GreeterServiceImpl service; + RouteGuideImpl service; ServerBuilder builder; builder.AddPort(server_address); From 2f22e84f725b2aa90c203410dff0b75c8ec25599 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Fri, 20 Feb 2015 16:39:32 -0800 Subject: [PATCH 087/576] Created helloworld tutorial outline --- cpp/helloworld/README.md | 95 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 cpp/helloworld/README.md diff --git a/cpp/helloworld/README.md b/cpp/helloworld/README.md new file mode 100644 index 00000000000..952325b4461 --- /dev/null +++ b/cpp/helloworld/README.md @@ -0,0 +1,95 @@ +# gRPC C++ Hello World Tutorial + +### Install gRPC +Make sure you have installed gRPC on your system. Follow the instructions here: +[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). + +### Get the tutorial source code + +The example code for this and our other examples lives in the `grpc-common` +GitHub repository. Clone this repository to your local machine by running the +following command: + + +```sh +$ git clone https://github.com/google/grpc-common.git +``` + +Change your current directory to grpc-common/cpp/helloworld + +```sh +$ cd grpc-common/cpp/helloworld/ +``` + +### Defining a service + +The first step in creating our example is to define a *service*: an RPC +service specifies the methods that can be called remotely with their parameters +and return types. As you saw in the +[overview](#protocolbuffers) above, gRPC does this using [protocol +buffers](https://developers.google.com/protocol-buffers/docs/overview). We +use the protocol buffers interface definition language (IDL) to define our +service methods, and define the parameters and return +types as protocol buffer message types. Both the client and the +server use interface code generated from the service definition. + +Here's our example service definition, defined using protocol buffers IDL in +[helloworld.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto). The `Greeting` +service has one method, `hello`, that lets the server receive a single +`HelloRequest` +message from the remote client containing the user's name, then send back +a greeting in a single `HelloReply`. This is the simplest type of RPC you +can specify in gRPC - we'll look at some other types later in this document. + +``` +syntax = "proto3"; + +option java_package = "ex.grpc"; + +package helloworld; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply) {} +} + +// The request message containing the user's name. +message HelloRequest { + string name = 1; +} + +// The response message containing the greetings +message HelloReply { + string message = 1; +} + +``` + + +### Generating gRPC code + +Once we've defined our service, we use the protocol buffer compiler +`protoc` to generate the special client and server code we need to create +our application. The generated code contains both stub code for clients to +use and an abstract interface for servers to implement, both with the method +defined in our `Greeting` service. + +To generate the client and server side interfaces: + +```sh +$ make helloworld.pb.cc +``` +Which internally invokes the proto-compiler as: + +```sh +$protoc -I ../../protos/ --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin helloworld.proto +``` + +### Writing a client + +This is an incomplete tutorial. For now the reader should refer to [greeter_client.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_client.cc). + +### Writing a server + +This is an incomplete tutorial. For now the reader should refer to [greeter_server.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_server.cc). From ca8c87738c5eb2c40173506131997efb03a30cde Mon Sep 17 00:00:00 2001 From: David Symonds Date: Sat, 21 Feb 2015 12:11:55 +1100 Subject: [PATCH 088/576] Tidy up README.md. Simply Go version requirement. Use `go get` instead of `go install`. Don't mention $GOBIN, which is irrelevant for most people. Fix a couple of typos. --- go/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/go/README.md b/go/README.md index d464b45d364..5d837f969da 100644 --- a/go/README.md +++ b/go/README.md @@ -4,7 +4,7 @@ gRPC in 3 minutes (Go) PREREQUISITES ------------- -- This requires Go 1.4.x +- This requires Go 1.4 - Requires that [GOPATH is set](https://golang.org/doc/code.html#GOPATH) ```sh $ go help gopath @@ -42,10 +42,10 @@ OPTIONAL - Rebuilding the generated code - This is will change once proto3 is officially released 2 Install the protoc Go plugin. ```sh -$ go install -a github.com/golang/protobuf/protoc-gen-go -$ # ensure the PATH contains $GOPATH/bin or $GOBIN -$ export PATH=PATH: +$ go get -a github.com/golang/protobuf/protoc-gen-go +$ # ensure the PATH contains $GOPATH/bin +$ export PATH=PATH:$GOPATH/bin $ -$ # from ths dir; invoke protoc +$ # from this dir; invoke protoc $ protoc -I ../protos ../protos/helloworld.proto --go_out=plugins=grpc:. ``` From 8169a6876245770f453e2cfe2517be91315bcf07 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Sat, 21 Feb 2015 12:23:36 +1100 Subject: [PATCH 089/576] Update to match standard Go style. Remove completely unused dial options, and reorder a bit of code to match what real code would look like. --- go/greeter_client/main.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/go/greeter_client/main.go b/go/greeter_client/main.go index abe33c0e2ad..3398040d7e5 100644 --- a/go/greeter_client/main.go +++ b/go/greeter_client/main.go @@ -49,19 +49,18 @@ const ( func main() { // Set up a connection to the server. - var opts []grpc.DialOption - conn, err := grpc.Dial(address, opts...) + conn, err := grpc.Dial(address) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() + c := pb.NewGreeterClient(conn) // Contact the server and print out its response. name := defaultName if len(os.Args) > 1 { name = os.Args[1] } - c := pb.NewGreeterClient(conn) r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) From 051969c36a39221578a5346c99130802a56b5da0 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Sat, 21 Feb 2015 12:27:23 +1100 Subject: [PATCH 090/576] More README.md improvements. Suggest the standard `go get` for downloading the demo. Remove instruction to set GOPATH during install flow, since the prerequisites section already does that. --- go/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/go/README.md b/go/README.md index 5d837f969da..7b90157043d 100644 --- a/go/README.md +++ b/go/README.md @@ -16,9 +16,8 @@ INSTALL ------- ```sh -$ export GOPATH= -$ go install -u github.com/grpc-common/go/greeter_client -$ go install -u github.com/grpc-common/go/greeter_server +$ go get -u github.com/grpc-common/go/greeter_client +$ go get -u github.com/grpc-common/go/greeter_server ``` TRY IT! From 6c359b36cd9f940d913d428bbaeb38a07806c4ce Mon Sep 17 00:00:00 2001 From: Qi Zhao Date: Fri, 20 Feb 2015 17:33:15 -0800 Subject: [PATCH 091/576] make the format correct. --- go/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/go/README.md b/go/README.md index 7b90157043d..2cab9092ae2 100644 --- a/go/README.md +++ b/go/README.md @@ -39,6 +39,7 @@ OPTIONAL - Rebuilding the generated code 1 First [install protoc](https://github.com/google/protobuf/blob/master/INSTALL.txt) - For now, this needs to be installed from source - This is will change once proto3 is officially released + 2 Install the protoc Go plugin. ```sh $ go get -a github.com/golang/protobuf/protoc-gen-go From d314cd2e884dc3730c879e7a2b7e1c84538cdeaa Mon Sep 17 00:00:00 2001 From: Qi Zhao Date: Fri, 20 Feb 2015 17:54:59 -0800 Subject: [PATCH 092/576] Improve README.md --- go/README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/go/README.md b/go/README.md index 2cab9092ae2..bf5d6c8cf48 100644 --- a/go/README.md +++ b/go/README.md @@ -8,8 +8,8 @@ PREREQUISITES - Requires that [GOPATH is set](https://golang.org/doc/code.html#GOPATH) ```sh $ go help gopath -$ # ensure the PATH contains $GOPATH/bin or $GOBIN -$ export PATH=PATH: +$ # ensure the PATH contains $GOPATH/bin +$ export PATH=$PATH:$GOPATH/bin ``` INSTALL @@ -43,8 +43,6 @@ OPTIONAL - Rebuilding the generated code 2 Install the protoc Go plugin. ```sh $ go get -a github.com/golang/protobuf/protoc-gen-go -$ # ensure the PATH contains $GOPATH/bin -$ export PATH=PATH:$GOPATH/bin $ $ # from this dir; invoke protoc $ protoc -I ../protos ../protos/helloworld.proto --go_out=plugins=grpc:. From 29bfc13ddae6c4d143519e01d5cc970b75168869 Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Fri, 20 Feb 2015 17:55:23 -0800 Subject: [PATCH 093/576] Update README.md Fix broken link --- cpp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/README.md b/cpp/README.md index a95bd3c8f0e..84fa34e7055 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -3,6 +3,6 @@ First you need to install gRPC on your system. Follow the instructions here: [https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). -After installing, you can proceed to the [gRPC C++ Hello World tutorial](https://github.com/grpc/grpc-common/cpp/helloworld). +After installing, you can proceed to the [gRPC C++ Hello World tutorial](helloworld/README.md). A more detailed tutorial is coming soon. From eb158ffb584e5067460e812a058b46ea517a1de2 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Sat, 21 Feb 2015 06:29:53 -0800 Subject: [PATCH 094/576] Update README.md --- ruby/README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ruby/README.md b/ruby/README.md index 668baf3eb71..1fc19a4f246 100644 --- a/ruby/README.md +++ b/ruby/README.md @@ -1,26 +1,26 @@ -gRPC Ruby Helloworld -==================== +gRPC in 3 minutes (Ruby) +======================== -INSTALLATION PREREQUISITES --------------------------- +PREREQUISITES +------------- -This requires Ruby 2.x, as the gRPC API surface uses keyword args. +This requires Ruby 2.1, as the gRPC API surface uses keyword args. INSTALL ------- - Clone this repository. - Follow the instructions in [INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL) to install the gRPC C core. -- *Temporary* Install gRPC for Ruby from source on your local machine and update path: to refer to it [Gemfile]. - - this is needed until the gRPC ruby gem is published +- *Temporary* Install the full gRPC distribution from source on your local machine and update path: in [Gemfile] to refer src/ruby within it. + - this is necessary until the gRPC ruby gem is published - Use bundler to install ```sh $ # from this directory $ gem install bundler && bundle install ``` -USAGE ------ +Try it! +------- - Run the server ```sh From 6b3df7da6a468313c2220315d1d141d9fe9353b0 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 00:54:35 -0800 Subject: [PATCH 095/576] client impl except db_parser --- cpp/route_guide/route_guide_client.cc | 169 +++++++++++++++++++++++--- 1 file changed, 150 insertions(+), 19 deletions(-) diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 65ca3af7d41..6dbe6b87303 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -31,9 +31,14 @@ * */ +#include +#include #include #include +#include +#include #include +#include #include #include @@ -58,6 +63,33 @@ using examples::RouteSummary; using examples::RouteNote; using examples::RouteGuide; +Point MakePoint(long latitude, long longitude) { + Point p; + p.set_latitude(latitude); + p.set_longitude(longitude); + return p; +} + +Feature MakeFeature(const std::string& name, + long latitude, long longitude) { + Feature f; + f.set_name(name); + f.mutable_location()->CopyFrom(MakePoint(latitude, longitude)); + return f; +} + +RouteNote MakeRouteNote(const std::string& message, + long latitude, long longitude) { + RouteNote n; + n.set_message(message); + n.mutable_location()->CopyFrom(MakePoint(latitude, longitude)); + return n; +} + +bool ParseDb(stringstream stream, std::vector* feature_list) { + // TODO +} + class RouteGuideClient { public: RouteGuideClient(std::shared_ptr channel) @@ -66,14 +98,10 @@ class RouteGuideClient { void GetFeature() { Point point; Feature feature; - ClientContext context; - - Status status = stub_->GetFeature(&context, point, &feature); - if (status.IsOk()) { - std::cout << "GetFeature rpc succeeded." << std::endl; - } else { - std::cout << "GetFeature rpc failed." << std::endl; - } + point = MakePoint(409146138, -746188906); + GetOneFeature(point, &feature); + point = MakePoint(0, 0); + GetOneFeature(point, &feature); } void ListFeatures() { @@ -81,10 +109,20 @@ class RouteGuideClient { Feature feature; ClientContext context; + rect.mutable_lo()->set_latitude(400000000); + rect.mutable_lo()->set_longitude(-750000000); + rect.mutable_hi()->set_latitude(420000000); + rect.mutable_hi()->set_longitude(-730000000); + std::cout << "Looking for features between 40, -75 and 42, -73" + << std::endl; + std::unique_ptr > reader( stub_->ListFeatures(&context, rect)); while (reader->Read(&feature)) { - std::cout << "Received feature" << std::endl; + std::cout << "Found feature called " + << feature.name() << " at " + << feature.location().latitude()/kCoordFactor_ << ", " + << feature.location().latitude()/kCoordFactor_ << std::endl; } Status status = reader->Finish(); if (status.IsOk()) { @@ -96,41 +134,120 @@ class RouteGuideClient { void RecordRoute() { Point point; - RouteSummary summary; + RouteSummary stats; ClientContext context; + const int kPoints = 10; + std::default_random_engine generator; + std::uniform_int_distribution feature_distribution( + 0, feature_list_.size() - 1); + std::uniform_int_distribution delay_distribution( + 500, 1500); std::unique_ptr > writer( - stub_->RecordRoute(&context, &summary)); + stub_->RecordRoute(&context, &stats)); + for (int i = 0; i < kPoints; i++) { + const Feature& f = feature_list_[feature_distribution(generator)]; + std::cout << "Visiting point " + << f.location().latitude()/kCoordFactor_ << ", " + << f.location().longitude()/kCoordFactor_ << std::endl; + if (!writer->Write(f.location())) { + // Broken stream. + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds( + delay_distribution(generator))); + } writer->WritesDone(); Status status = writer->Finish(); if (status.IsOk()) { - std::cout << "RecordRoute rpc succeeded." << std::endl; + std::cout << "Finished trip with " << stats.point_count() << " points\n" + << "Passed " << stats.feature_count() << " features\n" + << "Travelled " << stats.distance() << " meters\n" + << "It took " << stats.elapsed_time() << " seconds" + << std::endl; } else { std::cout << "RecordRoute rpc failed." << std::endl; } } void RouteChat() { - RouteNote server_note; ClientContext context; - std::unique_ptr > stream( - stub_->RouteChat(&context)); - stream->WritesDone(); + ClientReaderWriter* stream = + stub_->RouteChat(&context); + + std::thread writer([stream]() { + std::vector notes{ + MakeRouteNote("First message", 0, 0), + MakeRouteNote("Second message", 0, 1), + MakeRouteNote("Third message", 1, 0), + MakeRouteNote("Fourth message", 0, 0)}; + for (const RouteNote& note : notes) { + std::cout << "Sending message " << note.message() + << " at " << note.location().latitude() << ", " + << note.location().longitude() << std::endl; + stream->Write(note); + } + stream->WritesDone(); + }); + + RouteNote server_note; while (stream->Read(&server_note)) { + std::cout << "Got message " << server_note.message() + << " at " << server_note.location().latitude() << ", " + << server_note.location().longitude() << std::endl; } + writer.join(); Status status = stream->Finish(); - if (status.IsOk()) { - std::cout << "RouteChat rpc succeeded." << std::endl; - } else { + if (!status.IsOk()) { std::cout << "RouteChat rpc failed." << std::endl; } + delete stream; } void Shutdown() { stub_.reset(); } + void FillFeatureList(const std::string& db_path) { + if (db_path.empty()) { + return; + } + std::ifstream db_file(db_path); + if (!db_file.is_open()) { + std::cout << "Failed to open " << db_path << std::endl; + } + std::stringstream db; + db << db_file.rdbuf(); + ParseDb(db, &feature_list_); + } + private: + + bool GetOneFeature(const Point& point, Feature* feature) { + ClientContext context; + Status status = stub_->GetFeature(&context, point, feature); + if (!status.IsOk()) { + std::cout << "GetFeature rpc failed." << std::endl; + return false; + } + if (!feature->has_location()) { + std::cout << "Server returns incomplete feature." << std::endl; + return false; + } + if (feature->name().empty()) { + std::cout << "Found no feature at " + << feature->location().latitude()/kCoordFactor_ << ", " + << feature->location().longitude()/kCoordFactor_ << std::endl; + } else { + std::cout << "Found feature called " << feature->name() << " at " + << feature->location().latitude()/kCoordFactor_ << ", " + << feature->location().longitude()/kCoordFactor_ << std::endl; + } + return true; + } + + const float kCoordFactor_ = 10000000.0; std::unique_ptr stub_; + std::vector feature_list_; }; int main(int argc, char** argv) { @@ -138,6 +255,20 @@ int main(int argc, char** argv) { RouteGuideClient guide( grpc::CreateChannel("localhost:50051", ChannelArguments())); + std::string db_path; + std::string arg_str("--db_path"); + if (argc > 1) { + std::string argv_1 = argv[1]; + size_t start_position = argv_1.find(arg_str); + if (start_position != std::string::npos) { + start_position += arg_str.size(); + if (argv_1[start_position] == ' ' || + argv_1[start_position] == '=') { + db_path = argv_1.substr(start_position + 1); + } + } + } + guide.FillFeatureList(db_path); guide.GetFeature(); guide.ListFeatures(); From 9b3b2a23c15e39b1d8bd8f3b2416ff5ea59f3d77 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 23 Feb 2015 13:36:27 +0000 Subject: [PATCH 096/576] Added Go client example section, more tidying up of general info including protobuf. --- README.md | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 3a2fb8d7d1e..cb30f7d3c31 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,12 @@ platform-neutral remote procedure call (RPC) system developed at Google. This document introduces you to gRPC with a quick overview and a simple Hello World example. More documentation is coming soon! +## What's in this repository? + +The `grpc-common` repository contains documentation, resources, and examples for all gRPC users + +You can find out about the gRPC source code repositories in [`grpc`](https://github.com/grpc/grpc). + ## What is gRPC? In gRPC a *client* application can directly call @@ -69,23 +75,18 @@ a single Hello World method. - Create a Java server that implements this interface. - Create a Java client that accesses the Java server. -- Create a [probably need a different language now] client that accesses +- Create a Go client that accesses the same Java server. -- Update the service with more advanced features like RPC streaming. +- Update the service with a streaming RPC. The complete code for the example is available in the `grpc-common` GitHub -repository. You can -work along with the example and hack on the code in the comfort of your own -computer, giving you hands-on practice of really writing -gRPC code. We use the Git versioning system for source code management: +repository. We use the Git versioning system for source code management: however, you don't need to know anything about Git to follow along other than how to install and run a few git commands. This is an introductory example rather than a comprehensive tutorial, so don't worry if you're not a Go or -Java developer - the concepts introduced here are similar for all languages, -and complete tutorials and reference documentation for all gRPC -languages are coming soon. +Java developer - the concepts are similar for all languages, and you can find more implementations of our Hello World example in other languages in the language-specific folders in this repository. Complete tutorials and reference documentation for all gRPC languages are coming soon. ### Setup @@ -170,7 +171,7 @@ types as protocol buffer message types. Both the client and the server use interface code generated from the service definition. Here's our example service definition, defined using protocol buffers IDL in -[helloworld.proto](java/src/main/proto/helloworld.proto). The `Greeting` +[helloworld.proto](protos/helloworld.proto). The `Greeting` service has one method, `hello`, that lets the server receive a single `HelloRequest` message from the remote client containing the user's name, then send back @@ -223,13 +224,7 @@ classes. By default `protoc` just generates code for reading and writing protocol buffers, so you need to use plugins to add additional features to generated code. As we're creating Java code, we use the gRPC Java plugin. -To build the plugin: - -```sh -$ pushd external/grpc_java -$ make java_plugin -$ popd -``` +To build the plugin, follow the instructions in the relevant repo: for Java, the instructions are in [`grpc-java1](https://github.com/grpc/grpc-java). To use it to generate the code: @@ -440,6 +435,7 @@ and in another terminal window confirm that it receives a message. $ ./run_greeter_client.sh ``` + ### Adding another client From 683232652ecb6cb86cea2e743e69f009bfe39de9 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 23 Feb 2015 13:37:41 +0000 Subject: [PATCH 097/576] More tidying up --- README.md | 83 ++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 73 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index cb30f7d3c31..edb2b9daf89 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,14 @@ Hello World example. More documentation is coming soon! ## What's in this repository? -The `grpc-common` repository contains documentation, resources, and examples for all gRPC users +The `grpc-common` repository contains documentation, resources, and examples +for all gRPC users. You can find examples and instructions specific to your +favourite language in the relevant subdirectory. + +You can find out about the gRPC source code repositories in +[`grpc`](https://github.com/grpc/grpc). Each repository provides instructions +for building the appropriate libraries for your language. -You can find out about the gRPC source code repositories in [`grpc`](https://github.com/grpc/grpc). ## What is gRPC? @@ -51,7 +56,11 @@ While protocol buffers have been available for open source users for some time, our examples use a new flavour of protocol buffers called proto3, which has a slightly simplified syntax, some useful new features, and supports lots more languages. This is currently available as an alpha release in -[languages] from [wherever it's going], with more languages in development. +Java, C++ from [the protocol buffers Github +repo](https://github.com/google/protobuf/releases), as well as a Go language +generator [wherever that is](), with more languages in development. Full +documentation for proto3 is currently in development but you can see +the major differences from the current default version in the [release notes](https://github.com/google/protobuf/releases). In general, we recommend that you use proto3 with gRPC as it lets you use the full range of gRPC-supported languages, as well as avoiding compatibility @@ -86,7 +95,10 @@ than how to install and run a few git commands. This is an introductory example rather than a comprehensive tutorial, so don't worry if you're not a Go or -Java developer - the concepts are similar for all languages, and you can find more implementations of our Hello World example in other languages in the language-specific folders in this repository. Complete tutorials and reference documentation for all gRPC languages are coming soon. +Java developer - the concepts are similar for all languages, and you can +find more implementations of our Hello World example in other languages in +the language-specific folders in this repository. Complete tutorials and +reference documentation for all gRPC languages are coming soon. ### Setup @@ -224,7 +236,8 @@ classes. By default `protoc` just generates code for reading and writing protocol buffers, so you need to use plugins to add additional features to generated code. As we're creating Java code, we use the gRPC Java plugin. -To build the plugin, follow the instructions in the relevant repo: for Java, the instructions are in [`grpc-java1](https://github.com/grpc/grpc-java). +To build the plugin, follow the instructions in the relevant repo: for Java, +the instructions are in [`grpc-java1](https://github.com/grpc/grpc-java). To use it to generate the code: @@ -236,6 +249,8 @@ $ protoc -I . helloworld.proto --java_out=src/main/java ``` +[need to update this once I get the plugin built] + This generates the following classes, which contain all the generated code we need to create our example: @@ -435,12 +450,60 @@ and in another terminal window confirm that it receives a message. $ ./run_greeter_client.sh ``` - ### Adding another client - Finally, let's look at one of gRPC's most useful features - interoperability -between code in different languages. So far, we've just generated Java code -from our `Greeter` service definition.... +between code in different languages. So far, we've just looked at Java code +generated from and implementing our `Greeter` service definition. However, +as you'll see if you look at the language-specific subdirectories +in this repository, we've also generated and implemented `Greeter` +in some of gRPC's other supported languages. Each service +and client uses interface code generated from [exactly the same +.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto) +that we used for the Java example. + +So, for example, if we visit the [`go` +directory](https://github.com/grpc/grpc-common/tree/master/go) and look at the +[`greeter_client`](https://github.com/grpc/grpc-common/blob/master/go/greeter_client/main.go), +we can see that like the Java client, it connects to a `Greeter` service +at `localhost:50051` and uses a stub to call the `SayHello` method with a +`HelloRequest`: + +```go +const ( + address = "localhost:50051" + defaultName = "world" +) + +func main() { + // Set up a connection to the server. + conn, err := grpc.Dial(address) + if err != nil { + log.Fatalf("did not connect: %v", err) + } + defer conn.Close() + c := pb.NewGreeterClient(conn) + + // Contact the server and print out its response. + name := defaultName + if len(os.Args) > 1 { + name = os.Args[1] + } + r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: + name}) + if err != nil { + log.Fatalf("could not greet: %v", err) + } + log.Printf("Greeting: %s", r.Message) +} +``` + + +If we run the Java server from earlier in another terminal window, we can +run the Go client and connect to it just like the Java client, even though +it's written in a different language. + +``` +$ greeter_client +``` -###TODO: Section on Go client for same server From 5279a5f7ae94077948d74127a46af5201770075e Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 23 Feb 2015 13:39:16 +0000 Subject: [PATCH 098/576] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index edb2b9daf89..7f695cab907 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,7 @@ protocol buffers, so you need to use plugins to add additional features to generated code. As we're creating Java code, we use the gRPC Java plugin. To build the plugin, follow the instructions in the relevant repo: for Java, -the instructions are in [`grpc-java1](https://github.com/grpc/grpc-java). +the instructions are in [`grpc-java`](https://github.com/grpc/grpc-java). To use it to generate the code: From 54e0c6d4121e986b3b1acd35cbc74cba3bde4a72 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 23 Feb 2015 16:00:38 +0000 Subject: [PATCH 099/576] Starting the C++ Route Guide tutorial... --- cpp/cpptutorial.md | 108 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 cpp/cpptutorial.md diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md new file mode 100644 index 00000000000..d6c38f4f9bc --- /dev/null +++ b/cpp/cpptutorial.md @@ -0,0 +1,108 @@ +#gRPC Basics: C++ + +This tutorial provides a basic C++ programmer's introduction to working with gRPC. By walking through this example you'll learn how to: + +- Define a service in a .proto file. +- Generate server and client code using the protocol buffer compiler. +- Use the C++ gRPC API to write a simple client and server for your service. + +It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release: you can see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository. + +This isn't a comprehensive guide to using gRPC in C++: more reference documentation is coming soon. + +## Why use gRPC? + +Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. + +With gRPC we can define our service once in a .proto file and implement clients and servers in , which in turn - all the complexity of communication between different languages and environments is handled for you by gRPC. gRPC also + +We also get all the advantages of working with protocol buffers + +[possibly insert more advantages here] + +## Example code and setup + +The example code for our tutorial is in [grpc/grpc-common/cpp/route_guide](https://github.com/grpc/grpc-common/cpp/route_guide). To download the example, clone the `grpc-common` repository by running the following command: +```shell +$ git clone https://github.com/google/grpc-common.git +``` + +Then change your current directory to `grpc-common/cpp/route_guide`: +```shell +$ cd grpc-common/cpp/route_guide +``` + +Although we've provided the complete example so you don't need to generate the gRPC code yourself, if you want to try generating your own server and client interface code you can follow the setup instructions for the C++ gRPC libraries in [grpc/grpc/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). + + +## Defining the service + +Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto). + +To define a service, you specify a named `service` in your .proto file: + +``` +service RouteGuide { + ... +} +``` + +Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service: + +- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. +``` + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) {} +``` + +- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. +``` + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) {} +``` + +- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. +``` + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} +``` + +- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. +``` + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} +``` + +Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: +``` + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} +``` + + +## Generating client and server code + +Now we need to ... + + +## Creating the server + +First let's look at implementing our R + +There are two parts to making our `RouteGuide` service work: +- + + +## Creating the client + + + + + + From 450d112c02270149222578ec2238cca6516be285 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 23 Feb 2015 16:05:25 +0000 Subject: [PATCH 100/576] Small fixes in snippets. --- cpp/cpptutorial.md | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index d6c38f4f9bc..6f3f330c2c6 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -55,7 +55,7 @@ Then you define `rpc` methods inside your service definition, specifying their r rpc GetFeature(Point) returns (Feature) {} ``` -- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. +- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. ``` // Obtains the Features available within the given Rectangle. Results are // streamed rather than returned at once (e.g. in a response message with a @@ -64,25 +64,30 @@ Then you define `rpc` methods inside your service definition, specifying their r rpc ListFeatures(Rectangle) returns (stream Feature) {} ``` -- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. +- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type. ``` // Accepts a stream of Points on a route being traversed, returning a // RouteSummary when traversal is completed. rpc RecordRoute(stream Point) returns (RouteSummary) {} ``` -- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. +- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. ``` - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - rpc RecordRoute(stream Point) returns (RouteSummary) {} + // Accepts a stream of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} ``` Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: ``` - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - rpc RecordRoute(stream Point) returns (RouteSummary) {} +// Points are represented as latitude-longitude pairs in the E7 representation +// (degrees multiplied by 10**7 and rounded to the nearest integer). +// Latitudes should be in the range +/- 90 degrees and longitude should be in +// the range +/- 180 degrees (inclusive). +message Point { + int32 latitude = 1; + int32 longitude = 2; +} ``` From 7a21966ee7e0c4487887d34dda969e8b3457edf9 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 23 Feb 2015 16:42:21 +0000 Subject: [PATCH 101/576] More tutorial.. --- cpp/cpptutorial.md | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 6f3f330c2c6..ade134c86b4 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -14,9 +14,7 @@ This isn't a comprehensive guide to using gRPC in C++: more reference documentat Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. -With gRPC we can define our service once in a .proto file and implement clients and servers in , which in turn - all the complexity of communication between different languages and environments is handled for you by gRPC. gRPC also - -We also get all the advantages of working with protocol buffers +With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. [possibly insert more advantages here] @@ -93,15 +91,32 @@ message Point { ## Generating client and server code -Now we need to ... +Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC C++ plugin. + +For simplicity, we've provided a [makefile](https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/Makefile) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've followed the [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first): + +```shell +$ make route_guide.pb.cc +``` + +which actually runs: + +[actual command] + +Running this command generates the following files: +- `route_guide.pb.h` +- `route_guide.pb.cc` + +These contain ## Creating the server -First let's look at implementing our R +First let's look at how we create a `RouteGuide` server. There are two parts to making our `RouteGuide` service work: -- +- Implementing the service interface generated from our service definition: doing the actual "work" of our service. +- Running a gRPC server to listen for requests from clients and return the service responses ## Creating the client From 453eca38bb747d09a6ee0feaa97d6d8e9feaa68d Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Mon, 23 Feb 2015 16:58:19 +0000 Subject: [PATCH 102/576] Generating code... --- cpp/cpptutorial.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index ade134c86b4..21026781638 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -104,10 +104,12 @@ which actually runs: [actual command] Running this command generates the following files: -- `route_guide.pb.h` -- `route_guide.pb.cc` +- `route_guide.pb.h`, the header which declares your generated classes +- `route_guide.pb.cc`, which contains the implementation of your classes -These contain +These contain: +- All the protocol buffer code to populate, serialize, and retrieve our request and response message types +- A class called `RouteGuide` that contains both a remote interface type (or *stub*) for clients to call and an abstract interface for servers to implement, both with the methods defined in the `RouteGuide` service. ## Creating the server From 10135581963735854ed4918f805ab0c10f7a95d3 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Mon, 23 Feb 2015 09:22:26 -0800 Subject: [PATCH 103/576] Update README.md --- cpp/README.md | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/cpp/README.md b/cpp/README.md index 84fa34e7055..c1c79b592b3 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -3,6 +3,100 @@ First you need to install gRPC on your system. Follow the instructions here: [https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). -After installing, you can proceed to the [gRPC C++ Hello World tutorial](helloworld/README.md). +# gRPC C++ Hello World Tutorial + +### Install gRPC +Make sure you have installed gRPC on your system. Follow the instructions here: +[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). + +### Get the tutorial source code + +The example code for this and our other examples lives in the `grpc-common` +GitHub repository. Clone this repository to your local machine by running the +following command: + + +```sh +$ git clone https://github.com/google/grpc-common.git +``` + +Change your current directory to grpc-common/cpp/helloworld + +```sh +$ cd grpc-common/cpp/helloworld/ +``` + +### Defining a service + +The first step in creating our example is to define a *service*: an RPC +service specifies the methods that can be called remotely with their parameters +and return types. As you saw in the +[overview](#protocolbuffers) above, gRPC does this using [protocol +buffers](https://developers.google.com/protocol-buffers/docs/overview). We +use the protocol buffers interface definition language (IDL) to define our +service methods, and define the parameters and return +types as protocol buffer message types. Both the client and the +server use interface code generated from the service definition. + +Here's our example service definition, defined using protocol buffers IDL in +[helloworld.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto). The `Greeting` +service has one method, `hello`, that lets the server receive a single +`HelloRequest` +message from the remote client containing the user's name, then send back +a greeting in a single `HelloReply`. This is the simplest type of RPC you +can specify in gRPC - we'll look at some other types later in this document. + +``` +syntax = "proto3"; + +option java_package = "ex.grpc"; + +package helloworld; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply) {} +} + +// The request message containing the user's name. +message HelloRequest { + string name = 1; +} + +// The response message containing the greetings +message HelloReply { + string message = 1; +} + +``` + + +### Generating gRPC code + +Once we've defined our service, we use the protocol buffer compiler +`protoc` to generate the special client and server code we need to create +our application. The generated code contains both stub code for clients to +use and an abstract interface for servers to implement, both with the method +defined in our `Greeting` service. + +To generate the client and server side interfaces: + +```sh +$ make helloworld.pb.cc +``` +Which internally invokes the proto-compiler as: + +```sh +$protoc -I ../../protos/ --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin helloworld.proto +``` + +### Writing a client + +This is an incomplete tutorial. For now the reader should refer to [greeter_client.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_client.cc). + +### Writing a server + +This is an incomplete tutorial. For now the reader should refer to [greeter_server.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_server.cc). A more detailed tutorial is coming soon. From 9f5d6f64511a59efa374ae7920f266ffca391a38 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Mon, 23 Feb 2015 09:25:14 -0800 Subject: [PATCH 104/576] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index c123ba0a5a5..df3108d839a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,11 @@ +# Please pick your language to proceed: +* [C++](https://github.com/grpc/grpc-common/tree/master/cpp) +* [Java](https://github.com/grpc/grpc-common/tree/master/java) +* [Python](https://github.com/grpc/grpc-common/tree/master/python) +* [Go](https://github.com/grpc/grpc-common/tree/master/go) +* [ruby](https://github.com/grpc/grpc-common/tree/master/ruby) +* [Node.js](https://github.com/grpc/grpc-common/tree/master/node) + # Getting started Welcome to the developer documentation for gRPC, a language-neutral, From 686042c703f367f4cc3351179bfd8de2b52e3727 Mon Sep 17 00:00:00 2001 From: Mugur Marculescu Date: Mon, 23 Feb 2015 09:30:21 -0800 Subject: [PATCH 105/576] Delete README_NEW.md Content links moved to main README.md --- README_NEW.md | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 README_NEW.md diff --git a/README_NEW.md b/README_NEW.md deleted file mode 100644 index 583136bc0dd..00000000000 --- a/README_NEW.md +++ /dev/null @@ -1,8 +0,0 @@ - -# Please pick your language to proceed: -### [C++](https://github.com/grpc/grpc-common/tree/master/cpp) -### [Java](https://github.com/grpc/grpc-common/tree/master/java) -### [Python](https://github.com/grpc/grpc-common/tree/master/python) -### [Go](https://github.com/grpc/grpc-common/tree/master/go) -### [ruby](https://github.com/grpc/grpc-common/tree/master/ruby) -### [Node.js](https://github.com/grpc/grpc-common/tree/master/node) From d1e11e74939dded780bdaf1693451002d4059c3f Mon Sep 17 00:00:00 2001 From: LisaFC Date: Mon, 23 Feb 2015 18:16:08 +0000 Subject: [PATCH 106/576] Update README.md --- cpp/README.md | 79 ++++++++++----------------------------------------- 1 file changed, 15 insertions(+), 64 deletions(-) diff --git a/cpp/README.md b/cpp/README.md index c1c79b592b3..fe9b71620e7 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -1,15 +1,13 @@ -#gRPC C++ Getting started +#gRPC in 3 minutes (C++) -First you need to install gRPC on your system. Follow the instructions here: -[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). - -# gRPC C++ Hello World Tutorial +## Installation -### Install gRPC -Make sure you have installed gRPC on your system. Follow the instructions here: +To install gRPC on your system, follow the instructions here: [https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). -### Get the tutorial source code +## Hello C++ gRPC! + +Here's how to build and run the C++ implementation of the [Hello World](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto) example used in [Getting started](https://github.com/grpc/grpc-common). The example code for this and our other examples lives in the `grpc-common` GitHub repository. Clone this repository to your local machine by running the @@ -26,60 +24,9 @@ Change your current directory to grpc-common/cpp/helloworld $ cd grpc-common/cpp/helloworld/ ``` -### Defining a service - -The first step in creating our example is to define a *service*: an RPC -service specifies the methods that can be called remotely with their parameters -and return types. As you saw in the -[overview](#protocolbuffers) above, gRPC does this using [protocol -buffers](https://developers.google.com/protocol-buffers/docs/overview). We -use the protocol buffers interface definition language (IDL) to define our -service methods, and define the parameters and return -types as protocol buffer message types. Both the client and the -server use interface code generated from the service definition. - -Here's our example service definition, defined using protocol buffers IDL in -[helloworld.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto). The `Greeting` -service has one method, `hello`, that lets the server receive a single -`HelloRequest` -message from the remote client containing the user's name, then send back -a greeting in a single `HelloReply`. This is the simplest type of RPC you -can specify in gRPC - we'll look at some other types later in this document. - -``` -syntax = "proto3"; - -option java_package = "ex.grpc"; - -package helloworld; - -// The greeting service definition. -service Greeter { - // Sends a greeting - rpc SayHello (HelloRequest) returns (HelloReply) {} -} -// The request message containing the user's name. -message HelloRequest { - string name = 1; -} - -// The response message containing the greetings -message HelloReply { - string message = 1; -} - -``` - - ### Generating gRPC code -Once we've defined our service, we use the protocol buffer compiler -`protoc` to generate the special client and server code we need to create -our application. The generated code contains both stub code for clients to -use and an abstract interface for servers to implement, both with the method -defined in our `Greeting` service. - To generate the client and server side interfaces: ```sh @@ -91,12 +38,16 @@ Which internally invokes the proto-compiler as: $protoc -I ../../protos/ --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin helloworld.proto ``` -### Writing a client +### Client and server implementations + +The client implementation is at [greeter_client.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_client.cc). + +The server implementation is at [greeter_server.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_server.cc). -This is an incomplete tutorial. For now the reader should refer to [greeter_client.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_client.cc). +### Try it! -### Writing a server +###TODO: instructions to run server and client -This is an incomplete tutorial. For now the reader should refer to [greeter_server.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_server.cc). +## Tutorial -A more detailed tutorial is coming soon. +You can find a more detailed tutorial in [gRPC Basics: C++](https://github.com/grpc/grpc-common/blob/master/cpp/cpptutorial.md) From 613a1f32c2760bb7836dd1b2aafbb2d960189a99 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Mon, 23 Feb 2015 18:18:46 +0000 Subject: [PATCH 107/576] Update README.md --- README.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index df3108d839a..a1a3c4b9733 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,3 @@ -# Please pick your language to proceed: -* [C++](https://github.com/grpc/grpc-common/tree/master/cpp) -* [Java](https://github.com/grpc/grpc-common/tree/master/java) -* [Python](https://github.com/grpc/grpc-common/tree/master/python) -* [Go](https://github.com/grpc/grpc-common/tree/master/go) -* [ruby](https://github.com/grpc/grpc-common/tree/master/ruby) -* [Node.js](https://github.com/grpc/grpc-common/tree/master/node) # Getting started @@ -14,6 +7,15 @@ platform-neutral remote procedure call (RPC) system developed at Google. This document introduces you to gRPC with a quick overview and a simple Hello World example. More documentation is coming soon! +## Quick start +You can find quick start guides for each language, including installation instructions and examples here: +* [C++](https://github.com/grpc/grpc-common/tree/master/cpp) +* [Java](https://github.com/grpc/grpc-common/tree/master/java) +* [Python](https://github.com/grpc/grpc-common/tree/master/python) +* [Go](https://github.com/grpc/grpc-common/tree/master/go) +* [ruby](https://github.com/grpc/grpc-common/tree/master/ruby) +* [Node.js](https://github.com/grpc/grpc-common/tree/master/node) + ## What's in this repository? The `grpc-common` repository contains documentation, resources, and examples From 3906f35c453e9219bc1f7be0705ad0092d1e7044 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 10:44:44 -0800 Subject: [PATCH 108/576] make things compile --- cpp/route_guide/route_guide_client.cc | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 6dbe6b87303..86f603f5b47 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -86,7 +86,7 @@ RouteNote MakeRouteNote(const std::string& message, return n; } -bool ParseDb(stringstream stream, std::vector* feature_list) { +bool ParseDb(const std::string& stream, std::vector* feature_list) { // TODO } @@ -173,8 +173,8 @@ class RouteGuideClient { void RouteChat() { ClientContext context; - ClientReaderWriter* stream = - stub_->RouteChat(&context); + std::shared_ptr > stream( + stub_->RouteChat(&context)); std::thread writer([stream]() { std::vector notes{ @@ -202,7 +202,6 @@ class RouteGuideClient { if (!status.IsOk()) { std::cout << "RouteChat rpc failed." << std::endl; } - delete stream; } void Shutdown() { stub_.reset(); } @@ -217,7 +216,7 @@ class RouteGuideClient { } std::stringstream db; db << db_file.rdbuf(); - ParseDb(db, &feature_list_); + ParseDb(db.str(), &feature_list_); } private: From 09275f0be4e8c282d2febe3a983fd5632d89cbcc Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Mon, 23 Feb 2015 11:08:42 -0800 Subject: [PATCH 109/576] Added route guide example --- node/package.json | 5 +- node/route_guide/route_guide.proto | 120 +++++ node/route_guide/route_guide_client.js | 231 ++++++++++ node/route_guide/route_guide_db.json | 601 +++++++++++++++++++++++++ node/route_guide/route_guide_server.js | 249 ++++++++++ 5 files changed, 1205 insertions(+), 1 deletion(-) create mode 100644 node/route_guide/route_guide.proto create mode 100644 node/route_guide/route_guide_client.js create mode 100644 node/route_guide/route_guide_db.json create mode 100644 node/route_guide/route_guide_server.js diff --git a/node/package.json b/node/package.json index 435654034fa..a669dec8f18 100644 --- a/node/package.json +++ b/node/package.json @@ -2,6 +2,9 @@ "name": "grpc-greeter", "version": "0.1.0", "dependencies": { - "grpc" : "~0.2.0" + "async": "^0.9.0", + "grpc": "~0.2.0", + "minimist": "^1.1.0", + "underscore": "^1.8.2" } } diff --git a/node/route_guide/route_guide.proto b/node/route_guide/route_guide.proto new file mode 100644 index 00000000000..442112823e5 --- /dev/null +++ b/node/route_guide/route_guide.proto @@ -0,0 +1,120 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +option java_package = "io.grpc.examples"; + +package examples; + +// Interface exported by the server. +service RouteGuide { + // A simple RPC. + // + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) {} + + // A server-to-client streaming RPC. + // + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) {} + + // A client-to-server streaming RPC. + // + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} + + // A Bidirectional streaming RPC. + // + // Accepts a stream of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} +} + +// Points are represented as latitude-longitude pairs in the E7 representation +// (degrees multiplied by 10**7 and rounded to the nearest integer). +// Latitudes should be in the range +/- 90 degrees and longitude should be in +// the range +/- 180 degrees (inclusive). +message Point { + optional int32 latitude = 1; + optional int32 longitude = 2; +} + +// A latitude-longitude rectangle, represented as two diagonally opposite +// points "lo" and "hi". +message Rectangle { + // One corner of the rectangle. + optional Point lo = 1; + + // The other corner of the rectangle. + optional Point hi = 2; +} + +// A feature names something at a given point. +// +// If a feature could not be named, the name is empty. +message Feature { + // The name of the feature. + optional string name = 1; + + // The point where the feature is detected. + optional Point location = 2; +} + +// A RouteNote is a message sent while at a given point. +message RouteNote { + // The location from which the message is sent. + optional Point location = 1; + + // The message to be sent. + optional string message = 2; +} + +// A RouteSummary is received in response to a RecordRoute rpc. +// +// It contains the number of individual points received, the number of +// detected features, and the total distance covered as the cumulative sum of +// the distance between each point. +message RouteSummary { + // The number of points received. + optional int32 point_count = 1; + + // The number of known features passed while traversing the route. + optional int32 feature_count = 2; + + // The distance covered in metres. + optional int32 distance = 3; + + // The duration of the traversal in seconds. + optional int32 elapsed_time = 4; +} diff --git a/node/route_guide/route_guide_client.js b/node/route_guide/route_guide_client.js new file mode 100644 index 00000000000..60c47a429d6 --- /dev/null +++ b/node/route_guide/route_guide_client.js @@ -0,0 +1,231 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +var async = require('async'); +var fs = require('fs'); +var parseArgs = require('minimist'); +var path = require('path'); +var _ = require('underscore'); +var grpc = require('grpc'); +var examples = grpc.load(__dirname + '/route_guide.proto').examples; +var client = new examples.RouteGuide('localhost:50051'); + +var COORD_FACTOR = 1e7; + +/** + * Run the getFeature demo. Calls getFeature with a point known to have a + * feature and a point known not to have a feature. + * @param {function} callback Called when this demo is complete + */ +function runGetFeature(callback) { + var next = _.after(2, callback); + function featureCallback(error, feature) { + if (error) { + callback(error); + } + if (feature.name === '') { + console.log('Found no feature at ' + + feature.location.latitude/COORD_FACTOR + ', ' + + feature.location.longitude/COORD_FACTOR); + } else { + console.log('Found feature called "' + feature.name + '" at ' + + feature.location.latitude/COORD_FACTOR + ', ' + + feature.location.longitude/COORD_FACTOR); + } + next(); + } + var point1 = { + latitude: 409146138, + longitude: -746188906 + }; + var point2 = { + latitude: 0, + longitude: 0 + }; + client.getFeature(point1, featureCallback); + client.getFeature(point2, featureCallback); +} + +/** + * Run the listFeatures demo. Calls listFeatures with a rectangle containing all + * of the features in the pre-generated database. Prints each response as it + * comes in. + * @param {function} callback Called when this demo is complete + */ +function runListFeatures(callback) { + var rectangle = { + lo: { + latitude: 400000000, + longitude: -750000000 + }, + hi: { + latitude: 420000000, + longitude: -730000000 + } + }; + console.log('Looking for features between 40, -75 and 42, -73'); + var call = client.listFeatures(rectangle); + call.on('data', function(feature) { + console.log('Found feature called "' + feature.name + '" at ' + + feature.location.latitude/COORD_FACTOR + ', ' + + feature.location.longitude/COORD_FACTOR); + }); + call.on('end', callback); +} + +/** + * Run the recordRoute demo. Sends several randomly chosen points from the + * pre-generated feature database with a variable delay in between. Prints the + * statistics when they are sent from the server. + * @param {function} callback Called when this demo is complete + */ +function runRecordRoute(callback) { + var argv = parseArgs(process.argv, { + string: 'db_path' + }); + fs.readFile(path.resolve(argv.db_path), function(err, data) { + if (err) callback(err); + var feature_list = JSON.parse(data); + + var num_points = 10; + var call = client.recordRoute(function(error, stats) { + if (error) { + callback(error); + } + console.log('Finished trip with', stats.point_count, 'points'); + console.log('Passed', stats.feature_count, 'features'); + console.log('Travelled', stats.distance, 'meters'); + console.log('It took', stats.elapsed_time, 'seconds'); + callback(); + }); + /** + * Constructs a function that asynchronously sends the given point and then + * delays sending its callback + * @param {number} lat The latitude to send + * @param {number} lng The longitude to send + * @return {function(function)} The function that sends the point + */ + function pointSender(lat, lng) { + /** + * Sends the point, then calls the callback after a delay + * @param {function} callback Called when complete + */ + return function(callback) { + console.log('Visiting point ' + lat/COORD_FACTOR + ', ' + + lng/COORD_FACTOR); + call.write({ + latitude: lat, + longitude: lng + }); + _.delay(callback, _.random(500, 1500)); + }; + } + var point_senders = []; + for (var i = 0; i < num_points; i++) { + var rand_point = feature_list[_.random(0, feature_list.length - 1)]; + point_senders[i] = pointSender(rand_point.location.latitude, + rand_point.location.longitude); + } + async.series(point_senders, function() { + call.end(); + }); + }); +} + +/** + * Run the routeChat demo. Send some chat messages, and print any chat messages + * that are sent from the server. + * @param {function} callback Called when the demo is complete + */ +function runRouteChat(callback) { + var call = client.routeChat(); + call.on('data', function(note) { + console.log('Got message "' + note.message + '" at ' + + note.location.latitude + ', ' + note.location.longitude); + }); + + call.on('end', callback); + + var notes = [{ + location: { + latitude: 0, + longitude: 0 + }, + message: 'First message' + }, { + location: { + latitude: 0, + longitude: 1 + }, + message: 'Second message' + }, { + location: { + latitude: 1, + longitude: 0 + }, + message: 'Third message' + }, { + location: { + latitude: 0, + longitude: 0 + }, + message: 'Fourth message' + }]; + for (var i = 0; i < notes.length; i++) { + var note = notes[i]; + console.log('Sending message "' + note.message + '" at ' + + note.location.latitude + ', ' + note.location.longitude); + call.write(note); + } + call.end(); +} + +/** + * Run all of the demos in order + */ +function main() { + async.series([ + runGetFeature, + runListFeatures, + runRecordRoute, + runRouteChat + ]); +} + +if (require.main === module) { + main(); +} + +exports.runGetFeature = runGetFeature; + +exports.runListFeatures = runListFeatures; + +exports.runRecordRoute = runRecordRoute; + +exports.runRouteChat = runRouteChat; diff --git a/node/route_guide/route_guide_db.json b/node/route_guide/route_guide_db.json new file mode 100644 index 00000000000..9d6a980ab7d --- /dev/null +++ b/node/route_guide/route_guide_db.json @@ -0,0 +1,601 @@ +[{ + "location": { + "latitude": 407838351, + "longitude": -746143763 + }, + "name": "Patriots Path, Mendham, NJ 07945, USA" +}, { + "location": { + "latitude": 408122808, + "longitude": -743999179 + }, + "name": "101 New Jersey 10, Whippany, NJ 07981, USA" +}, { + "location": { + "latitude": 413628156, + "longitude": -749015468 + }, + "name": "U.S. 6, Shohola, PA 18458, USA" +}, { + "location": { + "latitude": 419999544, + "longitude": -740371136 + }, + "name": "5 Conners Road, Kingston, NY 12401, USA" +}, { + "location": { + "latitude": 414008389, + "longitude": -743951297 + }, + "name": "Mid Hudson Psychiatric Center, New Hampton, NY 10958, USA" +}, { + "location": { + "latitude": 419611318, + "longitude": -746524769 + }, + "name": "287 Flugertown Road, Livingston Manor, NY 12758, USA" +}, { + "location": { + "latitude": 406109563, + "longitude": -742186778 + }, + "name": "4001 Tremley Point Road, Linden, NJ 07036, USA" +}, { + "location": { + "latitude": 416802456, + "longitude": -742370183 + }, + "name": "352 South Mountain Road, Wallkill, NY 12589, USA" +}, { + "location": { + "latitude": 412950425, + "longitude": -741077389 + }, + "name": "Bailey Turn Road, Harriman, NY 10926, USA" +}, { + "location": { + "latitude": 412144655, + "longitude": -743949739 + }, + "name": "193-199 Wawayanda Road, Hewitt, NJ 07421, USA" +}, { + "location": { + "latitude": 415736605, + "longitude": -742847522 + }, + "name": "406-496 Ward Avenue, Pine Bush, NY 12566, USA" +}, { + "location": { + "latitude": 413843930, + "longitude": -740501726 + }, + "name": "162 Merrill Road, Highland Mills, NY 10930, USA" +}, { + "location": { + "latitude": 410873075, + "longitude": -744459023 + }, + "name": "Clinton Road, West Milford, NJ 07480, USA" +}, { + "location": { + "latitude": 412346009, + "longitude": -744026814 + }, + "name": "16 Old Brook Lane, Warwick, NY 10990, USA" +}, { + "location": { + "latitude": 402948455, + "longitude": -747903913 + }, + "name": "3 Drake Lane, Pennington, NJ 08534, USA" +}, { + "location": { + "latitude": 406337092, + "longitude": -740122226 + }, + "name": "6324 8th Avenue, Brooklyn, NY 11220, USA" +}, { + "location": { + "latitude": 406421967, + "longitude": -747727624 + }, + "name": "1 Merck Access Road, Whitehouse Station, NJ 08889, USA" +}, { + "location": { + "latitude": 416318082, + "longitude": -749677716 + }, + "name": "78-98 Schalck Road, Narrowsburg, NY 12764, USA" +}, { + "location": { + "latitude": 415301720, + "longitude": -748416257 + }, + "name": "282 Lakeview Drive Road, Highland Lake, NY 12743, USA" +}, { + "location": { + "latitude": 402647019, + "longitude": -747071791 + }, + "name": "330 Evelyn Avenue, Hamilton Township, NJ 08619, USA" +}, { + "location": { + "latitude": 412567807, + "longitude": -741058078 + }, + "name": "New York State Reference Route 987E, Southfields, NY 10975, USA" +}, { + "location": { + "latitude": 416855156, + "longitude": -744420597 + }, + "name": "103-271 Tempaloni Road, Ellenville, NY 12428, USA" +}, { + "location": { + "latitude": 404663628, + "longitude": -744820157 + }, + "name": "1300 Airport Road, North Brunswick Township, NJ 08902, USA" +}, { + "location": { + "latitude": 407113723, + "longitude": -749746483 + }, + "name": "" +}, { + "location": { + "latitude": 402133926, + "longitude": -743613249 + }, + "name": "" +}, { + "location": { + "latitude": 400273442, + "longitude": -741220915 + }, + "name": "" +}, { + "location": { + "latitude": 411236786, + "longitude": -744070769 + }, + "name": "" +}, { + "location": { + "latitude": 411633782, + "longitude": -746784970 + }, + "name": "211-225 Plains Road, Augusta, NJ 07822, USA" +}, { + "location": { + "latitude": 415830701, + "longitude": -742952812 + }, + "name": "" +}, { + "location": { + "latitude": 413447164, + "longitude": -748712898 + }, + "name": "165 Pedersen Ridge Road, Milford, PA 18337, USA" +}, { + "location": { + "latitude": 405047245, + "longitude": -749800722 + }, + "name": "100-122 Locktown Road, Frenchtown, NJ 08825, USA" +}, { + "location": { + "latitude": 418858923, + "longitude": -746156790 + }, + "name": "" +}, { + "location": { + "latitude": 417951888, + "longitude": -748484944 + }, + "name": "650-652 Willi Hill Road, Swan Lake, NY 12783, USA" +}, { + "location": { + "latitude": 407033786, + "longitude": -743977337 + }, + "name": "26 East 3rd Street, New Providence, NJ 07974, USA" +}, { + "location": { + "latitude": 417548014, + "longitude": -740075041 + }, + "name": "" +}, { + "location": { + "latitude": 410395868, + "longitude": -744972325 + }, + "name": "" +}, { + "location": { + "latitude": 404615353, + "longitude": -745129803 + }, + "name": "" +}, { + "location": { + "latitude": 406589790, + "longitude": -743560121 + }, + "name": "611 Lawrence Avenue, Westfield, NJ 07090, USA" +}, { + "location": { + "latitude": 414653148, + "longitude": -740477477 + }, + "name": "18 Lannis Avenue, New Windsor, NY 12553, USA" +}, { + "location": { + "latitude": 405957808, + "longitude": -743255336 + }, + "name": "82-104 Amherst Avenue, Colonia, NJ 07067, USA" +}, { + "location": { + "latitude": 411733589, + "longitude": -741648093 + }, + "name": "170 Seven Lakes Drive, Sloatsburg, NY 10974, USA" +}, { + "location": { + "latitude": 412676291, + "longitude": -742606606 + }, + "name": "1270 Lakes Road, Monroe, NY 10950, USA" +}, { + "location": { + "latitude": 409224445, + "longitude": -748286738 + }, + "name": "509-535 Alphano Road, Great Meadows, NJ 07838, USA" +}, { + "location": { + "latitude": 406523420, + "longitude": -742135517 + }, + "name": "652 Garden Street, Elizabeth, NJ 07202, USA" +}, { + "location": { + "latitude": 401827388, + "longitude": -740294537 + }, + "name": "349 Sea Spray Court, Neptune City, NJ 07753, USA" +}, { + "location": { + "latitude": 410564152, + "longitude": -743685054 + }, + "name": "13-17 Stanley Street, West Milford, NJ 07480, USA" +}, { + "location": { + "latitude": 408472324, + "longitude": -740726046 + }, + "name": "47 Industrial Avenue, Teterboro, NJ 07608, USA" +}, { + "location": { + "latitude": 412452168, + "longitude": -740214052 + }, + "name": "5 White Oak Lane, Stony Point, NY 10980, USA" +}, { + "location": { + "latitude": 409146138, + "longitude": -746188906 + }, + "name": "Berkshire Valley Management Area Trail, Jefferson, NJ, USA" +}, { + "location": { + "latitude": 404701380, + "longitude": -744781745 + }, + "name": "1007 Jersey Avenue, New Brunswick, NJ 08901, USA" +}, { + "location": { + "latitude": 409642566, + "longitude": -746017679 + }, + "name": "6 East Emerald Isle Drive, Lake Hopatcong, NJ 07849, USA" +}, { + "location": { + "latitude": 408031728, + "longitude": -748645385 + }, + "name": "1358-1474 New Jersey 57, Port Murray, NJ 07865, USA" +}, { + "location": { + "latitude": 413700272, + "longitude": -742135189 + }, + "name": "367 Prospect Road, Chester, NY 10918, USA" +}, { + "location": { + "latitude": 404310607, + "longitude": -740282632 + }, + "name": "10 Simon Lake Drive, Atlantic Highlands, NJ 07716, USA" +}, { + "location": { + "latitude": 409319800, + "longitude": -746201391 + }, + "name": "11 Ward Street, Mount Arlington, NJ 07856, USA" +}, { + "location": { + "latitude": 406685311, + "longitude": -742108603 + }, + "name": "300-398 Jefferson Avenue, Elizabeth, NJ 07201, USA" +}, { + "location": { + "latitude": 419018117, + "longitude": -749142781 + }, + "name": "43 Dreher Road, Roscoe, NY 12776, USA" +}, { + "location": { + "latitude": 412856162, + "longitude": -745148837 + }, + "name": "Swan Street, Pine Island, NY 10969, USA" +}, { + "location": { + "latitude": 416560744, + "longitude": -746721964 + }, + "name": "66 Pleasantview Avenue, Monticello, NY 12701, USA" +}, { + "location": { + "latitude": 405314270, + "longitude": -749836354 + }, + "name": "" +}, { + "location": { + "latitude": 414219548, + "longitude": -743327440 + }, + "name": "" +}, { + "location": { + "latitude": 415534177, + "longitude": -742900616 + }, + "name": "565 Winding Hills Road, Montgomery, NY 12549, USA" +}, { + "location": { + "latitude": 406898530, + "longitude": -749127080 + }, + "name": "231 Rocky Run Road, Glen Gardner, NJ 08826, USA" +}, { + "location": { + "latitude": 407586880, + "longitude": -741670168 + }, + "name": "100 Mount Pleasant Avenue, Newark, NJ 07104, USA" +}, { + "location": { + "latitude": 400106455, + "longitude": -742870190 + }, + "name": "517-521 Huntington Drive, Manchester Township, NJ 08759, USA" +}, { + "location": { + "latitude": 400066188, + "longitude": -746793294 + }, + "name": "" +}, { + "location": { + "latitude": 418803880, + "longitude": -744102673 + }, + "name": "40 Mountain Road, Napanoch, NY 12458, USA" +}, { + "location": { + "latitude": 414204288, + "longitude": -747895140 + }, + "name": "" +}, { + "location": { + "latitude": 414777405, + "longitude": -740615601 + }, + "name": "" +}, { + "location": { + "latitude": 415464475, + "longitude": -747175374 + }, + "name": "48 North Road, Forestburgh, NY 12777, USA" +}, { + "location": { + "latitude": 404062378, + "longitude": -746376177 + }, + "name": "" +}, { + "location": { + "latitude": 405688272, + "longitude": -749285130 + }, + "name": "" +}, { + "location": { + "latitude": 400342070, + "longitude": -748788996 + }, + "name": "" +}, { + "location": { + "latitude": 401809022, + "longitude": -744157964 + }, + "name": "" +}, { + "location": { + "latitude": 404226644, + "longitude": -740517141 + }, + "name": "9 Thompson Avenue, Leonardo, NJ 07737, USA" +}, { + "location": { + "latitude": 410322033, + "longitude": -747871659 + }, + "name": "" +}, { + "location": { + "latitude": 407100674, + "longitude": -747742727 + }, + "name": "" +}, { + "location": { + "latitude": 418811433, + "longitude": -741718005 + }, + "name": "213 Bush Road, Stone Ridge, NY 12484, USA" +}, { + "location": { + "latitude": 415034302, + "longitude": -743850945 + }, + "name": "" +}, { + "location": { + "latitude": 411349992, + "longitude": -743694161 + }, + "name": "" +}, { + "location": { + "latitude": 404839914, + "longitude": -744759616 + }, + "name": "1-17 Bergen Court, New Brunswick, NJ 08901, USA" +}, { + "location": { + "latitude": 414638017, + "longitude": -745957854 + }, + "name": "35 Oakland Valley Road, Cuddebackville, NY 12729, USA" +}, { + "location": { + "latitude": 412127800, + "longitude": -740173578 + }, + "name": "" +}, { + "location": { + "latitude": 401263460, + "longitude": -747964303 + }, + "name": "" +}, { + "location": { + "latitude": 412843391, + "longitude": -749086026 + }, + "name": "" +}, { + "location": { + "latitude": 418512773, + "longitude": -743067823 + }, + "name": "" +}, { + "location": { + "latitude": 404318328, + "longitude": -740835638 + }, + "name": "42-102 Main Street, Belford, NJ 07718, USA" +}, { + "location": { + "latitude": 419020746, + "longitude": -741172328 + }, + "name": "" +}, { + "location": { + "latitude": 404080723, + "longitude": -746119569 + }, + "name": "" +}, { + "location": { + "latitude": 401012643, + "longitude": -744035134 + }, + "name": "" +}, { + "location": { + "latitude": 404306372, + "longitude": -741079661 + }, + "name": "" +}, { + "location": { + "latitude": 403966326, + "longitude": -748519297 + }, + "name": "" +}, { + "location": { + "latitude": 405002031, + "longitude": -748407866 + }, + "name": "" +}, { + "location": { + "latitude": 409532885, + "longitude": -742200683 + }, + "name": "" +}, { + "location": { + "latitude": 416851321, + "longitude": -742674555 + }, + "name": "" +}, { + "location": { + "latitude": 406411633, + "longitude": -741722051 + }, + "name": "3387 Richmond Terrace, Staten Island, NY 10303, USA" +}, { + "location": { + "latitude": 413069058, + "longitude": -744597778 + }, + "name": "261 Van Sickle Road, Goshen, NY 10924, USA" +}, { + "location": { + "latitude": 418465462, + "longitude": -746859398 + }, + "name": "" +}, { + "location": { + "latitude": 411733222, + "longitude": -744228360 + }, + "name": "" +}, { + "location": { + "latitude": 410248224, + "longitude": -747127767 + }, + "name": "3 Hasta Way, Newton, NJ 07860, USA" +}] diff --git a/node/route_guide/route_guide_server.js b/node/route_guide/route_guide_server.js new file mode 100644 index 00000000000..5dd84126543 --- /dev/null +++ b/node/route_guide/route_guide_server.js @@ -0,0 +1,249 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +var fs = require('fs'); +var parseArgs = require('minimist'); +var path = require('path'); +var _ = require('underscore'); +var grpc = require('grpc'); +var examples = grpc.load(__dirname + '/route_guide.proto').examples; + +var Server = grpc.buildServer([examples.RouteGuide.service]); + +var COORD_FACTOR = 1e7; + +/** + * For simplicity, a point is a record type that looks like + * {latitude: number, longitude: number}, and a feature is a record type that + * looks like {name: string, location: point}. feature objects with name==='' + * are points with no feature. + */ + +/** + * List of feature objects at points that have been requested so far. + */ +var feature_list = []; + +/** + * Get a feature object at the given point, or creates one if it does not exist. + * @param {point} point The point to check + * @return {feature} The feature object at the point. Note that an empty name + * indicates no feature + */ +function checkFeature(point) { + var feature; + // Check if there is already a feature object for the given point + for (var i = 0; i < feature_list.length; i++) { + feature = feature_list[i]; + if (feature.location.latitude === point.latitude && + feature.location.longitude === point.longitude) { + return feature; + } + } + var name = ''; + feature = { + name: name, + location: point + }; + return feature; +} + +/** + * getFeature request handler. Gets a request with a point, and responds with a + * feature object indicating whether there is a feature at that point. + * @param {EventEmitter} call Call object for the handler to process + * @param {function(Error, feature)} callback Response callback + */ +function getFeature(call, callback) { + callback(null, checkFeature(call.request)); +} + +/** + * listFeatures request handler. Gets a request with two points, and responds + * with a stream of all features in the bounding box defined by those points. + * @param {Writable} call Writable stream for responses with an additional + * request property for the request value. + */ +function listFeatures(call) { + var lo = call.request.lo; + var hi = call.request.hi; + var left = _.min([lo.longitude, hi.longitude]); + var right = _.max([lo.longitude, hi.longitude]); + var top = _.max([lo.latitude, hi.latitude]); + var bottom = _.min([lo.latitude, hi.latitude]); + // For each feature, check if it is in the given bounding box + _.each(feature_list, function(feature) { + if (feature.name === '') { + return; + } + if (feature.location.longitude >= left && + feature.location.longitude <= right && + feature.location.latitude >= bottom && + feature.location.latitude <= top) { + call.write(feature); + } + }); + call.end(); +} + +/** + * Calculate the distance between two points using the "haversine" formula. + * This code was taken from http://www.movable-type.co.uk/scripts/latlong.html. + * @param start The starting point + * @param end The end point + * @return The distance between the points in meters + */ +function getDistance(start, end) { + function toRadians(num) { + return num * Math.PI / 180; + } + var lat1 = start.latitude / COORD_FACTOR; + var lat2 = end.latitude / COORD_FACTOR; + var lon1 = start.longitude / COORD_FACTOR; + var lon2 = end.longitude / COORD_FACTOR; + var R = 6371000; // metres + var φ1 = toRadians(lat1); + var φ2 = toRadians(lat2); + var Δφ = toRadians(lat2-lat1); + var Δλ = toRadians(lon2-lon1); + + var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + + Math.cos(φ1) * Math.cos(φ2) * + Math.sin(Δλ/2) * Math.sin(Δλ/2); + var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + + return R * c; +} + +/** + * recordRoute handler. Gets a stream of points, and responds with statistics + * about the "trip": number of points, number of known features visited, total + * distance traveled, and total time spent. + * @param {Readable} call The request point stream. + * @param {function(Error, routeSummary)} callback The callback to pass the + * response to + */ +function recordRoute(call, callback) { + var point_count = 0; + var feature_count = 0; + var distance = 0; + var previous = null; + // Start a timer + var start_time = process.hrtime(); + call.on('data', function(point) { + point_count += 1; + if (checkFeature(point).name !== '') { + feature_count += 1; + } + /* For each point after the first, add the incremental distance from the + * previous point to the total distance value */ + if (previous != null) { + distance += getDistance(previous, point); + } + previous = point; + }); + call.on('end', function() { + callback(null, { + point_count: point_count, + feature_count: feature_count, + // Cast the distance to an integer + distance: distance|0, + // End the timer + elapsed_time: process.hrtime(start_time)[0] + }); + }); +} + +var route_notes = {}; + +/** + * Turn the point into a dictionary key. + * @param {point} point The point to use + * @return {string} The key for an object + */ +function pointKey(point) { + return point.latitude + ' ' + point.longitude; +} + +/** + * routeChat handler. Receives a stream of message/location pairs, and responds + * with a stream of all previous messages at each of those locations. + * @param {Duplex} call The stream for incoming and outgoing messages + */ +function routeChat(call) { + call.on('data', function(note) { + var key = pointKey(note.location); + /* For each note sent, respond with all previous notes that correspond to + * the same point */ + if (route_notes.hasOwnProperty(key)) { + _.each(route_notes[key], function(note) { + call.write(note); + }); + } else { + route_notes[key] = []; + } + // Then add the new note to the list + route_notes[key].push(JSON.parse(JSON.stringify(note))); + }); + call.on('end', function() { + call.end(); + }); +} + +/** + * Get a new server with the handler functions in this file bound to the methods + * it serves. + * @return {Server} The new server object + */ +function getServer() { + return new Server({ + 'examples.RouteGuide' : { + getFeature: getFeature, + listFeatures: listFeatures, + recordRoute: recordRoute, + routeChat: routeChat + } + }); +} + +if (require.main === module) { + // If this is run as a script, start a server on an unused port + var routeServer = getServer(); + routeServer.bind('0.0.0.0:50051'); + var argv = parseArgs(process.argv, { + string: 'db_path' + }); + fs.readFile(path.resolve(argv.db_path), function(err, data) { + if (err) throw err; + feature_list = JSON.parse(data); + routeServer.listen(); + }); +} + +exports.getServer = getServer; From ea33d60f71980f53e20c245768efe50683170e24 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 13:55:33 -0800 Subject: [PATCH 110/576] Server impl. Status: builds. Missing db parsing logic --- cpp/route_guide/route_guide_client.cc | 24 +++-- cpp/route_guide/route_guide_server.cc | 143 +++++++++++++++++++++++++- 2 files changed, 154 insertions(+), 13 deletions(-) diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 86f603f5b47..8b4a5323271 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -90,6 +90,19 @@ bool ParseDb(const std::string& stream, std::vector* feature_list) { // TODO } +void FillFeatureList(const std::string& db_path, std::vector* feature_list) { + if (db_path.empty()) { + return; + } + std::ifstream db_file(db_path); + if (!db_file.is_open()) { + std::cout << "Failed to open " << db_path << std::endl; + } + std::stringstream db; + db << db_file.rdbuf(); + ParseDb(db.str(), feature_list); +} + class RouteGuideClient { public: RouteGuideClient(std::shared_ptr channel) @@ -207,16 +220,7 @@ class RouteGuideClient { void Shutdown() { stub_.reset(); } void FillFeatureList(const std::string& db_path) { - if (db_path.empty()) { - return; - } - std::ifstream db_file(db_path); - if (!db_file.is_open()) { - std::cout << "Failed to open " << db_path << std::endl; - } - std::stringstream db; - db << db_file.rdbuf(); - ParseDb(db.str(), &feature_list_); + ::FillFeatureList(db_path, &feature_list_); } private: diff --git a/cpp/route_guide/route_guide_server.cc b/cpp/route_guide/route_guide_server.cc index 718afbae2a8..d4ecded69ba 100644 --- a/cpp/route_guide/route_guide_server.cc +++ b/cpp/route_guide/route_guide_server.cc @@ -31,8 +31,13 @@ * */ +#include +#include +#include +#include #include #include +#include #include #include @@ -57,29 +62,148 @@ using examples::Rectangle; using examples::RouteSummary; using examples::RouteNote; using examples::RouteGuide; +using std::chrono::system_clock; + +const float kCoordFactor = 10000000.0; + +bool ParseDb(const std::string& stream, std::vector* feature_list) { + // TODO +} + +float ConvertToRadians(float num) { + return num * 3.1415926 /180; +} + +float GetDistance(const Point& start, const Point& end) { + + float lat_1 = start.latitude() / kCoordFactor; + float lat_2 = end.latitude() / kCoordFactor; + float lon_1 = start.longitude() / kCoordFactor; + float lon_2 = end.longitude() / kCoordFactor; + float lat_rad_1 = ConvertToRadians(lat_1); + float lat_rad_2 = ConvertToRadians(lat_2); + float delta_lat_rad = ConvertToRadians(lat_2-lat_1); + float delta_lon_rad = ConvertToRadians(lon_2-lon_1); + + float a = pow(sin(delta_lat_rad/2), 2) + cos(lat_rad_1) * cos(lat_rad_2) * + pow(sin(delta_lon_rad/2), 2); + float c = 2 * atan2(sqrt(a), sqrt(1-a)); + int R = 6371000; // metres + + return R * c; +} + +void FillFeatureList(const std::string& db_path, std::vector* feature_list) { + if (db_path.empty()) { + return; + } + std::ifstream db_file(db_path); + if (!db_file.is_open()) { + std::cout << "Failed to open " << db_path << std::endl; + } + std::stringstream db; + db << db_file.rdbuf(); + ParseDb(db.str(), feature_list); +} + +std::string GetFeatureName(const Point& point, + const std::vector& feature_list) { + for (const Feature& f : feature_list) { + if (f.location().latitude() == point.latitude() && + f.location().longitude() == point.longitude()) { + return f.name(); + } + } + return ""; +} class RouteGuideImpl final : public RouteGuide::Service { + public: + RouteGuideImpl(const std::string& db_path) { + FillFeatureList(db_path, &feature_list_); + } + Status GetFeature(ServerContext* context, const Point* point, Feature* feature) override { + feature->set_name(GetFeatureName(*point, feature_list_)); + feature->mutable_location()->CopyFrom(*point); return Status::OK; } + Status ListFeatures(ServerContext* context, const Rectangle* rectangle, ServerWriter* writer) override { + auto lo = rectangle->lo(); + auto hi = rectangle->hi(); + long left = std::min(lo.longitude(), hi.longitude()); + long right = std::max(lo.longitude(), hi.longitude()); + long top = std::max(lo.latitude(), hi.latitude()); + long bottom = std::min(lo.latitude(), hi.latitude()); + for (const Feature& f : feature_list_) { + if (f.location().longitude() >= left && + f.location().longitude() <= right && + f.location().latitude() >= bottom && + f.location().latitude() <= top) { + writer->Write(f); + } + } return Status::OK; } + Status RecordRoute(ServerContext* context, ServerReader* reader, RouteSummary* summary) override { + Point point; + int point_count = 0; + int feature_count = 0; + float distance = 0.0; + Point previous; + + system_clock::time_point start_time = system_clock::now(); + while (reader->Read(&point)) { + point_count++; + if (!GetFeatureName(point, feature_list_).empty()) { + feature_count++; + } + if (point_count != 1) { + distance += GetDistance(previous, point); + } + previous = point; + } + system_clock::time_point end_time = system_clock::now(); + summary->set_point_count(point_count); + summary->set_feature_count(feature_count); + summary->set_distance(static_cast(distance)); + auto secs = std::chrono::duration_cast( + end_time - start_time); + summary->set_elapsed_time(secs.count()); + return Status::OK; } + Status RouteChat(ServerContext* context, ServerReaderWriter* stream) override { + std::vector received_notes; + RouteNote note; + while (stream->Read(¬e)) { + for (const RouteNote& n : received_notes) { + if (n.location().latitude() == note.location().latitude() && + n.location().longitude() == note.location().longitude()) { + stream->Write(n); + } + } + received_notes.push_back(note); + } + return Status::OK; } + + private: + + std::vector feature_list_; }; -void RunServer() { +void RunServer(const std::string& db_path) { std::string server_address("0.0.0.0:50051"); - RouteGuideImpl service; + RouteGuideImpl service(db_path); ServerBuilder builder; builder.AddPort(server_address); @@ -94,7 +218,20 @@ void RunServer() { int main(int argc, char** argv) { grpc_init(); - RunServer(); + std::string db_path; + std::string arg_str("--db_path"); + if (argc > 1) { + std::string argv_1 = argv[1]; + size_t start_position = argv_1.find(arg_str); + if (start_position != std::string::npos) { + start_position += arg_str.size(); + if (argv_1[start_position] == ' ' || + argv_1[start_position] == '=') { + db_path = argv_1.substr(start_position + 1); + } + } + } + RunServer(db_path); grpc_shutdown(); return 0; From 178fdf82e1538d3c2c34181cc66d7cb25d29096e Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 14:16:01 -0800 Subject: [PATCH 111/576] clean up a bit --- cpp/route_guide/Makefile | 4 +- cpp/route_guide/helper.cc | 73 +++++++++++++++++++++++++++ cpp/route_guide/helper.h | 50 ++++++++++++++++++ cpp/route_guide/route_guide_client.cc | 40 ++------------- cpp/route_guide/route_guide_server.cc | 43 +++------------- 5 files changed, 136 insertions(+), 74 deletions(-) create mode 100644 cpp/route_guide/helper.cc create mode 100644 cpp/route_guide/helper.h diff --git a/cpp/route_guide/Makefile b/cpp/route_guide/Makefile index fae9a9d284a..131956296cb 100644 --- a/cpp/route_guide/Makefile +++ b/cpp/route_guide/Makefile @@ -43,10 +43,10 @@ vpath %.proto $(PROTOS_PATH) all: system-check route_guide_client route_guide_server -route_guide_client: route_guide.pb.o route_guide_client.o +route_guide_client: route_guide.pb.o route_guide_client.o helper.o $(CXX) $^ $(LDFLAGS) -o $@ -route_guide_server: route_guide.pb.o route_guide_server.o +route_guide_server: route_guide.pb.o route_guide_server.o helper.o $(CXX) $^ $(LDFLAGS) -o $@ %.pb.cc: %.proto diff --git a/cpp/route_guide/helper.cc b/cpp/route_guide/helper.cc new file mode 100644 index 00000000000..a4be8bfc6c6 --- /dev/null +++ b/cpp/route_guide/helper.cc @@ -0,0 +1,73 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include +#include +#include +#include "route_guide.pb.h" + +namespace examples { + +std::string GetDbFileContent(int argc, char** argv) { + std::string db_path; + std::string arg_str("--db_path"); + if (argc > 1) { + std::string argv_1 = argv[1]; + size_t start_position = argv_1.find(arg_str); + if (start_position != std::string::npos) { + start_position += arg_str.size(); + if (argv_1[start_position] == ' ' || + argv_1[start_position] == '=') { + db_path = argv_1.substr(start_position + 1); + } + } + } + std::ifstream db_file(db_path); + if (!db_file.is_open()) { + std::cout << "Failed to open " << db_path << std::endl; + return ""; + } + std::stringstream db; + db << db_file.rdbuf(); + return db.str(); +} + +void ParseDb(const std::string& db, std::vector* feature_list) { + +} + + +} // namespace examples + diff --git a/cpp/route_guide/helper.h b/cpp/route_guide/helper.h new file mode 100644 index 00000000000..65c93c1d347 --- /dev/null +++ b/cpp/route_guide/helper.h @@ -0,0 +1,50 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_ +#define GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_ + +#include +#include + +namespace examples { +class Feature; + +std::string GetDbFileContent(int argc, char** argv); + +void ParseDb(const std::string& db, std::vector* feature_list); + +} // namespace examples + +#endif // GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_ + diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 8b4a5323271..fd3d98e30af 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -32,11 +32,9 @@ */ #include -#include #include #include #include -#include #include #include @@ -47,6 +45,7 @@ #include #include #include +#include "helper.h" #include "route_guide.pb.h" using grpc::ChannelArguments; @@ -86,23 +85,6 @@ RouteNote MakeRouteNote(const std::string& message, return n; } -bool ParseDb(const std::string& stream, std::vector* feature_list) { - // TODO -} - -void FillFeatureList(const std::string& db_path, std::vector* feature_list) { - if (db_path.empty()) { - return; - } - std::ifstream db_file(db_path); - if (!db_file.is_open()) { - std::cout << "Failed to open " << db_path << std::endl; - } - std::stringstream db; - db << db_file.rdbuf(); - ParseDb(db.str(), feature_list); -} - class RouteGuideClient { public: RouteGuideClient(std::shared_ptr channel) @@ -219,8 +201,8 @@ class RouteGuideClient { void Shutdown() { stub_.reset(); } - void FillFeatureList(const std::string& db_path) { - ::FillFeatureList(db_path, &feature_list_); + void FillFeatureList(const std::string& db) { + examples::ParseDb(db, &feature_list_); } private: @@ -258,20 +240,8 @@ int main(int argc, char** argv) { RouteGuideClient guide( grpc::CreateChannel("localhost:50051", ChannelArguments())); - std::string db_path; - std::string arg_str("--db_path"); - if (argc > 1) { - std::string argv_1 = argv[1]; - size_t start_position = argv_1.find(arg_str); - if (start_position != std::string::npos) { - start_position += arg_str.size(); - if (argv_1[start_position] == ' ' || - argv_1[start_position] == '=') { - db_path = argv_1.substr(start_position + 1); - } - } - } - guide.FillFeatureList(db_path); + std::string db = examples::GetDbFileContent(argc, argv); + guide.FillFeatureList(db); guide.GetFeature(); guide.ListFeatures(); diff --git a/cpp/route_guide/route_guide_server.cc b/cpp/route_guide/route_guide_server.cc index d4ecded69ba..38cd64be945 100644 --- a/cpp/route_guide/route_guide_server.cc +++ b/cpp/route_guide/route_guide_server.cc @@ -34,10 +34,8 @@ #include #include #include -#include #include #include -#include #include #include @@ -47,6 +45,7 @@ #include #include #include +#include "helper.h" #include "route_guide.pb.h" using grpc::Server; @@ -64,18 +63,13 @@ using examples::RouteNote; using examples::RouteGuide; using std::chrono::system_clock; -const float kCoordFactor = 10000000.0; - -bool ParseDb(const std::string& stream, std::vector* feature_list) { - // TODO -} float ConvertToRadians(float num) { return num * 3.1415926 /180; } float GetDistance(const Point& start, const Point& end) { - + const float kCoordFactor = 10000000.0; float lat_1 = start.latitude() / kCoordFactor; float lat_2 = end.latitude() / kCoordFactor; float lon_1 = start.longitude() / kCoordFactor; @@ -93,19 +87,6 @@ float GetDistance(const Point& start, const Point& end) { return R * c; } -void FillFeatureList(const std::string& db_path, std::vector* feature_list) { - if (db_path.empty()) { - return; - } - std::ifstream db_file(db_path); - if (!db_file.is_open()) { - std::cout << "Failed to open " << db_path << std::endl; - } - std::stringstream db; - db << db_file.rdbuf(); - ParseDb(db.str(), feature_list); -} - std::string GetFeatureName(const Point& point, const std::vector& feature_list) { for (const Feature& f : feature_list) { @@ -119,8 +100,8 @@ std::string GetFeatureName(const Point& point, class RouteGuideImpl final : public RouteGuide::Service { public: - RouteGuideImpl(const std::string& db_path) { - FillFeatureList(db_path, &feature_list_); + RouteGuideImpl(const std::string& db) { + examples::ParseDb(db, &feature_list_); } Status GetFeature(ServerContext* context, const Point* point, @@ -218,20 +199,8 @@ void RunServer(const std::string& db_path) { int main(int argc, char** argv) { grpc_init(); - std::string db_path; - std::string arg_str("--db_path"); - if (argc > 1) { - std::string argv_1 = argv[1]; - size_t start_position = argv_1.find(arg_str); - if (start_position != std::string::npos) { - start_position += arg_str.size(); - if (argv_1[start_position] == ' ' || - argv_1[start_position] == '=') { - db_path = argv_1.substr(start_position + 1); - } - } - } - RunServer(db_path); + std::string db = examples::GetDbFileContent(argc, argv); + RunServer(db); grpc_shutdown(); return 0; From dbc06dd84c80d0f2211f24d65d786367e140e1cb Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 14:26:28 -0800 Subject: [PATCH 112/576] more cleanup --- cpp/route_guide/helper.cc | 1 + cpp/route_guide/route_guide_client.cc | 17 ++++++++--------- cpp/route_guide/route_guide_server.cc | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cpp/route_guide/helper.cc b/cpp/route_guide/helper.cc index a4be8bfc6c6..8c04489837f 100644 --- a/cpp/route_guide/helper.cc +++ b/cpp/route_guide/helper.cc @@ -65,6 +65,7 @@ std::string GetDbFileContent(int argc, char** argv) { } void ParseDb(const std::string& db, std::vector* feature_list) { + feature_list->clear(); } diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index fd3d98e30af..01c48c9e16f 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -87,8 +87,11 @@ RouteNote MakeRouteNote(const std::string& message, class RouteGuideClient { public: - RouteGuideClient(std::shared_ptr channel) - : stub_(RouteGuide::NewStub(channel)) {} + RouteGuideClient(std::shared_ptr channel, + const std::string& db) + : stub_(RouteGuide::NewStub(channel)) { + examples::ParseDb(db, &feature_list_); + } void GetFeature() { Point point; @@ -201,10 +204,6 @@ class RouteGuideClient { void Shutdown() { stub_.reset(); } - void FillFeatureList(const std::string& db) { - examples::ParseDb(db, &feature_list_); - } - private: bool GetOneFeature(const Point& point, Feature* feature) { @@ -238,10 +237,10 @@ class RouteGuideClient { int main(int argc, char** argv) { grpc_init(); - RouteGuideClient guide( - grpc::CreateChannel("localhost:50051", ChannelArguments())); std::string db = examples::GetDbFileContent(argc, argv); - guide.FillFeatureList(db); + RouteGuideClient guide( + grpc::CreateChannel("localhost:50051", ChannelArguments()), + db); guide.GetFeature(); guide.ListFeatures(); diff --git a/cpp/route_guide/route_guide_server.cc b/cpp/route_guide/route_guide_server.cc index 38cd64be945..62fee245d08 100644 --- a/cpp/route_guide/route_guide_server.cc +++ b/cpp/route_guide/route_guide_server.cc @@ -100,7 +100,7 @@ std::string GetFeatureName(const Point& point, class RouteGuideImpl final : public RouteGuide::Service { public: - RouteGuideImpl(const std::string& db) { + explicit RouteGuideImpl(const std::string& db) { examples::ParseDb(db, &feature_list_); } From 9b7f104ee3ed7a7514f1aa887147df76497f585b Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 17:00:07 -0800 Subject: [PATCH 113/576] Add a simple parser --- cpp/route_guide/helper.cc | 102 +++++ cpp/route_guide/route_guide_db.json | 601 ++++++++++++++++++++++++++++ 2 files changed, 703 insertions(+) create mode 100644 cpp/route_guide/route_guide_db.json diff --git a/cpp/route_guide/helper.cc b/cpp/route_guide/helper.cc index 8c04489837f..3e104963176 100644 --- a/cpp/route_guide/helper.cc +++ b/cpp/route_guide/helper.cc @@ -31,6 +31,8 @@ * */ +#include +#include #include #include #include @@ -64,9 +66,109 @@ std::string GetDbFileContent(int argc, char** argv) { return db.str(); } +// A simple parser for the json db file. It requires the db file to have the +// exact form of [{"location": { "latitude": 123, "longitude": 456}, "name": +// "the name can be empty" }, { ... } ... The spaces will be stripped. +class Parser { + public: + explicit Parser(const std::string& db) : db_(db) { + // Remove all spaces. + db_.erase( + std::remove_if(db_.begin(), db_.end(), isspace), + db_.end()); + if (!Match("[")) { + SetFailedAndReturnFalse(); + } + } + + bool Finished() { + return current_ >= db_.size(); + } + + bool TryParseOne(Feature* feature) { + if (failed_ || Finished() || !Match("{")) { + return SetFailedAndReturnFalse(); + } + if (!Match(location_) || !Match("{") || !Match(latitude_)) { + return SetFailedAndReturnFalse(); + } + long temp = 0; + ReadLong(&temp); + feature->mutable_location()->set_latitude(temp); + if (!Match(",") || !Match(longitude_)) { + return SetFailedAndReturnFalse(); + } + ReadLong(&temp); + feature->mutable_location()->set_longitude(temp); + if (!Match("},") || !Match(name_) || !Match("\"")) { + return SetFailedAndReturnFalse(); + } + size_t name_start = current_; + while (current_ != db_.size() && db_[current_++] != '"') { + } + if (current_ == db_.size()) { + return SetFailedAndReturnFalse(); + } + feature->set_name(db_.substr(name_start, current_-name_start-1)); + if (!Match("},")) { + if (db_[current_ - 1] == ']' && current_ == db_.size()) { + return true; + } + return SetFailedAndReturnFalse(); + } + return true; + } + + private: + + bool SetFailedAndReturnFalse() { + failed_ = true; + return false; + } + + bool Match(const std::string& prefix) { + bool eq = db_.substr(current_, prefix.size()) == prefix; + current_ += prefix.size(); + return eq; + } + + void ReadLong(long* l) { + size_t start = current_; + while (current_ != db_.size() && db_[current_] != ',' && db_[current_] != '}') { + current_++; + } + // It will throw an exception if fails. + *l = std::stol(db_.substr(start, current_ - start)); + } + + bool failed_ = false; + std::string db_; + size_t current_ = 0; + const std::string location_ = "\"location\":"; + const std::string latitude_ = "\"latitude\":"; + const std::string longitude_ = "\"longitude\":"; + const std::string name_ = "\"name\":"; +}; + void ParseDb(const std::string& db, std::vector* feature_list) { feature_list->clear(); + std::string db_content(db); + db_content.erase( + std::remove_if(db_content.begin(), db_content.end(), isspace), + db_content.end()); + Parser parser(db_content); + Feature feature; + while (!parser.Finished()) { + feature_list->push_back(Feature()); + if (!parser.TryParseOne(&feature_list->back())) { + std::cout << "Error parsing the db file"; + feature_list->clear(); + break; + } + } + std::cout << "DB parsed, loaded " << feature_list->size() + << " features." << std::endl; } diff --git a/cpp/route_guide/route_guide_db.json b/cpp/route_guide/route_guide_db.json new file mode 100644 index 00000000000..9d6a980ab7d --- /dev/null +++ b/cpp/route_guide/route_guide_db.json @@ -0,0 +1,601 @@ +[{ + "location": { + "latitude": 407838351, + "longitude": -746143763 + }, + "name": "Patriots Path, Mendham, NJ 07945, USA" +}, { + "location": { + "latitude": 408122808, + "longitude": -743999179 + }, + "name": "101 New Jersey 10, Whippany, NJ 07981, USA" +}, { + "location": { + "latitude": 413628156, + "longitude": -749015468 + }, + "name": "U.S. 6, Shohola, PA 18458, USA" +}, { + "location": { + "latitude": 419999544, + "longitude": -740371136 + }, + "name": "5 Conners Road, Kingston, NY 12401, USA" +}, { + "location": { + "latitude": 414008389, + "longitude": -743951297 + }, + "name": "Mid Hudson Psychiatric Center, New Hampton, NY 10958, USA" +}, { + "location": { + "latitude": 419611318, + "longitude": -746524769 + }, + "name": "287 Flugertown Road, Livingston Manor, NY 12758, USA" +}, { + "location": { + "latitude": 406109563, + "longitude": -742186778 + }, + "name": "4001 Tremley Point Road, Linden, NJ 07036, USA" +}, { + "location": { + "latitude": 416802456, + "longitude": -742370183 + }, + "name": "352 South Mountain Road, Wallkill, NY 12589, USA" +}, { + "location": { + "latitude": 412950425, + "longitude": -741077389 + }, + "name": "Bailey Turn Road, Harriman, NY 10926, USA" +}, { + "location": { + "latitude": 412144655, + "longitude": -743949739 + }, + "name": "193-199 Wawayanda Road, Hewitt, NJ 07421, USA" +}, { + "location": { + "latitude": 415736605, + "longitude": -742847522 + }, + "name": "406-496 Ward Avenue, Pine Bush, NY 12566, USA" +}, { + "location": { + "latitude": 413843930, + "longitude": -740501726 + }, + "name": "162 Merrill Road, Highland Mills, NY 10930, USA" +}, { + "location": { + "latitude": 410873075, + "longitude": -744459023 + }, + "name": "Clinton Road, West Milford, NJ 07480, USA" +}, { + "location": { + "latitude": 412346009, + "longitude": -744026814 + }, + "name": "16 Old Brook Lane, Warwick, NY 10990, USA" +}, { + "location": { + "latitude": 402948455, + "longitude": -747903913 + }, + "name": "3 Drake Lane, Pennington, NJ 08534, USA" +}, { + "location": { + "latitude": 406337092, + "longitude": -740122226 + }, + "name": "6324 8th Avenue, Brooklyn, NY 11220, USA" +}, { + "location": { + "latitude": 406421967, + "longitude": -747727624 + }, + "name": "1 Merck Access Road, Whitehouse Station, NJ 08889, USA" +}, { + "location": { + "latitude": 416318082, + "longitude": -749677716 + }, + "name": "78-98 Schalck Road, Narrowsburg, NY 12764, USA" +}, { + "location": { + "latitude": 415301720, + "longitude": -748416257 + }, + "name": "282 Lakeview Drive Road, Highland Lake, NY 12743, USA" +}, { + "location": { + "latitude": 402647019, + "longitude": -747071791 + }, + "name": "330 Evelyn Avenue, Hamilton Township, NJ 08619, USA" +}, { + "location": { + "latitude": 412567807, + "longitude": -741058078 + }, + "name": "New York State Reference Route 987E, Southfields, NY 10975, USA" +}, { + "location": { + "latitude": 416855156, + "longitude": -744420597 + }, + "name": "103-271 Tempaloni Road, Ellenville, NY 12428, USA" +}, { + "location": { + "latitude": 404663628, + "longitude": -744820157 + }, + "name": "1300 Airport Road, North Brunswick Township, NJ 08902, USA" +}, { + "location": { + "latitude": 407113723, + "longitude": -749746483 + }, + "name": "" +}, { + "location": { + "latitude": 402133926, + "longitude": -743613249 + }, + "name": "" +}, { + "location": { + "latitude": 400273442, + "longitude": -741220915 + }, + "name": "" +}, { + "location": { + "latitude": 411236786, + "longitude": -744070769 + }, + "name": "" +}, { + "location": { + "latitude": 411633782, + "longitude": -746784970 + }, + "name": "211-225 Plains Road, Augusta, NJ 07822, USA" +}, { + "location": { + "latitude": 415830701, + "longitude": -742952812 + }, + "name": "" +}, { + "location": { + "latitude": 413447164, + "longitude": -748712898 + }, + "name": "165 Pedersen Ridge Road, Milford, PA 18337, USA" +}, { + "location": { + "latitude": 405047245, + "longitude": -749800722 + }, + "name": "100-122 Locktown Road, Frenchtown, NJ 08825, USA" +}, { + "location": { + "latitude": 418858923, + "longitude": -746156790 + }, + "name": "" +}, { + "location": { + "latitude": 417951888, + "longitude": -748484944 + }, + "name": "650-652 Willi Hill Road, Swan Lake, NY 12783, USA" +}, { + "location": { + "latitude": 407033786, + "longitude": -743977337 + }, + "name": "26 East 3rd Street, New Providence, NJ 07974, USA" +}, { + "location": { + "latitude": 417548014, + "longitude": -740075041 + }, + "name": "" +}, { + "location": { + "latitude": 410395868, + "longitude": -744972325 + }, + "name": "" +}, { + "location": { + "latitude": 404615353, + "longitude": -745129803 + }, + "name": "" +}, { + "location": { + "latitude": 406589790, + "longitude": -743560121 + }, + "name": "611 Lawrence Avenue, Westfield, NJ 07090, USA" +}, { + "location": { + "latitude": 414653148, + "longitude": -740477477 + }, + "name": "18 Lannis Avenue, New Windsor, NY 12553, USA" +}, { + "location": { + "latitude": 405957808, + "longitude": -743255336 + }, + "name": "82-104 Amherst Avenue, Colonia, NJ 07067, USA" +}, { + "location": { + "latitude": 411733589, + "longitude": -741648093 + }, + "name": "170 Seven Lakes Drive, Sloatsburg, NY 10974, USA" +}, { + "location": { + "latitude": 412676291, + "longitude": -742606606 + }, + "name": "1270 Lakes Road, Monroe, NY 10950, USA" +}, { + "location": { + "latitude": 409224445, + "longitude": -748286738 + }, + "name": "509-535 Alphano Road, Great Meadows, NJ 07838, USA" +}, { + "location": { + "latitude": 406523420, + "longitude": -742135517 + }, + "name": "652 Garden Street, Elizabeth, NJ 07202, USA" +}, { + "location": { + "latitude": 401827388, + "longitude": -740294537 + }, + "name": "349 Sea Spray Court, Neptune City, NJ 07753, USA" +}, { + "location": { + "latitude": 410564152, + "longitude": -743685054 + }, + "name": "13-17 Stanley Street, West Milford, NJ 07480, USA" +}, { + "location": { + "latitude": 408472324, + "longitude": -740726046 + }, + "name": "47 Industrial Avenue, Teterboro, NJ 07608, USA" +}, { + "location": { + "latitude": 412452168, + "longitude": -740214052 + }, + "name": "5 White Oak Lane, Stony Point, NY 10980, USA" +}, { + "location": { + "latitude": 409146138, + "longitude": -746188906 + }, + "name": "Berkshire Valley Management Area Trail, Jefferson, NJ, USA" +}, { + "location": { + "latitude": 404701380, + "longitude": -744781745 + }, + "name": "1007 Jersey Avenue, New Brunswick, NJ 08901, USA" +}, { + "location": { + "latitude": 409642566, + "longitude": -746017679 + }, + "name": "6 East Emerald Isle Drive, Lake Hopatcong, NJ 07849, USA" +}, { + "location": { + "latitude": 408031728, + "longitude": -748645385 + }, + "name": "1358-1474 New Jersey 57, Port Murray, NJ 07865, USA" +}, { + "location": { + "latitude": 413700272, + "longitude": -742135189 + }, + "name": "367 Prospect Road, Chester, NY 10918, USA" +}, { + "location": { + "latitude": 404310607, + "longitude": -740282632 + }, + "name": "10 Simon Lake Drive, Atlantic Highlands, NJ 07716, USA" +}, { + "location": { + "latitude": 409319800, + "longitude": -746201391 + }, + "name": "11 Ward Street, Mount Arlington, NJ 07856, USA" +}, { + "location": { + "latitude": 406685311, + "longitude": -742108603 + }, + "name": "300-398 Jefferson Avenue, Elizabeth, NJ 07201, USA" +}, { + "location": { + "latitude": 419018117, + "longitude": -749142781 + }, + "name": "43 Dreher Road, Roscoe, NY 12776, USA" +}, { + "location": { + "latitude": 412856162, + "longitude": -745148837 + }, + "name": "Swan Street, Pine Island, NY 10969, USA" +}, { + "location": { + "latitude": 416560744, + "longitude": -746721964 + }, + "name": "66 Pleasantview Avenue, Monticello, NY 12701, USA" +}, { + "location": { + "latitude": 405314270, + "longitude": -749836354 + }, + "name": "" +}, { + "location": { + "latitude": 414219548, + "longitude": -743327440 + }, + "name": "" +}, { + "location": { + "latitude": 415534177, + "longitude": -742900616 + }, + "name": "565 Winding Hills Road, Montgomery, NY 12549, USA" +}, { + "location": { + "latitude": 406898530, + "longitude": -749127080 + }, + "name": "231 Rocky Run Road, Glen Gardner, NJ 08826, USA" +}, { + "location": { + "latitude": 407586880, + "longitude": -741670168 + }, + "name": "100 Mount Pleasant Avenue, Newark, NJ 07104, USA" +}, { + "location": { + "latitude": 400106455, + "longitude": -742870190 + }, + "name": "517-521 Huntington Drive, Manchester Township, NJ 08759, USA" +}, { + "location": { + "latitude": 400066188, + "longitude": -746793294 + }, + "name": "" +}, { + "location": { + "latitude": 418803880, + "longitude": -744102673 + }, + "name": "40 Mountain Road, Napanoch, NY 12458, USA" +}, { + "location": { + "latitude": 414204288, + "longitude": -747895140 + }, + "name": "" +}, { + "location": { + "latitude": 414777405, + "longitude": -740615601 + }, + "name": "" +}, { + "location": { + "latitude": 415464475, + "longitude": -747175374 + }, + "name": "48 North Road, Forestburgh, NY 12777, USA" +}, { + "location": { + "latitude": 404062378, + "longitude": -746376177 + }, + "name": "" +}, { + "location": { + "latitude": 405688272, + "longitude": -749285130 + }, + "name": "" +}, { + "location": { + "latitude": 400342070, + "longitude": -748788996 + }, + "name": "" +}, { + "location": { + "latitude": 401809022, + "longitude": -744157964 + }, + "name": "" +}, { + "location": { + "latitude": 404226644, + "longitude": -740517141 + }, + "name": "9 Thompson Avenue, Leonardo, NJ 07737, USA" +}, { + "location": { + "latitude": 410322033, + "longitude": -747871659 + }, + "name": "" +}, { + "location": { + "latitude": 407100674, + "longitude": -747742727 + }, + "name": "" +}, { + "location": { + "latitude": 418811433, + "longitude": -741718005 + }, + "name": "213 Bush Road, Stone Ridge, NY 12484, USA" +}, { + "location": { + "latitude": 415034302, + "longitude": -743850945 + }, + "name": "" +}, { + "location": { + "latitude": 411349992, + "longitude": -743694161 + }, + "name": "" +}, { + "location": { + "latitude": 404839914, + "longitude": -744759616 + }, + "name": "1-17 Bergen Court, New Brunswick, NJ 08901, USA" +}, { + "location": { + "latitude": 414638017, + "longitude": -745957854 + }, + "name": "35 Oakland Valley Road, Cuddebackville, NY 12729, USA" +}, { + "location": { + "latitude": 412127800, + "longitude": -740173578 + }, + "name": "" +}, { + "location": { + "latitude": 401263460, + "longitude": -747964303 + }, + "name": "" +}, { + "location": { + "latitude": 412843391, + "longitude": -749086026 + }, + "name": "" +}, { + "location": { + "latitude": 418512773, + "longitude": -743067823 + }, + "name": "" +}, { + "location": { + "latitude": 404318328, + "longitude": -740835638 + }, + "name": "42-102 Main Street, Belford, NJ 07718, USA" +}, { + "location": { + "latitude": 419020746, + "longitude": -741172328 + }, + "name": "" +}, { + "location": { + "latitude": 404080723, + "longitude": -746119569 + }, + "name": "" +}, { + "location": { + "latitude": 401012643, + "longitude": -744035134 + }, + "name": "" +}, { + "location": { + "latitude": 404306372, + "longitude": -741079661 + }, + "name": "" +}, { + "location": { + "latitude": 403966326, + "longitude": -748519297 + }, + "name": "" +}, { + "location": { + "latitude": 405002031, + "longitude": -748407866 + }, + "name": "" +}, { + "location": { + "latitude": 409532885, + "longitude": -742200683 + }, + "name": "" +}, { + "location": { + "latitude": 416851321, + "longitude": -742674555 + }, + "name": "" +}, { + "location": { + "latitude": 406411633, + "longitude": -741722051 + }, + "name": "3387 Richmond Terrace, Staten Island, NY 10303, USA" +}, { + "location": { + "latitude": 413069058, + "longitude": -744597778 + }, + "name": "261 Van Sickle Road, Goshen, NY 10924, USA" +}, { + "location": { + "latitude": 418465462, + "longitude": -746859398 + }, + "name": "" +}, { + "location": { + "latitude": 411733222, + "longitude": -744228360 + }, + "name": "" +}, { + "location": { + "latitude": 410248224, + "longitude": -747127767 + }, + "name": "3 Hasta Way, Newton, NJ 07860, USA" +}] From bc69d72f91a6dbed2d665145859ca991db12ad1a Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Mon, 23 Feb 2015 19:15:09 -0800 Subject: [PATCH 114/576] Adds a quickstart README for java with working instructions --- java/README.md | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 java/README.md diff --git a/java/README.md b/java/README.md new file mode 100644 index 00000000000..8cd0e59896b --- /dev/null +++ b/java/README.md @@ -0,0 +1,59 @@ +gRPC in 3 minutes (Java) +======================== + +PREREQUISITES +------------- + +- [Java 8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) + +- [Maven 2.3](http://maven.apache.org/users/index.html). + - this is needed to install Netty5, a dependency of gRPC, and to build this sample + +- [Latest version of google-protobuf](https://github.com/google/protobuf/tree/master/java) + - to generate java code from proto files + - to install the base Java proto3 library + + +INSTALL +------- + +1 Clone the gRPC Java git repo +```sh +$ cd +$ git clone https://github.com/grpc/grpc-java +``` + +2 Install gRPC Java, as described in [How to Build](https://github.com/grpc/grpc-java#how-to-build) +```sh +$ # from this dir +$ cd grpc-java +$ # follow the instructions in 'How to Build' +``` + +3 Clone this repo, if you've not already done so. +```sh +$ cd +$ git clone https://github.com/grpc/grpc-common +$ cd grpc-common/java # switch to this directory +``` + +4 Build the samples +```sh +$ # from this directory +$ mvn package +``` + +TRY IT! +------- + +- Run the server +```sh +$ # from this directory +$ ./run_greeter_server.sh & +``` + +- Run the client +```sh +$ # from this directory +$ ./run_greeter_client.sh +``` From f65c93abde35c9999096812b60cb891eb965ef50 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 22:01:56 -0800 Subject: [PATCH 115/576] Add more logs --- cpp/route_guide/route_guide_client.cc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 01c48c9e16f..5fb1697934a 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -242,9 +242,13 @@ int main(int argc, char** argv) { grpc::CreateChannel("localhost:50051", ChannelArguments()), db); + std::cout << "-------------- GetFeature --------------" << std::endl; guide.GetFeature(); + std::cout << "-------------- ListFeatures --------------" << std::endl; guide.ListFeatures(); + std::cout << "-------------- RecordRoute --------------" << std::endl; guide.RecordRoute(); + std::cout << "-------------- RouteChat --------------" << std::endl; guide.RouteChat(); guide.Shutdown(); From 57d306e78ef329842d89bfe9a1aee6583241c0be Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 22:40:19 -0800 Subject: [PATCH 116/576] Sync-up API change and seed the random generator --- cpp/route_guide/route_guide_client.cc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 5fb1697934a..acb8dd489d2 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -135,7 +135,9 @@ class RouteGuideClient { RouteSummary stats; ClientContext context; const int kPoints = 10; - std::default_random_engine generator; + unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); + + std::default_random_engine generator(seed); std::uniform_int_distribution feature_distribution( 0, feature_list_.size() - 1); std::uniform_int_distribution delay_distribution( @@ -239,7 +241,7 @@ int main(int argc, char** argv) { std::string db = examples::GetDbFileContent(argc, argv); RouteGuideClient guide( - grpc::CreateChannel("localhost:50051", ChannelArguments()), + grpc::CreateChannelDeprecated("localhost:50051", ChannelArguments()), db); std::cout << "-------------- GetFeature --------------" << std::endl; From 9f392590bba5b517fc82f7b25b9de71c4c707d6b Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 22:51:14 -0800 Subject: [PATCH 117/576] Add default json path --- cpp/route_guide/helper.cc | 2 ++ cpp/route_guide/route_guide_client.cc | 1 + cpp/route_guide/route_guide_server.cc | 1 + 3 files changed, 4 insertions(+) diff --git a/cpp/route_guide/helper.cc b/cpp/route_guide/helper.cc index 3e104963176..d1478464636 100644 --- a/cpp/route_guide/helper.cc +++ b/cpp/route_guide/helper.cc @@ -55,6 +55,8 @@ std::string GetDbFileContent(int argc, char** argv) { db_path = argv_1.substr(start_position + 1); } } + } else { + db_path = "route_guide_db.json"; } std::ifstream db_file(db_path); if (!db_file.is_open()) { diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index acb8dd489d2..cbf420780d6 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -239,6 +239,7 @@ class RouteGuideClient { int main(int argc, char** argv) { grpc_init(); + // Expect only arg: --db_path=path/to/route_guide_db.json. std::string db = examples::GetDbFileContent(argc, argv); RouteGuideClient guide( grpc::CreateChannelDeprecated("localhost:50051", ChannelArguments()), diff --git a/cpp/route_guide/route_guide_server.cc b/cpp/route_guide/route_guide_server.cc index 62fee245d08..2699330e4c6 100644 --- a/cpp/route_guide/route_guide_server.cc +++ b/cpp/route_guide/route_guide_server.cc @@ -199,6 +199,7 @@ void RunServer(const std::string& db_path) { int main(int argc, char** argv) { grpc_init(); + // Expect only arg: --db_path=path/to/route_guide_db.json. std::string db = examples::GetDbFileContent(argc, argv); RunServer(db); From 7c968086a99e3eff9d0bb1604f7a63600e606309 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Mon, 23 Feb 2015 22:59:58 -0800 Subject: [PATCH 118/576] CreateChannel API change syncup and regenerate files --- cpp/helloworld/greeter_client.cc | 2 +- cpp/helloworld/helloworld.pb.cc | 8 ++++---- cpp/helloworld/helloworld.pb.h | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cpp/helloworld/greeter_client.cc b/cpp/helloworld/greeter_client.cc index 3c2bbc20747..0eb4746c65b 100644 --- a/cpp/helloworld/greeter_client.cc +++ b/cpp/helloworld/greeter_client.cc @@ -80,7 +80,7 @@ int main(int argc, char** argv) { grpc_init(); GreeterClient greeter( - grpc::CreateChannel("localhost:50051", ChannelArguments())); + grpc::CreateChannelDeprecated("localhost:50051", ChannelArguments())); std::string user("world"); std::string reply = greeter.SayHello(user); std::cout << "Greeter received: " << reply << std::endl; diff --git a/cpp/helloworld/helloworld.pb.cc b/cpp/helloworld/helloworld.pb.cc index 9540f2c94c1..3675f5f857e 100644 --- a/cpp/helloworld/helloworld.pb.cc +++ b/cpp/helloworld/helloworld.pb.cc @@ -590,8 +590,8 @@ static const char* Greeter_method_names[] = { "/helloworld.Greeter/SayHello", }; -Greeter::Stub* Greeter::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) { - Greeter::Stub* stub = new Greeter::Stub(); +std::unique_ptr< Greeter::Stub> Greeter::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) { + std::unique_ptr< Greeter::Stub> stub(new Greeter::Stub()); stub->set_channel(channel); return stub; }; @@ -600,8 +600,8 @@ Greeter::Stub* Greeter::NewStub(const std::shared_ptr< ::grpc::ChannelInterface> return ::grpc::BlockingUnaryCall(channel(),::grpc::RpcMethod(Greeter_method_names[0]), context, request, response); } -::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* Greeter::Stub::SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag) { - return new ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>(channel(), cq, ::grpc::RpcMethod(Greeter_method_names[0]), context, request, tag); +std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>> Greeter::Stub::SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>>(new ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>(channel(), cq, ::grpc::RpcMethod(Greeter_method_names[0]), context, request, tag)); } Greeter::AsyncService::AsyncService(::grpc::CompletionQueue* cq) : ::grpc::AsynchronousService(cq, Greeter_method_names, 1) {} diff --git a/cpp/helloworld/helloworld.pb.h b/cpp/helloworld/helloworld.pb.h index 1eb870166af..67ec7a29692 100644 --- a/cpp/helloworld/helloworld.pb.h +++ b/cpp/helloworld/helloworld.pb.h @@ -320,9 +320,9 @@ class Greeter final { class Stub final : public ::grpc::InternalStub { public: ::grpc::Status SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response); - ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>* SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag); + std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::helloworld::HelloReply>> SayHello(::grpc::ClientContext* context, const ::helloworld::HelloRequest& request, ::grpc::CompletionQueue* cq, void* tag); }; - static Stub* NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); class Service : public ::grpc::SynchronousService { public: From c23768547439d67dc41390635bc824b187738f26 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Tue, 24 Feb 2015 10:18:50 +0000 Subject: [PATCH 119/576] Update README.md Added link to golang/protobuf repo --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a1a3c4b9733..92377b04b25 100644 --- a/README.md +++ b/README.md @@ -66,10 +66,9 @@ While protocol buffers have been available for open source users for some time, our examples use a new flavour of protocol buffers called proto3, which has a slightly simplified syntax, some useful new features, and supports lots more languages. This is currently available as an alpha release in -Java, C++ from [the protocol buffers Github +Java, C++, Java_nano (Android Java), Python, and Ruby from [the protocol buffers Github repo](https://github.com/google/protobuf/releases), as well as a Go language -generator [wherever that is](), with more languages in development. Full -documentation for proto3 is currently in development but you can see +generator from [the golang/protobuf Github repo](https://github.com/golang/protobuf), with more languages in development. Full documentation for proto3 is currently in development, but you can see the major differences from the current default version in the [release notes](https://github.com/google/protobuf/releases). In general, we recommend that you use proto3 with gRPC as it lets you use the From 2eadf58ab63a4ddfa7a4a82a32feda448cfb2e03 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Tue, 24 Feb 2015 10:20:33 +0000 Subject: [PATCH 120/576] Update README.md --- README.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 92377b04b25..acea9289a7a 100644 --- a/README.md +++ b/README.md @@ -71,15 +71,8 @@ repo](https://github.com/google/protobuf/releases), as well as a Go language generator from [the golang/protobuf Github repo](https://github.com/golang/protobuf), with more languages in development. Full documentation for proto3 is currently in development, but you can see the major differences from the current default version in the [release notes](https://github.com/google/protobuf/releases). -In general, we recommend that you use proto3 with gRPC as it lets you use the -full range of gRPC-supported languages, as well as avoiding compatibility -issues with proto2 clients talking to proto3 servers and vice versa. You -can find out more about these potential issues in [where should we put this -info? It's important but not really part of an overview]. If you need to -continue using proto2 for Java, C++, or Python but want -to try gRPC, you can see an example using a proto2 gRPC client and server -[wherever we put it]. - +In general, while you *can* use proto2 (the current default protocol buffers version), we recommend that you use proto3 with gRPC as it lets you use the full range of gRPC-supported languages, as well as avoiding compatibility +issues with proto2 clients talking to proto3 servers and vice versa. ## Hello gRPC! From 21b7fd30cb5a9bcbc6f15bf7fc5ea8a0c78a493d Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 03:58:40 -0800 Subject: [PATCH 121/576] Fixed Maven version --- java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/README.md b/java/README.md index 8cd0e59896b..35c9db31927 100644 --- a/java/README.md +++ b/java/README.md @@ -6,7 +6,7 @@ PREREQUISITES - [Java 8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) -- [Maven 2.3](http://maven.apache.org/users/index.html). +- [Maven 3.2](http://maven.apache.org/users/index.html). - this is needed to install Netty5, a dependency of gRPC, and to build this sample - [Latest version of google-protobuf](https://github.com/google/protobuf/tree/master/java) From f3e73a487129c1a971aa7e298a9433c6e60befeb Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 04:09:51 -0800 Subject: [PATCH 122/576] Updates the Node.js README to match the common template --- node/README.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/node/README.md b/node/README.md index 57dc83ee3f3..f9df3b0a81d 100644 --- a/node/README.md +++ b/node/README.md @@ -1,17 +1,21 @@ -# gRPC Node.js Helloworld +gRPC in 3 minutes (Node.js) +=========================== -## INSTALLATION REQUIREMENTS +PREREQUISITES +------------- This requires Node 10.x or greater. -## INSTALL +INSTALL +------- - Clone this repository - Follow the instructions in [INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL) to install the gRPC C core. - Run `npm install` to install dependencies - If `grpc` is not found, clone the [gRPC](https://github.com/grpc/grpc) repository and run `npm install path/to/grpc/src/node`. -## USAGE +Try it! +------- - Run the server @@ -27,7 +31,8 @@ This requires Node 10.x or greater. $ nodejs ./greeter_client.js ``` -## NOTE +Note +---- This directory has a copy of `helloworld.proto` because it currently depends on some Protocol Buffer 2.0 syntax that is deprecated in Protocol Buffer 3.0. From 43f3841063f56455b3db0ab3c6fb0cdbcd8c2521 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 07:42:14 -0800 Subject: [PATCH 123/576] rename the gem to reflect the fact that it contains two samples --- ruby/{greeter.gemspec => grpc-demo.gemspec} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename ruby/{greeter.gemspec => grpc-demo.gemspec} (82%) diff --git a/ruby/greeter.gemspec b/ruby/grpc-demo.gemspec similarity index 82% rename from ruby/greeter.gemspec rename to ruby/grpc-demo.gemspec index 795c84c0f5f..d4e2ec7a266 100644 --- a/ruby/greeter.gemspec +++ b/ruby/grpc-demo.gemspec @@ -2,7 +2,7 @@ # encoding: utf-8 Gem::Specification.new do |s| - s.name = 'grpc-greeter' + s.name = 'grpc-demo' s.version = '0.1.0' s.authors = ['gRPC Authors'] s.email = 'temiola@google.com' @@ -11,7 +11,7 @@ Gem::Specification.new do |s| s.description = 'Simple demo of using gRPC from Ruby' s.files = `git ls-files -- ruby/*`.split("\n") - s.executables = `git ls-files -- ruby/greeter*.rb`.split("\n").map do |f| + s.executables = `git ls-files -- ruby/*client.rb ruby/*server.rb`.split("\n").map do |f| File.basename(f) end s.require_paths = ['lib'] From 56dff9f757f5b36ffa7073a7bd22acc968bcee74 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 07:43:10 -0800 Subject: [PATCH 124/576] Adds the generated code for the route_guide example --- ruby/lib/route_guide.rb | 37 ++++++++++++++++++++++++++++++++ ruby/lib/route_guide_services.rb | 27 +++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 ruby/lib/route_guide.rb create mode 100644 ruby/lib/route_guide_services.rb diff --git a/ruby/lib/route_guide.rb b/ruby/lib/route_guide.rb new file mode 100644 index 00000000000..98bac8395ce --- /dev/null +++ b/ruby/lib/route_guide.rb @@ -0,0 +1,37 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: route_guide.proto + +require 'google/protobuf' + +Google::Protobuf::DescriptorPool.generated_pool.build do + add_message "examples.Point" do + optional :latitude, :int32, 1 + optional :longitude, :int32, 2 + end + add_message "examples.Rectangle" do + optional :lo, :message, 1, "examples.Point" + optional :hi, :message, 2, "examples.Point" + end + add_message "examples.Feature" do + optional :name, :string, 1 + optional :location, :message, 2, "examples.Point" + end + add_message "examples.RouteNote" do + optional :location, :message, 1, "examples.Point" + optional :message, :string, 2 + end + add_message "examples.RouteSummary" do + optional :point_count, :int32, 1 + optional :feature_count, :int32, 2 + optional :distance, :int32, 3 + optional :elapsed_time, :int32, 4 + end +end + +module Examples + Point = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.Point").msgclass + Rectangle = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.Rectangle").msgclass + Feature = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.Feature").msgclass + RouteNote = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.RouteNote").msgclass + RouteSummary = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.RouteSummary").msgclass +end diff --git a/ruby/lib/route_guide_services.rb b/ruby/lib/route_guide_services.rb new file mode 100644 index 00000000000..6e07653c425 --- /dev/null +++ b/ruby/lib/route_guide_services.rb @@ -0,0 +1,27 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# Source: route_guide.proto for package 'examples' + +require 'grpc' +require 'route_guide' + +module Examples + module RouteGuide + + # TODO: add proto service documentation here + class Service + + include GRPC::GenericService + + self.marshal_class_method = :encode + self.unmarshal_class_method = :decode + self.service_name = 'examples.RouteGuide' + + rpc :GetFeature, Point, Feature + rpc :ListFeatures, Rectangle, stream(Feature) + rpc :RecordRoute, stream(Point), RouteSummary + rpc :RouteChat, stream(RouteNote), stream(RouteNote) + end + + Stub = Service.rpc_stub_class + end +end From 14184fafc99d858786766f5c3d3e22123cab87af Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 24 Feb 2015 16:56:30 +0000 Subject: [PATCH 125/576] First go of service and client impl stuff --- cpp/cpptutorial.md | 179 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 173 insertions(+), 6 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 21026781638..8fa1b6df65a 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -30,7 +30,7 @@ Then change your current directory to `grpc-common/cpp/route_guide`: $ cd grpc-common/cpp/route_guide ``` -Although we've provided the complete example so you don't need to generate the gRPC code yourself, if you want to try generating your own server and client interface code you can follow the setup instructions for the C++ gRPC libraries in [grpc/grpc/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL). +Although we've provided the complete example so you don't need to generate the gRPC code yourself, if you want to try generating your own server and client interface code you can follow the setup instructions in [the C++ quick start guide](https://github.com/grpc/grpc-common/tree/master/cpp). ## Defining the service @@ -93,7 +93,7 @@ message Point { Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC C++ plugin. -For simplicity, we've provided a [makefile](https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/Makefile) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've followed the [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first): +For simplicity, we've provided a [makefile](https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/Makefile) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first): ```shell $ make route_guide.pb.cc @@ -109,22 +109,189 @@ Running this command generates the following files: These contain: - All the protocol buffer code to populate, serialize, and retrieve our request and response message types -- A class called `RouteGuide` that contains both a remote interface type (or *stub*) for clients to call and an abstract interface for servers to implement, both with the methods defined in the `RouteGuide` service. +- A class called `RouteGuide` that contains + - a remote interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service. + - two abstract interfaces for servers to implement, also with the methods defined in the `RouteGuide` service. + ## Creating the server -First let's look at how we create a `RouteGuide` server. +First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!). -There are two parts to making our `RouteGuide` service work: +There are two parts to making our `RouteGuide` service do its job: - Implementing the service interface generated from our service definition: doing the actual "work" of our service. -- Running a gRPC server to listen for requests from clients and return the service responses +- Running a gRPC server to listen for requests from clients and return the service responses. +You can find our example `RouteGuide` server in [grpc-common/cpp/route_guide/route_guide_server.cc]((https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/route_guide_server.cc). Let's take a closer look at how it works. +### Implementing RouteGuide + +As you can see, our server has a `RouteGuideImpl` class that implements the generated `RouteGuide::Service` interface: + +```cpp +class RouteGuideImpl final : public RouteGuide::Service { +... +} +``` +In this case we're implementing the *synchronous* version of `RouteGuide`, where... It's also possible to implement an asynchronous interface, `RouteGuide::AsyncService`... + +`RouteGuideImpl` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. + +```cpp + Status GetFeature(ServerContext* context, const Point* point, + Feature* feature) override { + feature->set_name(GetFeatureName(*point, feature_list_)); + feature->mutable_location()->CopyFrom(*point); + return Status::OK; + } +``` + +The method is passed a context object for the RPC, the client's `Point` protocol buffer request, and a `Feature` protocol buffer to fill in with the response information. In the method we populate the `Feature` with the appropriate information, and then `return` with an `OK` status to tell gRPC that we've finished dealing with the RPC and that the `Feature` can be returned to the client. + +Now let's look at something a bit more complicated - a streaming RPC. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. + +```cpp + Status ListFeatures(ServerContext* context, const Rectangle* rectangle, + ServerWriter* writer) override { + auto lo = rectangle->lo(); + auto hi = rectangle->hi(); + long left = std::min(lo.longitude(), hi.longitude()); + long right = std::max(lo.longitude(), hi.longitude()); + long top = std::max(lo.latitude(), hi.latitude()); + long bottom = std::min(lo.latitude(), hi.latitude()); + for (const Feature& f : feature_list_) { + if (f.location().longitude() >= left && + f.location().longitude() <= right && + f.location().latitude() >= bottom && + f.location().latitude() <= top) { + writer->Write(f); + } + } + return Status::OK; + } +``` + +As you can see, instead of getting simple request and response objects in our method parameters, this time we get a request object (the `Rectangle` in which our client wants to find `Feature`s) and a special `ServerWriter` object. In the method, we populate as many `Feature` objects as we need to return, writing them to the `ServerWriter` using its `Write()` method. Finally, as in our simple RPC, we `return Status::OK` to tell gRPC that we've finished writing responses. + +If you look at the client-side streaming method `RecordRoute` you'll see it's quite similar, except this time we get a `ServerReader` instead of a request object and a single response. We use the `ServerReader`s `Read()` method to repeatedly read in our client's requests to a request object (in this case a `Point`) until there are no more messages: the server needs to check the return value of `Read()` after each call. If `true`, the stream is still good and it can continue reading; if `false` the message stream has ended. + +```cpp +while (stream->Read(&point)) { + ...//process client input +} +``` +Finally, let's look at our bidirectional streaming RPC `RouteChat()`. + +```cpp + Status RouteChat(ServerContext* context, + ServerReaderWriter* stream) override { + std::vector received_notes; + RouteNote note; + while (stream->Read(¬e)) { + for (const RouteNote& n : received_notes) { + if (n.location().latitude() == note.location().latitude() && + n.location().longitude() == note.location().longitude()) { + stream->Write(n); + } + } + received_notes.push_back(note); + } + + return Status::OK; + } +``` + +This time we get a `ServerReaderWriter` that can be used to read *and* write messages. The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. + +### Starting the server + +Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service: + +```cpp +void RunServer(const std::string& db_path) { + std::string server_address("0.0.0.0:50051"); + RouteGuideImpl service(db_path); + + ServerBuilder builder; + builder.AddPort(server_address); + builder.RegisterService(&service); + std::unique_ptr server(builder.BuildAndStart()); + std::cout << "Server listening on " << server_address << std::endl; + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(5)); + } +} +``` +As you can see, we build and start our server using a `ServerBuilder`. To do this, we: + +1. Create an instance of our service implementation class `RouteGuideImpl`. +2. Create an instance of the factory `ServerBuilder` class. +3. Specify the address and port we want to use to listen for client requests using the builder's `AddPort()` method. +4. Register our service implementation with the builder. +5. Call `BuildAndStart()` on the builder to create and start an RPC server for our service. + +_[is there no equivalent of the Stubby4 wait() method, ie do you have to do the while(true) loop to keep the server running?]_ + + ## Creating the client +In this section, we'll look at creating a C++ client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/cpp/route_guide/route_guide_client.cc]((https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/route_guide_client.cc). + +### Creating a stub + +To call service methods, we first need to create a *stub*. + +First we need to create a gRPC *channel* for our stub, specifying the server address and port we want to connect to and any special channel arguments - in our case we'll use the default `ChannelArguments`: + +```cpp +grpc::CreateChannelDeprecated("localhost:50051", ChannelArguments()); +``` + +Now we can use the channel to create our stub using the `NewStub` method provided in the `RouteGuide` class we generated from our .proto. + +```cpp + public: + RouteGuideClient(std::shared_ptr channel, + const std::string& db) + : stub_(RouteGuide::NewStub(channel)) { + ... + } +``` + +### Calling service methods + +Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method. + +```cpp + Point point; + Feature feature; + point = MakePoint(409146138, -746188906); + GetOneFeature(point, &feature); + +... + + bool GetOneFeature(const Point& point, Feature* feature) { + ClientContext context; + Status status = stub_->GetFeature(&context, point, feature); + ... + } +``` + +As you can see, you create and populate a request protocol buffer object (in our case `Point`), and create a response protocol buffer object for the server to fill in. You also create a `ClientContext` object for your call. Finally, you call the method on the stub, passing it the context, request, and response. If the method returns `OK`, then you can read your response information from the server from your response object. + +```cpp + std::cout << "Found feature called " << feature->name() << " at " + << feature->location().latitude()/kCoordFactor_ << ", " + << feature->location().longitude()/kCoordFactor_ << std::endl; +``` + +Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. + +## Try it out! +_[need build and run instructions here]_ From 18e24c8cca29d3864f9cf6bc75d6041cec915a85 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Tue, 24 Feb 2015 09:19:31 -0800 Subject: [PATCH 126/576] Create AUTH.md An overview auth document using c++ code exampoles. The code will be translated to other languages in subsequet pull requests. --- AUTH.md | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 AUTH.md diff --git a/AUTH.md b/AUTH.md new file mode 100644 index 00000000000..9850b8b24ef --- /dev/null +++ b/AUTH.md @@ -0,0 +1,88 @@ +#gRPC Authentication support + +gRPC is designed to plug-in a number of authentication mechanisms. We provide an overview +of the various auth mechanisms supported, discuss the API and demonstrate usage through +code examples, and conclude with a discussion of extensibility. + +###SSL/TLS +gRPC has SSL/TLS integration and promotes the use of SSL/TLS to authenticate the server, +and encrypt all the data exchanged between the client and the server. Optional +mechanisms are available for clients to provide certificates to accomplish mutual +authentication. + +###OAuth 2.0 +gRPC provides a generic mechanism (described below) to attach metadata to requests +and responses. This mechanism can be used to attach OAuth 2.0 Access Tokens to +RPCs being made at a client. Additional support for acquiring Access Tokens while +accessing Google APIs through gRPC is provided for certain auth flows, demonstrated +through code examples below. + +###API +To reduce complexity and minimize API clutter, gRPC works with a unified concept of +a Credentials object. Users construct gRPC credentials using corresponding bootstrap +credentials (e.g., SSL client certs or Service Account Keys), and use the +credentials while creating a gRPC channel to any server. Depending on the type of +credential supplied, the channel uses the credentials during the initial SSL/TLS +handshake with the server, or uses the credential to generate and attach Access +Tokens to each request being made on the channel. + +###Code Examples + +####SSL/TLS for server authentication and encryption +This is the simplest authentication scenario, where a client just wants to +authenticate the server and encrypt all data. + +``` +SslCredentialsOptions ssl_opts; // Options to override SSL params, empty by default +// Create the credentials object by providing service account key in constructor +std::unique_ptr creds = CredentialsFactory::SslCredentials(ssl_opts); +// Create a channel using the credentials created in the previous step +std::shared_ptr channel = CreateChannel(server_name, creds, channel_args); +// Create a stub on the channel +std::unique_ptr stub(Greeter::NewStub(channel)); +// Make actual RPC calls on the stub. +grpc::Status s = stub->sayHello(&context, *request, response); +``` + +For advanced use cases such as modifying the root CA or using client certs, +the corresponding options can be set in the SslCredentialsOptions parameter +passed to the factory method. + + +###Authenticating with Google + +gRPC applications can use a simple API to create a credential that works in various deployment scenarios. + +``` +std::unique_ptr creds = CredentialsFactory::DefaultGoogleCredentials(); +// Create a channel, stub and make RPC calls (same as in the previous example) +std::shared_ptr channel = CreateChannel(server_name, creds, channel_args); +std::unique_ptr stub(Greeter::NewStub(channel)); +grpc::Status s = stub->sayHello(&context, *request, response); +``` + +This credential works for applications using Service Accounts as well as for +applications running in Google Compute Engine (GCE). In the former case, the +service account’s private keys are expected in file located at [TODO: well +known file fath for service account keys] or in the file named in the environment +variable [TODO: add the env var name here]. The keys are used at run-time to +generate bearer tokens that are attached to each outgoing RPC on the +corresponding channel. + +For applications running in GCE, a default service account and corresponding +OAuth scopes can be configured during VM setup. At run-time, this credential +handles communication with the authentication systems to obtain OAuth2 access +tokens and attaches them to each outgoing RPC on the corresponding channel. +Extending gRPC to support other authentication mechanisms +The gRPC protocol is designed with a general mechanism for sending metadata +associated with RPC. Clients can send metadata at the beginning of an RPC and +servers can send back metadata at the beginning and end of the RPC. This +provides a natural mechanism to support OAuth2 and other authentication +mechanisms that need attach bearer tokens to individual request. + +In the simplest case, there is a single line of code required on the client +to add a specific token as metadata to an RPC and a corresponding access on +the server to retrieve this piece of metadata. The generation of the token +on the client side and its verification at the server can be done separately. + +A deeper integration can be achieved by plugging in a gRPC credentials implementation for any custom authentication mechanism that needs to attach per-request tokens. gRPC internals also allow switching out SSL/TLS with other encryption mechanisms. From fea9152c99566fd7ac8e471c63e0111efe455e01 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 24 Feb 2015 18:07:45 +0000 Subject: [PATCH 127/576] Finished client side --- cpp/cpptutorial.md | 62 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 8fa1b6df65a..2c9eea68ccc 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -134,7 +134,7 @@ class RouteGuideImpl final : public RouteGuide::Service { ... } ``` -In this case we're implementing the *synchronous* version of `RouteGuide`, where... It's also possible to implement an asynchronous interface, `RouteGuide::AsyncService`... +In this case we're implementing the *synchronous* version of `RouteGuide`, which provides our default gRPC server behaviour. It's also possible to implement an asynchronous interface, `RouteGuide::AsyncService`, which allows you to further customize your server's threading behaviour, though we won't look at this in this tutorial. `RouteGuideImpl` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. @@ -261,6 +261,8 @@ Now we can use the channel to create our stub using the `NewStub` method provide ### Calling service methods +Now let's look at how we call our service methods. Note that in this tutorial we're calling the *blocking/synchronous* versions of each method: this means that the RPC call waits for the server to respond, and will either return a response or raise an exception. + Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method. ```cpp @@ -278,7 +280,7 @@ Calling the simple RPC `GetFeature` is nearly as straightforward as calling a lo } ``` -As you can see, you create and populate a request protocol buffer object (in our case `Point`), and create a response protocol buffer object for the server to fill in. You also create a `ClientContext` object for your call. Finally, you call the method on the stub, passing it the context, request, and response. If the method returns `OK`, then you can read your response information from the server from your response object. +As you can see, we create and populate a request protocol buffer object (in our case `Point`), and create a response protocol buffer object for the server to fill in. We also create a `ClientContext` object for our call - you can optionally set RPC configuration values on this object, such as deadlines, though for now we'll use the default settings. Note that you cannot reuse this object between calls. Finally, we call the method on the stub, passing it the context, request, and response. If the method returns `OK`, then we can read the response information from the server from our response object. ```cpp std::cout << "Found feature called " << feature->name() << " at " @@ -286,8 +288,62 @@ As you can see, you create and populate a request protocol buffer object (in our << feature->location().longitude()/kCoordFactor_ << std::endl; ``` -Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. +Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s: + +```cpp + std::unique_ptr > reader( + stub_->ListFeatures(&context, rect)); + while (reader->Read(&feature)) { + std::cout << "Found feature called " + << feature.name() << " at " + << feature.location().latitude()/kCoordFactor_ << ", " + << feature.location().latitude()/kCoordFactor_ << std::endl; + } + Status status = reader->Finish(); +``` + +Instead of passing the method a context, request, and response, we pass it a context and request and get a `ClientReader` object back. The client can use the `ClientReader` to read the server's responses. We use the `ClientReader`s `Read()` method to repeatedly read in the server's responses to a response protocol buffer object (in this case a `Feature`) until there are no more messages: the client needs to check the return value of `Read()` after each call. If `true`, the stream is still good and it can continue reading; if `false` the message stream has ended. Finally, we call `Finish()` on the stream to complete the call and get our RPC status. + +The client-side streaming method `RecordRoute` is similar, except there we pass the method a context and response object and get back a `ClientWriter`. + +```cpp + std::unique_ptr > writer( + stub_->RecordRoute(&context, &stats)); + for (int i = 0; i < kPoints; i++) { + const Feature& f = feature_list_[feature_distribution(generator)]; + std::cout << "Visiting point " + << f.location().latitude()/kCoordFactor_ << ", " + << f.location().longitude()/kCoordFactor_ << std::endl; + if (!writer->Write(f.location())) { + // Broken stream. + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds( + delay_distribution(generator))); + } + writer->WritesDone(); + Status status = writer->Finish(); + if (status.IsOk()) { + std::cout << "Finished trip with " << stats.point_count() << " points\n" + << "Passed " << stats.feature_count() << " features\n" + << "Travelled " << stats.distance() << " meters\n" + << "It took " << stats.elapsed_time() << " seconds" + << std::endl; + } else { + std::cout << "RecordRoute rpc failed." << std::endl; + } +``` + +Once we've finished writing our client's requests to the stream using `Write()`, we need to call `WritesDone()` on the stream to let gRPC know that we've finished writing, then `Finish()` to complete the call and get our RPC status. If the status is `OK`, our response object that we initially passed to `RecordRoute()` will be populated with the server's response. + +Finally, let's look at our bidirectional streaming RPC `RouteChat()`. In this case, we just pass a context to the method and get back a `ClientReaderWriter`, which we can use to both write and read messages. + +```cpp + std::shared_ptr > stream( + stub_->RouteChat(&context)); +``` +The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. ## Try it out! From 88a49f65d05e51eeedb33341800fbe3576dff097 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 24 Feb 2015 18:09:38 +0000 Subject: [PATCH 128/576] Added a couple more headings --- cpp/cpptutorial.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 2c9eea68ccc..069ca4ea093 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -263,6 +263,8 @@ Now we can use the channel to create our stub using the `NewStub` method provide Now let's look at how we call our service methods. Note that in this tutorial we're calling the *blocking/synchronous* versions of each method: this means that the RPC call waits for the server to respond, and will either return a response or raise an exception. +#### Simple RPC + Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method. ```cpp @@ -288,6 +290,8 @@ As you can see, we create and populate a request protocol buffer object (in our << feature->location().longitude()/kCoordFactor_ << std::endl; ``` +#### Streaming RPCs + Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s: ```cpp From f0db7b70f39c3c61d258c610704680177997041a Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Tue, 24 Feb 2015 18:10:40 +0000 Subject: [PATCH 129/576] Fixed typo --- cpp/cpptutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 069ca4ea093..af6b6b1a65f 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -236,7 +236,7 @@ _[is there no equivalent of the Stubby4 wait() method, ie do you have to do the ## Creating the client -In this section, we'll look at creating a C++ client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/cpp/route_guide/route_guide_client.cc]((https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/route_guide_client.cc). +In this section, we'll look at creating a C++ client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/cpp/route_guide/route_guide_client.cc](https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/route_guide_client.cc). ### Creating a stub From d475445b1b192aae2d1d1ee279b76f38e5946e65 Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Tue, 24 Feb 2015 11:02:23 -0800 Subject: [PATCH 130/576] Rename AUTH.md to grpc-auth-support.md --- AUTH.md => grpc-auth-support.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename AUTH.md => grpc-auth-support.md (100%) diff --git a/AUTH.md b/grpc-auth-support.md similarity index 100% rename from AUTH.md rename to grpc-auth-support.md From 4a8feaac4cc48be2cfcda99a5ec9eea5736ea58d Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Tue, 24 Feb 2015 11:52:49 -0800 Subject: [PATCH 131/576] Adding grpc org to path In the instructions, adding grpc to the path for the github project. --- go/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go/README.md b/go/README.md index bf5d6c8cf48..9fc49474d79 100644 --- a/go/README.md +++ b/go/README.md @@ -16,8 +16,8 @@ INSTALL ------- ```sh -$ go get -u github.com/grpc-common/go/greeter_client -$ go get -u github.com/grpc-common/go/greeter_server +$ go get -u github.com/grpc/grpc-common/go/greeter_client +$ go get -u github.com/grpc/grpc-common/go/greeter_server ``` TRY IT! From cd3379fbeb80bd9741eda750ecbd2cc2e1474d23 Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Tue, 24 Feb 2015 11:56:02 -0800 Subject: [PATCH 132/576] Fixing path for pb import Was missing grpc in the path --- go/greeter_client/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go/greeter_client/main.go b/go/greeter_client/main.go index 3398040d7e5..065ae852bc3 100644 --- a/go/greeter_client/main.go +++ b/go/greeter_client/main.go @@ -37,7 +37,7 @@ import ( "log" "os" - pb "github.com/grpc-common/go/helloworld" + pb "github.com/grpc/grpc-common/go/helloworld" "golang.org/x/net/context" "google.golang.org/grpc" ) From 3054eba891802f7c48de16240ac1296fb1411e44 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 14:36:18 -0800 Subject: [PATCH 133/576] Fix readme --- cpp/README.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/cpp/README.md b/cpp/README.md index fe9b71620e7..ac4dea9b7fd 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -35,7 +35,7 @@ $ make helloworld.pb.cc Which internally invokes the proto-compiler as: ```sh -$protoc -I ../../protos/ --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin helloworld.proto +$ protoc -I ../../protos/ --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin ../../protos/helloworld.proto ``` ### Client and server implementations @@ -45,8 +45,18 @@ The client implementation is at [greeter_client.cc](https://github.com/grpc/grpc The server implementation is at [greeter_server.cc](https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_server.cc). ### Try it! - -###TODO: instructions to run server and client +Build client and server: +```sh +$ make +``` +Run the server: +```sh +$ ./greeter_server +``` +Run the client: +```sh +$ ./greeter_client +``` ## Tutorial From ecee424a879d0e56e7bd7115a7015beafe09c4e6 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 14:46:53 -0800 Subject: [PATCH 134/576] Add output piece. --- cpp/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cpp/README.md b/cpp/README.md index ac4dea9b7fd..078021d8760 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -53,10 +53,11 @@ Run the server: ```sh $ ./greeter_server ``` -Run the client: +Run the client (in a different terminal): ```sh $ ./greeter_client ``` +If things go smoothly, you will see the "Greeter received: Hello world" in the client side output. ## Tutorial From 84c263fd720090c1b5018068caf4c61f40cb0605 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 14:47:47 -0800 Subject: [PATCH 135/576] Add port info. --- cpp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/README.md b/cpp/README.md index 078021d8760..759e10bfe1f 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -49,7 +49,7 @@ Build client and server: ```sh $ make ``` -Run the server: +Run the server, which will listen on port 50051: ```sh $ ./greeter_server ``` From cdbb60c7b6dc1c64745e1ce0b0905f3a876a9a1b Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 15:01:36 -0800 Subject: [PATCH 136/576] Add missing protoc command --- cpp/cpptutorial.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index af6b6b1a65f..338e1e7d5a4 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -101,7 +101,9 @@ $ make route_guide.pb.cc which actually runs: -[actual command] +```shell +$ protoc -I ../../protos --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto +``` Running this command generates the following files: - `route_guide.pb.h`, the header which declares your generated classes From e1ea962f0a34d1d1d85e77de7536102d5b237bf2 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 15:09:26 -0800 Subject: [PATCH 137/576] Fix broken link --- cpp/cpptutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 338e1e7d5a4..cd712fe3c51 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -20,7 +20,7 @@ With gRPC we can define our service once in a .proto file and implement clients ## Example code and setup -The example code for our tutorial is in [grpc/grpc-common/cpp/route_guide](https://github.com/grpc/grpc-common/cpp/route_guide). To download the example, clone the `grpc-common` repository by running the following command: +The example code for our tutorial is in [grpc/grpc-common/cpp/route_guide](https://github.com/grpc/grpc-common/tree/master/cpp/route_guide). To download the example, clone the `grpc-common` repository by running the following command: ```shell $ git clone https://github.com/google/grpc-common.git ``` From de0c653ed5b8d639aa1436d9e55ccf88cbd240af Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 15:52:22 -0800 Subject: [PATCH 138/576] various fixes --- cpp/cpptutorial.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index cd712fe3c51..b13dff175e8 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -49,7 +49,7 @@ Then you define `rpc` methods inside your service definition, specifying their r - A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. ``` - // Obtains the feature at a given position. + // Obtains the feature at a given position. rpc GetFeature(Point) returns (Feature) {} ``` @@ -125,7 +125,7 @@ There are two parts to making our `RouteGuide` service do its job: - Implementing the service interface generated from our service definition: doing the actual "work" of our service. - Running a gRPC server to listen for requests from clients and return the service responses. -You can find our example `RouteGuide` server in [grpc-common/cpp/route_guide/route_guide_server.cc]((https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/route_guide_server.cc). Let's take a closer look at how it works. +You can find our example `RouteGuide` server in [grpc-common/cpp/route_guide/route_guide_server.cc](https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/route_guide_server.cc). Let's take a closer look at how it works. ### Implementing RouteGuide From 633625525ad7302c107cd23a21e1460ddf0e94bb Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 15:56:44 -0800 Subject: [PATCH 139/576] Update the Maven link --- java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/README.md b/java/README.md index 35c9db31927..4410f830f69 100644 --- a/java/README.md +++ b/java/README.md @@ -6,7 +6,7 @@ PREREQUISITES - [Java 8](http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html) -- [Maven 3.2](http://maven.apache.org/users/index.html). +- [Maven 3.2 or later](http://maven.apache.org/download.cgi). - this is needed to install Netty5, a dependency of gRPC, and to build this sample - [Latest version of google-protobuf](https://github.com/google/protobuf/tree/master/java) From 6b99bc5b7f73e2c590cce4e8b53cf8bc1fee796d Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 15:57:30 -0800 Subject: [PATCH 140/576] Remove superfluous link to protobuf install --- java/README.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/java/README.md b/java/README.md index 4410f830f69..89724904d46 100644 --- a/java/README.md +++ b/java/README.md @@ -9,11 +9,6 @@ PREREQUISITES - [Maven 3.2 or later](http://maven.apache.org/download.cgi). - this is needed to install Netty5, a dependency of gRPC, and to build this sample -- [Latest version of google-protobuf](https://github.com/google/protobuf/tree/master/java) - - to generate java code from proto files - - to install the base Java proto3 library - - INSTALL ------- From 2b4be223d3455c250b5618b14d9637eeaa98eb0a Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 15:59:43 -0800 Subject: [PATCH 141/576] Change to server.Wait() --- cpp/helloworld/greeter_server.cc | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/cpp/helloworld/greeter_server.cc b/cpp/helloworld/greeter_server.cc index 01a0bf242dd..e3dd36b0ed9 100644 --- a/cpp/helloworld/greeter_server.cc +++ b/cpp/helloworld/greeter_server.cc @@ -34,7 +34,6 @@ #include #include #include -#include #include #include @@ -69,9 +68,7 @@ void RunServer() { builder.RegisterService(&service); std::unique_ptr server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; - while (true) { - std::this_thread::sleep_for(std::chrono::seconds(5)); - } + server->Wait(); } int main(int argc, char** argv) { From 50bc9a77f878a682e687e75511c9cfe4d7eb30c7 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 16:02:59 -0800 Subject: [PATCH 142/576] Change to server.Wait() api. --- cpp/route_guide/route_guide_server.cc | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/cpp/route_guide/route_guide_server.cc b/cpp/route_guide/route_guide_server.cc index 2699330e4c6..d0a2ecd5d47 100644 --- a/cpp/route_guide/route_guide_server.cc +++ b/cpp/route_guide/route_guide_server.cc @@ -37,7 +37,6 @@ #include #include #include -#include #include #include @@ -191,9 +190,7 @@ void RunServer(const std::string& db_path) { builder.RegisterService(&service); std::unique_ptr server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; - while (true) { - std::this_thread::sleep_for(std::chrono::seconds(5)); - } + server->Wait(); } int main(int argc, char** argv) { From 44e9822568e906abfe1a587681ea5e9c83c7074f Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 16:06:02 -0800 Subject: [PATCH 143/576] Change code and text in text too --- cpp/cpptutorial.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index b13dff175e8..144b902519f 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -220,9 +220,7 @@ void RunServer(const std::string& db_path) { builder.RegisterService(&service); std::unique_ptr server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; - while (true) { - std::this_thread::sleep_for(std::chrono::seconds(5)); - } + server->Wait(); } ``` As you can see, we build and start our server using a `ServerBuilder`. To do this, we: @@ -232,8 +230,7 @@ As you can see, we build and start our server using a `ServerBuilder`. To do thi 3. Specify the address and port we want to use to listen for client requests using the builder's `AddPort()` method. 4. Register our service implementation with the builder. 5. Call `BuildAndStart()` on the builder to create and start an RPC server for our service. - -_[is there no equivalent of the Stubby4 wait() method, ie do you have to do the while(true) loop to keep the server running?]_ +5. Call `Wait()` on the server to do a blocking wait until process is killed or `Shutdown()` is called. ## Creating the client From 9a2ff4f376da3564f197df8b5704e1dda3799468 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 16:13:02 -0800 Subject: [PATCH 144/576] Add build and run section --- cpp/cpptutorial.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 144b902519f..613af1ae7cd 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -350,7 +350,16 @@ The syntax for reading and writing here is exactly the same as for our client-st ## Try it out! -_[need build and run instructions here]_ - - +Build client and server: +```shell +$ make +``` +Run the server, which will listen on port 50051: +```shell +$ ./route_guide_server +``` +Run the client (in a different terminal): +```shell +$ ./route_guide_client +``` From 507a2410f1071a529ea4883f7f6b193043b08d5e Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 17:22:37 -0800 Subject: [PATCH 145/576] Fixes more go package references --- go/greeter_client/main.go | 2 +- go/greeter_server/main.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/go/greeter_client/main.go b/go/greeter_client/main.go index abe33c0e2ad..0ca5a00035c 100644 --- a/go/greeter_client/main.go +++ b/go/greeter_client/main.go @@ -37,7 +37,7 @@ import ( "log" "os" - pb "github.com/grpc-common/go/helloworld" + pb "github.com/grpc/grpc-common/go/helloworld" "golang.org/x/net/context" "google.golang.org/grpc" ) diff --git a/go/greeter_server/main.go b/go/greeter_server/main.go index 231f5c607ba..c7fa06ad180 100644 --- a/go/greeter_server/main.go +++ b/go/greeter_server/main.go @@ -37,7 +37,7 @@ import ( "log" "net" - pb "github.com/grpc-common/go/helloworld" + pb "github.com/grpc/grpc-common/go/helloworld" "golang.org/x/net/context" "google.golang.org/grpc" ) From cec80edc6cda25ef870f64a67d774f7f6688fe2f Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Tue, 24 Feb 2015 23:45:00 -0800 Subject: [PATCH 146/576] fix link to Gemfile --- ruby/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby/README.md b/ruby/README.md index 1fc19a4f246..4afea611a42 100644 --- a/ruby/README.md +++ b/ruby/README.md @@ -11,7 +11,7 @@ INSTALL - Clone this repository. - Follow the instructions in [INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL) to install the gRPC C core. -- *Temporary* Install the full gRPC distribution from source on your local machine and update path: in [Gemfile] to refer src/ruby within it. +- *Temporary* Install the full gRPC distribution from source on your local machine and update path: in [Gemfile](https://github.com/grpc/grpc-common/blob/master/ruby/Gemfile) to refer src/ruby within it. - this is necessary until the gRPC ruby gem is published - Use bundler to install ```sh From 78c9e77a4adeff309ad1380aa2c9bf892889b53f Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 11:37:36 +0000 Subject: [PATCH 147/576] mentioned that we have (some) tutorials --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index acea9289a7a..4c9fc90903b 100644 --- a/README.md +++ b/README.md @@ -5,10 +5,11 @@ Welcome to the developer documentation for gRPC, a language-neutral, platform-neutral remote procedure call (RPC) system developed at Google. This document introduces you to gRPC with a quick overview and a simple -Hello World example. More documentation is coming soon! +Hello World example. You'll find more tutorials and reference docs in this repository - more documentation is coming soon! + ## Quick start -You can find quick start guides for each language, including installation instructions and examples here: +You can find quick start guides for each language, including installation instructions, examples, and tutorials here: * [C++](https://github.com/grpc/grpc-common/tree/master/cpp) * [Java](https://github.com/grpc/grpc-common/tree/master/java) * [Python](https://github.com/grpc/grpc-common/tree/master/python) @@ -98,8 +99,8 @@ than how to install and run a few git commands. This is an introductory example rather than a comprehensive tutorial, so don't worry if you're not a Go or Java developer - the concepts are similar for all languages, and you can -find more implementations of our Hello World example in other languages in -the language-specific folders in this repository. Complete tutorials and +find more implementations of our Hello World example in other languages (and full tutorials where available) in +the [language-specific folders](#quickstart) in this repository. Complete tutorials and reference documentation for all gRPC languages are coming soon. From b756da3bfd4612f915ea1c1aa57354c06d6547e6 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 11:42:43 +0000 Subject: [PATCH 148/576] Update cpptutorial.md --- cpp/cpptutorial.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 613af1ae7cd..65fd5c7eec2 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -16,8 +16,6 @@ Our example is a simple route mapping application that lets clients get informat With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. -[possibly insert more advantages here] - ## Example code and setup The example code for our tutorial is in [grpc/grpc-common/cpp/route_guide](https://github.com/grpc/grpc-common/tree/master/cpp/route_guide). To download the example, clone the `grpc-common` repository by running the following command: From 5b5e146d4d132170cb85a077ff7b35654fca9cea Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 25 Feb 2015 04:18:56 -0800 Subject: [PATCH 149/576] Update README.md --- ruby/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ruby/README.md b/ruby/README.md index 1fc19a4f246..b386a9b9250 100644 --- a/ruby/README.md +++ b/ruby/README.md @@ -6,6 +6,16 @@ PREREQUISITES This requires Ruby 2.1, as the gRPC API surface uses keyword args. +If you don't have that installed locally, you can use [RVM](https://www.rvm.io/) to use Ruby 2.1 for testing without upgrading the version of Ruby on your whole system. +```sh +$ command curl -sSL https://rvm.io/mpapis.asc | gpg --import - +$ \curl -sSL https://get.rvm.io | bash -s stable --ruby=ruby-2.1 +$ +$ # follow the instructions to ensure that your're using the latest stable version of Ruby +$ # and that the rvm command is installed +``` +- Make sure your run `source $HOME/.rvm/scripts/rvm` as instructed to complete the set up of RVM + INSTALL ------- From 25ffbd86db8a07fc9a7ffd538288f1f46af08a53 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 14:12:39 +0000 Subject: [PATCH 150/576] Update cpptutorial.md --- cpp/cpptutorial.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/cpptutorial.md b/cpp/cpptutorial.md index 65fd5c7eec2..d1762406263 100644 --- a/cpp/cpptutorial.md +++ b/cpp/cpptutorial.md @@ -28,7 +28,7 @@ Then change your current directory to `grpc-common/cpp/route_guide`: $ cd grpc-common/cpp/route_guide ``` -Although we've provided the complete example so you don't need to generate the gRPC code yourself, if you want to try generating your own server and client interface code you can follow the setup instructions in [the C++ quick start guide](https://github.com/grpc/grpc-common/tree/master/cpp). +You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the C++ quick start guide](https://github.com/grpc/grpc-common/tree/master/cpp). ## Defining the service @@ -103,7 +103,7 @@ which actually runs: $ protoc -I ../../protos --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto ``` -Running this command generates the following files: +Running this command generates the following files in your current directory: - `route_guide.pb.h`, the header which declares your generated classes - `route_guide.pb.cc`, which contains the implementation of your classes From e7e5b55e2296eddbfe492d37c6e230a287020d52 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 25 Feb 2015 07:10:01 -0800 Subject: [PATCH 151/576] Update grpc-auth-support.md --- grpc-auth-support.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 9850b8b24ef..5aa526af45b 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -86,3 +86,34 @@ the server to retrieve this piece of metadata. The generation of the token on the client side and its verification at the server can be done separately. A deeper integration can be achieved by plugging in a gRPC credentials implementation for any custom authentication mechanism that needs to attach per-request tokens. gRPC internals also allow switching out SSL/TLS with other encryption mechanisms. + +These authentication mechanisms will be available in all gRPC's supported languages. +The following sections demonstrate how authentication and authorization features described above appear in each language + +####SSL/TLS for server authentication and encryption (Ruby) +```ruby +# Base case - No encryption +stub = Helloworld::Greeter::Stub.new('localhost:50051') +... + +# With server authentication SSL/TLS +creds = GRPC::Core::Credentials.new(load_certs) # load_certs typically loads a CA roots file +stub = Helloworld::Greeter::Stub.new('localhost:50051', creds: creds) +``` + +###Authenticating with Google (Ruby) +```ruby +# Base case - No encryption/authorization +stub = Helloworld::Greeter::Stub.new('localhost:50051') +... + +# Authenticating with Google +require 'googleauth' # from [googleauth](http://www.rubydoc.info/gems/googleauth/0.1.0) +... +creds = GRPC::Core::Credentials.new(load_certs) # load_certs typically loads a CA roots file +scope = 'https://www.googleapis.com/auth/grpc-testing' +authorization = Google::Auth.get_application_default(scope) +stub = Helloworld::Greeter::Stub.new('localhost:50051', + creds: creds, + update_metadata: authorization.updater_proc) +``` From 43a0eb0a993305467a4ea58112c1f14c1c3923cc Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 17:27:56 +0000 Subject: [PATCH 152/576] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4c9fc90903b..77ac47a5150 100644 --- a/README.md +++ b/README.md @@ -320,6 +320,7 @@ As you can see, the class `GreeterImpl` implements the interface } ``` - `hello` takes two parameters: + -`Helloworld.HelloRequest`: the request -`StreamObserver`: a response observer, which is a special interface for the server to call with its response From a25a42b4b711d6eb97383947b243f215342139b5 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 17:28:30 +0000 Subject: [PATCH 153/576] Update README.md --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 77ac47a5150..c58dca9a2b4 100644 --- a/README.md +++ b/README.md @@ -320,9 +320,8 @@ As you can see, the class `GreeterImpl` implements the interface } ``` - `hello` takes two parameters: - - -`Helloworld.HelloRequest`: the request - -`StreamObserver`: a response observer, which is + - `Helloworld.HelloRequest`: the request + - `StreamObserver`: a response observer, which is a special interface for the server to call with its response To return our response to the client and complete the call: From 133b4b3b023fddc11b75f6d26e305d9441bcacc6 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Wed, 25 Feb 2015 18:46:17 +0000 Subject: [PATCH 154/576] New shiny Java tutorial --- java/javatutorial.md | 351 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 351 insertions(+) create mode 100644 java/javatutorial.md diff --git a/java/javatutorial.md b/java/javatutorial.md new file mode 100644 index 00000000000..4c419cf345b --- /dev/null +++ b/java/javatutorial.md @@ -0,0 +1,351 @@ +#gRPC Basics: Java + +This tutorial provides a basic Java programmer's introduction to working with gRPC. By walking through this example you'll learn how to: + +- Define a service in a .proto file. +- Generate server and client code using the protocol buffer compiler. +- Use the Java gRPC API to write a simple client and server for your service. + +It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release: you can see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository. + +This isn't a comprehensive guide to using gRPC in Java: more reference documentation is coming soon. + +## Why use gRPC? + +Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. + +With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. + +## Example code and setup + +The example code for our tutorial is in [grpc/grpc-java/examples/src/main/java/io/grpc/examples](https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples). To download the example, clone the `grpc-java` repository by running the following command: +```shell +$ git clone https://github.com/google/grpc-java.git +``` + +Then change your current directory to `grpc-java/examples`: +```shell +$ cd grpc-java/examples +``` + +You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Java quick start guide](https://github.com/grpc/grpc-common/tree/master/java). + + +## Defining the service + +Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-java/examples/src/main/proto/route_guide.proto`](https://github.com/grpc/grpc-java/blob/master/examples/src/main/proto/route_guide.proto). + +As we're generating Java code in this example, we've specified a `java_package` file option in our .proto: +``` +option java_package = "io.grpc.examples"; +``` + +This specifies the package we want to use for our generated Java classes. If no explicit `java_package` option is given in the .proto file, then by default the proto package (specified using the "package" keyword) will be used. However, proto packages generally do not make good Java packages since proto packages are not expected to start with reverse domain names. If we generate code in another language from this .proto, the `java_package` option has no effect. + +To define a service, we specify a named `service` in the .proto file: + +``` +service RouteGuide { + ... +} +``` + +Then we define `rpc` methods inside our service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service: + +- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. +``` + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) {} +``` + +- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. +``` + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) {} +``` + +- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type. +``` + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} +``` + +- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. +``` + // Accepts a stream of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} +``` + +Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: +``` +// Points are represented as latitude-longitude pairs in the E7 representation +// (degrees multiplied by 10**7 and rounded to the nearest integer). +// Latitudes should be in the range +/- 90 degrees and longitude should be in +// the range +/- 180 degrees (inclusive). +message Point { + int32 latitude = 1; + int32 longitude = 2; +} +``` + + +## Generating client and server code + +Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Java plugin. + +For simplicity, we've provided a [Gradle build file](https://github.com/grpc/grpc-java/blob/master/examples/build.gradle) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc-java) first): + +```shell +gradle build +``` + +which actually runs: + +[actual command] + +Running this command generates the following files: +- `RouteGuideOuterClass.java` [cheeeeeeck], which contains all the protocol buffer code to populate, serialize, and retrieve our request and response message types +- `RouteGuideGrpc.java` which contains (along with some other useful code): + - an interface for `RouteGuide` servers to implement, `RouteGuideGrpc.Service`, with all the methods defined in the `RouteGuide` service. + - *stub* classes that clients can use to talk to a `RouteGuide` server. These also implement the `RouteGuide` interface. + + + +## Creating the server + +First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!). + +There are two parts to making our `RouteGuide` service do its job: +- Implementing the service interface generated from our service definition: doing the actual "work" of our service. +- Running a gRPC server to listen for requests from clients and return the service responses. + +You can find our example `RouteGuide` server in [grpc-java/examples/src/main/java/io/grpc/examples/RouteGuideServer.java](https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/RouteGuideServer.java). Let's take a closer look at how it works. + +### Implementing RouteGuide + +As you can see, our server has a `RouteGuideService` class that implements the generated `RouteGuideGrpc.Service` interface: + +```java +private static class RouteGuideService implements RouteGuideGrpc.RouteGuide { +... +} +``` + +`RouteGuideService` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. + +```java + @Override + public void getFeature(Point request, StreamObserver responseObserver) { + responseObserver.onValue(getFeature(request)); + responseObserver.onCompleted(); + } + +... + + private Feature getFeature(Point location) { + for (Feature feature : features) { + if (feature.getLocation().getLatitude() == location.getLatitude() + && feature.getLocation().getLongitude() == location.getLongitude()) { + return feature; + } + } + + // No feature was found, return an unnamed feature. + return Feature.newBuilder().setName("").setLocation(location).build(); + } +``` + +`getFeature()` takes two parameters: +- `Point`: the request +- `StreamObserver`: a response observer, which is a special interface for the server to call with its response. + +To return our response to the client and complete the call: + +1. We construct and populate a `Feature` response object to return to the client, as specified in our service definition. In this example, we do this in a separate private `getFeature()` method. +2. We use the response observer's `onValue()` method to return the `Feature`. +3. We use the response observer's `onCompleted()` method to specify that we've finished dealing with the RPC. + +Next let's look at a streaming RPC. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. + +```java +private final Collection features; + +... + + @Override + public void listFeatures(Rectangle request, StreamObserver responseObserver) { + int left = min(request.getLo().getLongitude(), request.getHi().getLongitude()); + int right = max(request.getLo().getLongitude(), request.getHi().getLongitude()); + int top = max(request.getLo().getLatitude(), request.getHi().getLatitude()); + int bottom = min(request.getLo().getLatitude(), request.getHi().getLatitude()); + + for (Feature feature : features) { + if (!RouteGuideUtil.exists(feature)) { + continue; + } + + int lat = feature.getLocation().getLatitude(); + int lon = feature.getLocation().getLongitude(); + if (lon >= left && lon <= right && lat >= bottom && lat <= top) { + responseObserver.onValue(feature); + } + } + responseObserver.onCompleted(); + } +``` + +Like the simple RPC, this method gets a request object (the `Rectangle` in which our client wants to find `Feature`s) and a `StreamObserver` response observer. + +This time, we get as many `Feature` objects as we need to return to the client (in this case, we select them from the service's feature collection based on whether they're inside our request `Rectangle`), and write them each in turn to the response observer using its `Write()` method. Finally, as in our simple RPC, we use the response observer's `onCompleted()` method to tell gRPC that we've finished writing responses. + +Now let's look at something a little more complicated: the client-side streaming method `RecordRoute`, where we get a stream of `Point`s from the client and return a single `RouteSummary` with information about their trip. + +```java + @Override + public StreamObserver recordRoute(final StreamObserver responseObserver) { + return new StreamObserver() { + int pointCount; + int featureCount; + int distance; + Point previous; + long startTime = System.nanoTime(); + + @Override + public void onValue(Point point) { + pointCount++; + if (RouteGuideUtil.exists(getFeature(point))) { + featureCount++; + } + // For each point after the first, add the incremental distance from the previous point to + // the total distance value. + if (previous != null) { + distance += calcDistance(previous, point); + } + previous = point; + } + + @Override + public void onError(Throwable t) { + logger.log(Level.WARNING, "Encountered error in recordRoute", t); + } + + @Override + public void onCompleted() { + long seconds = NANOSECONDS.toSeconds(System.nanoTime() - startTime); + responseObserver.onValue(RouteSummary.newBuilder().setPointCount(pointCount) + .setFeatureCount(featureCount).setDistance(distance) + .setElapsedTime((int) seconds).build()); + responseObserver.onCompleted(); + } + }; + } +``` + +As you can see, like the previous method types our method gets a `StreamObserver` response observer parameter, but this time it returns a `StreamObserver` for the client to write its `Point`s. + +In the method body we instantiate an anonymous `StreamObserver` to return, in which we: +- Override the `onValue()` method to get features and other information each time the client writes a `Point` to the message stream. +- Override the `onCompleted()' method (called when the *client* has finished writing messages) to populate and build our `RouteSummary`. We then call our method's own response observer's `onValue()` with our `RouteSummary`, and then call its `onCompleted()` method to finish the call from the server side. + +Finally, let's look at our bidirectional streaming RPC `RouteChat()`. + +```cpp + @Override + public StreamObserver routeChat(final StreamObserver responseObserver) { + return new StreamObserver() { + @Override + public void onValue(RouteNote note) { + List notes = getOrCreateNotes(note.getLocation()); + + // Respond with all previous notes at this location. + for (RouteNote prevNote : notes.toArray(new RouteNote[0])) { + responseObserver.onValue(prevNote); + } + + // Now add the new note to the list + notes.add(note); + } + + @Override + public void onError(Throwable t) { + logger.log(Level.WARNING, "Encountered error in routeChat", t); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }; + } +``` + +As with our client-side streaming example, we both get and return a `StreamObserver` response observer, except this time we return values via our method's response observer while the client is still writing messages to *their* message stream. The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. + +### Starting the server + +Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service: + +```java + public void start() { + gRpcServer = NettyServerBuilder.forPort(port) + .addService(RouteGuideGrpc.bindService(new RouteGuideService(features))) + .build().start(); + logger.info("Server started, listening on " + port); + ... + } +``` +As you can see, we build and start our server using a `NettyServerBuilder`. To do this, we: + +1. Create an instance of our service implementation class `RouteGuideService` and pass it to the generated `RouteGuideGrpc` class's static `bindService()` method to get a service definition. +3. Specify the address and port we want to use to listen for client requests using the builder's `forPort()` method. +4. Register our service implementation with the builder by passing the service definition returned from `bindService()` to the builder's `addService()` method. +5. Call `build()` and `start()` on the builder to create and start an RPC server for our service. + + +## Creating the client + +In this section, we'll look at creating a Java client for our `RouteGuide` service. You can see our complete example client code in [grpc-java/examples/src/main/java/io/grpc/examples/RouteGuideClient.java](https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/RouteGuideClient.java). + +### Creating a stub + +To call service methods, we first need to create a *stub*, or rather, two stubs: +- a *blocking/synchronous* stub: this means that the RPC call waits for the server to respond, and will either return a response or raise an exception. +- a *non-blocking/asynchronous* stub that makes non-blocking calls to the server, where the response is returned asynchronously. You can make certain types of streaming call only using the asynchronous stub. + +First we need to create a gRPC *channel* for our stub, specifying the server address and port we want to connect to: + +```java + channel = NettyChannelBuilder.forAddress(host, port) + .negotiationType(NegotiationType.PLAINTEXT) + .build(); +``` + +Now we can use the channel to create our stubs using the `newStub` and `newBlockingStub` methods provided in the `RouteGuideGrpc` class we generated from our .proto. + +```java + blockingStub = RouteGuideGrpc.newBlockingStub(channel); + asyncStub = RouteGuideGrpc.newStub(channel); +``` + +### Calling service methods + +Now let's look at how we call our service methods. + +#### Simple RPC + + + +#### Streaming RPCs + + +## Try it out! + +_[need build and run instructions here]_ + + + From 63f6633529372743ac1ca3512e29646a8dbeda71 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Wed, 25 Feb 2015 18:48:22 +0000 Subject: [PATCH 155/576] Fixed typo --- java/javatutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/javatutorial.md b/java/javatutorial.md index 4c419cf345b..e74573e0b44 100644 --- a/java/javatutorial.md +++ b/java/javatutorial.md @@ -250,7 +250,7 @@ As you can see, like the previous method types our method gets a `StreamObserver In the method body we instantiate an anonymous `StreamObserver` to return, in which we: - Override the `onValue()` method to get features and other information each time the client writes a `Point` to the message stream. -- Override the `onCompleted()' method (called when the *client* has finished writing messages) to populate and build our `RouteSummary`. We then call our method's own response observer's `onValue()` with our `RouteSummary`, and then call its `onCompleted()` method to finish the call from the server side. +- Override the `onCompleted()` method (called when the *client* has finished writing messages) to populate and build our `RouteSummary`. We then call our method's own response observer's `onValue()` with our `RouteSummary`, and then call its `onCompleted()` method to finish the call from the server side. Finally, let's look at our bidirectional streaming RPC `RouteChat()`. From dacca2cd5e6191a0b221dea79b48c04a8ff6f9c2 Mon Sep 17 00:00:00 2001 From: nmittler Date: Wed, 25 Feb 2015 10:50:15 -0800 Subject: [PATCH 156/576] Updating java package for helloworld.proto --- protos/helloworld.proto | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protos/helloworld.proto b/protos/helloworld.proto index f9abd3d87f7..6281c934ae4 100644 --- a/protos/helloworld.proto +++ b/protos/helloworld.proto @@ -29,7 +29,7 @@ syntax = "proto3"; -option java_package = "ex.grpc"; +option java_package = "io.grpc.examples"; package helloworld; From e384403de53d095b886fb5a2ca1b6d6d05761cf7 Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Wed, 25 Feb 2015 10:57:30 -0800 Subject: [PATCH 157/576] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c58dca9a2b4..7360182c56c 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ Hello World example. You'll find more tutorials and reference docs in this repos You can find quick start guides for each language, including installation instructions, examples, and tutorials here: * [C++](https://github.com/grpc/grpc-common/tree/master/cpp) * [Java](https://github.com/grpc/grpc-common/tree/master/java) -* [Python](https://github.com/grpc/grpc-common/tree/master/python) * [Go](https://github.com/grpc/grpc-common/tree/master/go) * [ruby](https://github.com/grpc/grpc-common/tree/master/ruby) * [Node.js](https://github.com/grpc/grpc-common/tree/master/node) +* Python is coming soon ## What's in this repository? From 255b73b5b198f593b14d878842dd2a0bfec87fe9 Mon Sep 17 00:00:00 2001 From: nmittler Date: Wed, 25 Feb 2015 11:02:03 -0800 Subject: [PATCH 158/576] Removing java examples from grpc-common --- java/pom.xml | 105 -- java/run_greeter_client.sh | 10 - java/run_greeter_server.sh | 9 - java/src/main/java/ex/grpc/GreeterClient.java | 55 - java/src/main/java/ex/grpc/GreeterGrpc.java | 172 ---- java/src/main/java/ex/grpc/GreeterImpl.java | 16 - java/src/main/java/ex/grpc/GreeterServer.java | 51 - java/src/main/java/ex/grpc/Helloworld.java | 951 ------------------ 8 files changed, 1369 deletions(-) delete mode 100644 java/pom.xml delete mode 100755 java/run_greeter_client.sh delete mode 100755 java/run_greeter_server.sh delete mode 100644 java/src/main/java/ex/grpc/GreeterClient.java delete mode 100644 java/src/main/java/ex/grpc/GreeterGrpc.java delete mode 100644 java/src/main/java/ex/grpc/GreeterImpl.java delete mode 100644 java/src/main/java/ex/grpc/GreeterServer.java delete mode 100644 java/src/main/java/ex/grpc/Helloworld.java diff --git a/java/pom.xml b/java/pom.xml deleted file mode 100644 index da0ee205f77..00000000000 --- a/java/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - 4.0.0 - - - com.google.net.stubby - stubby-parent - 0.1.0-SNAPSHOT - - - grpc-hello-world - jar - - Hello gRPC World - - - - ${project.groupId} - stubby-core - ${project.version} - - - ${project.groupId} - stubby-netty - ${project.version} - - - ${project.groupId} - stubby-okhttp - ${project.version} - - - ${project.groupId} - stubby-stub - ${project.version} - - - ${project.groupId} - stubby-testing - ${project.version} - - - junit - junit - compile - - - org.mockito - mockito-core - compile - - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - - - assemble-all - package - - single - - - - - - jar-with-dependencies - - - - - - com.internetitem - write-properties-file-maven-plugin - - - bootclasspath - prepare-package - - write-properties-file - - - bootclasspath.properties - ${project.build.directory} - - - bootclasspath - ${argLine.bootcp} - - - jar - ${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar - - - - - - - - - diff --git a/java/run_greeter_client.sh b/java/run_greeter_client.sh deleted file mode 100755 index e86ab4ae891..00000000000 --- a/java/run_greeter_client.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -e -TARGET='Greeter Client' -TARGET_CLASS='ex.grpc.GreeterClient' -TARGET_ARGS="$@" - -cd "$(dirname "$0")" -mvn -q -nsu -am package -Dcheckstyle.skip=true -DskipTests -. target/bootclasspath.properties -echo "[INFO] Running: $TARGET ($TARGET_CLASS $TARGET_ARGS)" -exec java "$bootclasspath" -cp "$jar" "$TARGET_CLASS" $TARGET_ARGS diff --git a/java/run_greeter_server.sh b/java/run_greeter_server.sh deleted file mode 100755 index 836abc7f48a..00000000000 --- a/java/run_greeter_server.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -e -TARGET='Greeter Server' -TARGET_CLASS='ex.grpc.GreeterServer' - -cd "$(dirname "$0")" -mvn -q -nsu -am package -Dcheckstyle.skip=true -DskipTests -. target/bootclasspath.properties -echo "[INFO] Running: $TARGET ($TARGET_CLASS)" -exec java "$bootclasspath" -cp "$jar" "$TARGET_CLASS" diff --git a/java/src/main/java/ex/grpc/GreeterClient.java b/java/src/main/java/ex/grpc/GreeterClient.java deleted file mode 100644 index 9a4615132d6..00000000000 --- a/java/src/main/java/ex/grpc/GreeterClient.java +++ /dev/null @@ -1,55 +0,0 @@ -package ex.grpc; - -import com.google.net.stubby.ChannelImpl; -import com.google.net.stubby.stub.StreamObserver; -import com.google.net.stubby.transport.netty.NegotiationType; -import com.google.net.stubby.transport.netty.NettyChannelBuilder; - -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.concurrent.TimeUnit; - -public class GreeterClient { - private final Logger logger = Logger.getLogger( - GreeterClient.class.getName()); - private final ChannelImpl channel; - private final GreeterGrpc.GreeterBlockingStub blockingStub; - - public GreeterClient(String host, int port) { - channel = NettyChannelBuilder.forAddress(host, port) - .negotiationType(NegotiationType.PLAINTEXT) - .build(); - blockingStub = GreeterGrpc.newBlockingStub(channel); - } - - public void shutdown() throws InterruptedException { - channel.shutdown().awaitTerminated(5, TimeUnit.SECONDS); - } - - public void greet(String name) { - try { - logger.fine("Will try to greet " + name + " ..."); - Helloworld.HelloRequest req = - Helloworld.HelloRequest.newBuilder().setName(name).build(); - Helloworld.HelloReply reply = blockingStub.sayHello(req); - logger.info("Greeting: " + reply.getMessage()); - } catch (RuntimeException e) { - logger.log(Level.WARNING, "RPC failed", e); - return; - } - } - - public static void main(String[] args) throws Exception { - GreeterClient client = new GreeterClient("localhost", 50051); - try { - /* Access a service running on the local machine on port 50051 */ - String user = "world"; - if (args.length > 0) { - user = args[0]; /* Use the arg as the name to greet if provided */ - } - client.greet(user); - } finally { - client.shutdown(); - } - } -} diff --git a/java/src/main/java/ex/grpc/GreeterGrpc.java b/java/src/main/java/ex/grpc/GreeterGrpc.java deleted file mode 100644 index 080c3dfc434..00000000000 --- a/java/src/main/java/ex/grpc/GreeterGrpc.java +++ /dev/null @@ -1,172 +0,0 @@ -package ex.grpc; - -import static com.google.net.stubby.stub.Calls.createMethodDescriptor; -import static com.google.net.stubby.stub.Calls.asyncUnaryCall; -import static com.google.net.stubby.stub.Calls.asyncServerStreamingCall; -import static com.google.net.stubby.stub.Calls.asyncClientStreamingCall; -import static com.google.net.stubby.stub.Calls.duplexStreamingCall; -import static com.google.net.stubby.stub.Calls.blockingUnaryCall; -import static com.google.net.stubby.stub.Calls.blockingServerStreamingCall; -import static com.google.net.stubby.stub.Calls.unaryFutureCall; -import static com.google.net.stubby.stub.ServerCalls.createMethodDefinition; -import static com.google.net.stubby.stub.ServerCalls.asyncUnaryRequestCall; -import static com.google.net.stubby.stub.ServerCalls.asyncStreamingRequestCall; - -@javax.annotation.Generated("by gRPC proto compiler") -public class GreeterGrpc { - - private static final com.google.net.stubby.stub.Method METHOD_SAY_HELLO = - com.google.net.stubby.stub.Method.create( - com.google.net.stubby.MethodType.UNARY, "sayHello", - com.google.net.stubby.proto.ProtoUtils.marshaller(ex.grpc.Helloworld.HelloRequest.PARSER), - com.google.net.stubby.proto.ProtoUtils.marshaller(ex.grpc.Helloworld.HelloReply.PARSER)); - - public static GreeterStub newStub(com.google.net.stubby.Channel channel) { - return new GreeterStub(channel, CONFIG); - } - - public static GreeterBlockingStub newBlockingStub( - com.google.net.stubby.Channel channel) { - return new GreeterBlockingStub(channel, CONFIG); - } - - public static GreeterFutureStub newFutureStub( - com.google.net.stubby.Channel channel) { - return new GreeterFutureStub(channel, CONFIG); - } - - public static final GreeterServiceDescriptor CONFIG = - new GreeterServiceDescriptor(); - - @javax.annotation.concurrent.Immutable - public static class GreeterServiceDescriptor extends - com.google.net.stubby.stub.AbstractServiceDescriptor { - public final com.google.net.stubby.MethodDescriptor sayHello; - - private GreeterServiceDescriptor() { - sayHello = createMethodDescriptor( - "helloworld.Greeter", METHOD_SAY_HELLO); - } - - private GreeterServiceDescriptor( - java.util.Map> methodMap) { - sayHello = (com.google.net.stubby.MethodDescriptor) methodMap.get( - CONFIG.sayHello.getName()); - } - - @java.lang.Override - protected GreeterServiceDescriptor build( - java.util.Map> methodMap) { - return new GreeterServiceDescriptor(methodMap); - } - - @java.lang.Override - public com.google.common.collect.ImmutableList> methods() { - return com.google.common.collect.ImmutableList.>of( - sayHello); - } - } - - public static interface Greeter { - - public void sayHello(ex.grpc.Helloworld.HelloRequest request, - com.google.net.stubby.stub.StreamObserver responseObserver); - } - - public static interface GreeterBlockingClient { - - public ex.grpc.Helloworld.HelloReply sayHello(ex.grpc.Helloworld.HelloRequest request); - } - - public static interface GreeterFutureClient { - - public com.google.common.util.concurrent.ListenableFuture sayHello( - ex.grpc.Helloworld.HelloRequest request); - } - - public static class GreeterStub extends - com.google.net.stubby.stub.AbstractStub - implements Greeter { - private GreeterStub(com.google.net.stubby.Channel channel, - GreeterServiceDescriptor config) { - super(channel, config); - } - - @java.lang.Override - protected GreeterStub build(com.google.net.stubby.Channel channel, - GreeterServiceDescriptor config) { - return new GreeterStub(channel, config); - } - - @java.lang.Override - public void sayHello(ex.grpc.Helloworld.HelloRequest request, - com.google.net.stubby.stub.StreamObserver responseObserver) { - asyncUnaryCall( - channel.newCall(config.sayHello), request, responseObserver); - } - } - - public static class GreeterBlockingStub extends - com.google.net.stubby.stub.AbstractStub - implements GreeterBlockingClient { - private GreeterBlockingStub(com.google.net.stubby.Channel channel, - GreeterServiceDescriptor config) { - super(channel, config); - } - - @java.lang.Override - protected GreeterBlockingStub build(com.google.net.stubby.Channel channel, - GreeterServiceDescriptor config) { - return new GreeterBlockingStub(channel, config); - } - - @java.lang.Override - public ex.grpc.Helloworld.HelloReply sayHello(ex.grpc.Helloworld.HelloRequest request) { - return blockingUnaryCall( - channel.newCall(config.sayHello), request); - } - } - - public static class GreeterFutureStub extends - com.google.net.stubby.stub.AbstractStub - implements GreeterFutureClient { - private GreeterFutureStub(com.google.net.stubby.Channel channel, - GreeterServiceDescriptor config) { - super(channel, config); - } - - @java.lang.Override - protected GreeterFutureStub build(com.google.net.stubby.Channel channel, - GreeterServiceDescriptor config) { - return new GreeterFutureStub(channel, config); - } - - @java.lang.Override - public com.google.common.util.concurrent.ListenableFuture sayHello( - ex.grpc.Helloworld.HelloRequest request) { - return unaryFutureCall( - channel.newCall(config.sayHello), request); - } - } - - public static com.google.net.stubby.ServerServiceDefinition bindService( - final Greeter serviceImpl) { - return com.google.net.stubby.ServerServiceDefinition.builder("helloworld.Greeter") - .addMethod(createMethodDefinition( - METHOD_SAY_HELLO, - asyncUnaryRequestCall( - new com.google.net.stubby.stub.ServerCalls.UnaryRequestMethod< - ex.grpc.Helloworld.HelloRequest, - ex.grpc.Helloworld.HelloReply>() { - @java.lang.Override - public void invoke( - ex.grpc.Helloworld.HelloRequest request, - com.google.net.stubby.stub.StreamObserver responseObserver) { - serviceImpl.sayHello(request, responseObserver); - } - }))).build(); - } -} diff --git a/java/src/main/java/ex/grpc/GreeterImpl.java b/java/src/main/java/ex/grpc/GreeterImpl.java deleted file mode 100644 index 825ba8631ec..00000000000 --- a/java/src/main/java/ex/grpc/GreeterImpl.java +++ /dev/null @@ -1,16 +0,0 @@ -package ex.grpc; - -import com.google.net.stubby.stub.StreamObserver; - -public class GreeterImpl implements GreeterGrpc.Greeter { - - @Override - public void sayHello(Helloworld.HelloRequest req, - StreamObserver responseObserver) { - Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage( - "Hello " + req.getName()).build(); - responseObserver.onValue(reply); - responseObserver.onCompleted(); - } - -} diff --git a/java/src/main/java/ex/grpc/GreeterServer.java b/java/src/main/java/ex/grpc/GreeterServer.java deleted file mode 100644 index bb05680b0a6..00000000000 --- a/java/src/main/java/ex/grpc/GreeterServer.java +++ /dev/null @@ -1,51 +0,0 @@ -package ex.grpc; - -import com.google.common.util.concurrent.MoreExecutors; -import com.google.net.stubby.ServerImpl; -import com.google.net.stubby.transport.netty.NettyServerBuilder; - -import java.util.concurrent.TimeUnit; - -/** - * Server that manages startup/shutdown of a {@code Greeter} server. - */ -public class GreeterServer { - /* The port on which the server should run */ - private int port = 50051; - private ServerImpl server; - - private void start() throws Exception { - server = NettyServerBuilder.forPort(port) - .addService(GreeterGrpc.bindService(new GreeterImpl())) - .build(); - server.startAsync(); - server.awaitRunning(5, TimeUnit.SECONDS); - System.out.println("Server started on port:" + port); - } - - private void stop() throws Exception { - server.stopAsync(); - server.awaitTerminated(); - System.out.println("Server shutting down ..."); - } - - /** - * Main launches the server from the command line. - */ - public static void main(String[] args) throws Exception { - final GreeterServer server = new GreeterServer(); - - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - try { - System.out.println("Shutting down"); - server.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - server.start(); - } -} diff --git a/java/src/main/java/ex/grpc/Helloworld.java b/java/src/main/java/ex/grpc/Helloworld.java deleted file mode 100644 index b25a63fca32..00000000000 --- a/java/src/main/java/ex/grpc/Helloworld.java +++ /dev/null @@ -1,951 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: helloworld.proto - -package ex.grpc; - -public final class Helloworld { - private Helloworld() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - } - public interface HelloRequestOrBuilder extends - // @@protoc_insertion_point(interface_extends:helloworld.HelloRequest) - com.google.protobuf.MessageOrBuilder { - - /** - * optional string name = 1; - */ - java.lang.String getName(); - /** - * optional string name = 1; - */ - com.google.protobuf.ByteString - getNameBytes(); - } - /** - * Protobuf type {@code helloworld.HelloRequest} - * - *
-   * The request message containing the user's name.
-   * 
- */ - public static final class HelloRequest extends - com.google.protobuf.GeneratedMessage implements - // @@protoc_insertion_point(message_implements:helloworld.HelloRequest) - HelloRequestOrBuilder { - // Use HelloRequest.newBuilder() to construct. - private HelloRequest(com.google.protobuf.GeneratedMessage.Builder builder) { - super(builder); - } - private HelloRequest() { - name_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); - } - private HelloRequest( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - int mutable_bitField0_ = 0; - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!input.skipField(tag)) { - done = true; - } - break; - } - case 10: { - com.google.protobuf.ByteString bs = input.readBytes(); - - name_ = bs; - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - ex.grpc.Helloworld.HelloRequest.class, ex.grpc.Helloworld.HelloRequest.Builder.class); - } - - public static final com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - public HelloRequest parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new HelloRequest(input, extensionRegistry); - } - }; - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public static final int NAME_FIELD_NUMBER = 1; - private java.lang.Object name_; - /** - * optional string name = 1; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } - } - /** - * optional string name = 1; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (!getNameBytes().isEmpty()) { - output.writeBytes(1, getNameBytes()); - } - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (!getNameBytes().isEmpty()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(1, getNameBytes()); - } - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - public static ex.grpc.Helloworld.HelloRequest parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static ex.grpc.Helloworld.HelloRequest parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloRequest parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static ex.grpc.Helloworld.HelloRequest parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloRequest parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static ex.grpc.Helloworld.HelloRequest parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloRequest parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static ex.grpc.Helloworld.HelloRequest parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloRequest parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static ex.grpc.Helloworld.HelloRequest parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return new Builder(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(ex.grpc.Helloworld.HelloRequest prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code helloworld.HelloRequest} - * - *
-     * The request message containing the user's name.
-     * 
- */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder implements - // @@protoc_insertion_point(builder_implements:helloworld.HelloRequest) - ex.grpc.Helloworld.HelloRequestOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - ex.grpc.Helloworld.HelloRequest.class, ex.grpc.Helloworld.HelloRequest.Builder.class); - } - - // Construct using ex.grpc.Helloworld.HelloRequest.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - } - } - public Builder clear() { - super.clear(); - name_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloRequest_descriptor; - } - - public ex.grpc.Helloworld.HelloRequest getDefaultInstanceForType() { - return ex.grpc.Helloworld.HelloRequest.getDefaultInstance(); - } - - public ex.grpc.Helloworld.HelloRequest build() { - ex.grpc.Helloworld.HelloRequest result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public ex.grpc.Helloworld.HelloRequest buildPartial() { - ex.grpc.Helloworld.HelloRequest result = new ex.grpc.Helloworld.HelloRequest(this); - result.name_ = name_; - onBuilt(); - return result; - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof ex.grpc.Helloworld.HelloRequest) { - return mergeFrom((ex.grpc.Helloworld.HelloRequest)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(ex.grpc.Helloworld.HelloRequest other) { - if (other == ex.grpc.Helloworld.HelloRequest.getDefaultInstance()) return this; - if (!other.getName().isEmpty()) { - name_ = other.name_; - onChanged(); - } - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - ex.grpc.Helloworld.HelloRequest parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (ex.grpc.Helloworld.HelloRequest) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private java.lang.Object name_ = ""; - /** - * optional string name = 1; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * optional string name = 1; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * optional string name = 1; - */ - public Builder setName( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - - name_ = value; - onChanged(); - return this; - } - /** - * optional string name = 1; - */ - public Builder clearName() { - - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * optional string name = 1; - */ - public Builder setNameBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - - name_ = value; - onChanged(); - return this; - } - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return this; - } - - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return this; - } - - - // @@protoc_insertion_point(builder_scope:helloworld.HelloRequest) - } - - // @@protoc_insertion_point(class_scope:helloworld.HelloRequest) - private static final ex.grpc.Helloworld.HelloRequest defaultInstance;static { - defaultInstance = new ex.grpc.Helloworld.HelloRequest(); - } - - public static ex.grpc.Helloworld.HelloRequest getDefaultInstance() { - return defaultInstance; - } - - public ex.grpc.Helloworld.HelloRequest getDefaultInstanceForType() { - return defaultInstance; - } - - } - - public interface HelloReplyOrBuilder extends - // @@protoc_insertion_point(interface_extends:helloworld.HelloReply) - com.google.protobuf.MessageOrBuilder { - - /** - * optional string message = 1; - */ - java.lang.String getMessage(); - /** - * optional string message = 1; - */ - com.google.protobuf.ByteString - getMessageBytes(); - } - /** - * Protobuf type {@code helloworld.HelloReply} - * - *
-   * The response message containing the greetings
-   * 
- */ - public static final class HelloReply extends - com.google.protobuf.GeneratedMessage implements - // @@protoc_insertion_point(message_implements:helloworld.HelloReply) - HelloReplyOrBuilder { - // Use HelloReply.newBuilder() to construct. - private HelloReply(com.google.protobuf.GeneratedMessage.Builder builder) { - super(builder); - } - private HelloReply() { - message_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); - } - private HelloReply( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - int mutable_bitField0_ = 0; - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!input.skipField(tag)) { - done = true; - } - break; - } - case 10: { - com.google.protobuf.ByteString bs = input.readBytes(); - - message_ = bs; - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_fieldAccessorTable - .ensureFieldAccessorsInitialized( - ex.grpc.Helloworld.HelloReply.class, ex.grpc.Helloworld.HelloReply.Builder.class); - } - - public static final com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - public HelloReply parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new HelloReply(input, extensionRegistry); - } - }; - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public static final int MESSAGE_FIELD_NUMBER = 1; - private java.lang.Object message_; - /** - * optional string message = 1; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - message_ = s; - } - return s; - } - } - /** - * optional string message = 1; - */ - public com.google.protobuf.ByteString - getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (!getMessageBytes().isEmpty()) { - output.writeBytes(1, getMessageBytes()); - } - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (!getMessageBytes().isEmpty()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(1, getMessageBytes()); - } - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - public static ex.grpc.Helloworld.HelloReply parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static ex.grpc.Helloworld.HelloReply parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloReply parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static ex.grpc.Helloworld.HelloReply parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloReply parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static ex.grpc.Helloworld.HelloReply parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloReply parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static ex.grpc.Helloworld.HelloReply parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static ex.grpc.Helloworld.HelloReply parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static ex.grpc.Helloworld.HelloReply parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return new Builder(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(ex.grpc.Helloworld.HelloReply prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code helloworld.HelloReply} - * - *
-     * The response message containing the greetings
-     * 
- */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder implements - // @@protoc_insertion_point(builder_implements:helloworld.HelloReply) - ex.grpc.Helloworld.HelloReplyOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_fieldAccessorTable - .ensureFieldAccessorsInitialized( - ex.grpc.Helloworld.HelloReply.class, ex.grpc.Helloworld.HelloReply.Builder.class); - } - - // Construct using ex.grpc.Helloworld.HelloReply.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - } - } - public Builder clear() { - super.clear(); - message_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return ex.grpc.Helloworld.internal_static_helloworld_HelloReply_descriptor; - } - - public ex.grpc.Helloworld.HelloReply getDefaultInstanceForType() { - return ex.grpc.Helloworld.HelloReply.getDefaultInstance(); - } - - public ex.grpc.Helloworld.HelloReply build() { - ex.grpc.Helloworld.HelloReply result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public ex.grpc.Helloworld.HelloReply buildPartial() { - ex.grpc.Helloworld.HelloReply result = new ex.grpc.Helloworld.HelloReply(this); - result.message_ = message_; - onBuilt(); - return result; - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof ex.grpc.Helloworld.HelloReply) { - return mergeFrom((ex.grpc.Helloworld.HelloReply)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(ex.grpc.Helloworld.HelloReply other) { - if (other == ex.grpc.Helloworld.HelloReply.getDefaultInstance()) return this; - if (!other.getMessage().isEmpty()) { - message_ = other.message_; - onChanged(); - } - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - ex.grpc.Helloworld.HelloReply parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (ex.grpc.Helloworld.HelloReply) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private java.lang.Object message_ = ""; - /** - * optional string message = 1; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - message_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * optional string message = 1; - */ - public com.google.protobuf.ByteString - getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * optional string message = 1; - */ - public Builder setMessage( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - - message_ = value; - onChanged(); - return this; - } - /** - * optional string message = 1; - */ - public Builder clearMessage() { - - message_ = getDefaultInstance().getMessage(); - onChanged(); - return this; - } - /** - * optional string message = 1; - */ - public Builder setMessageBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - - message_ = value; - onChanged(); - return this; - } - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return this; - } - - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return this; - } - - - // @@protoc_insertion_point(builder_scope:helloworld.HelloReply) - } - - // @@protoc_insertion_point(class_scope:helloworld.HelloReply) - private static final ex.grpc.Helloworld.HelloReply defaultInstance;static { - defaultInstance = new ex.grpc.Helloworld.HelloReply(); - } - - public static ex.grpc.Helloworld.HelloReply getDefaultInstance() { - return defaultInstance; - } - - public ex.grpc.Helloworld.HelloReply getDefaultInstanceForType() { - return defaultInstance; - } - - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_helloworld_HelloRequest_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable - internal_static_helloworld_HelloRequest_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_helloworld_HelloReply_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable - internal_static_helloworld_HelloReply_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - java.lang.String[] descriptorData = { - "\n\020helloworld.proto\022\nhelloworld\"\034\n\014HelloR" + - "equest\022\014\n\004name\030\001 \001(\t\"\035\n\nHelloReply\022\017\n\007me" + - "ssage\030\001 \001(\t2I\n\007Greeter\022>\n\010sayHello\022\030.hel" + - "loworld.HelloRequest\032\026.helloworld.HelloR" + - "eply\"\000B\t\n\007ex.grpcb\006proto3" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_helloworld_HelloRequest_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_helloworld_HelloRequest_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_helloworld_HelloRequest_descriptor, - new java.lang.String[] { "Name", }); - internal_static_helloworld_HelloReply_descriptor = - getDescriptor().getMessageTypes().get(1); - internal_static_helloworld_HelloReply_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_helloworld_HelloReply_descriptor, - new java.lang.String[] { "Message", }); - } - - // @@protoc_insertion_point(outer_class_scope) -} From 3ae2147cbcec04605d30fb6f60e51d01f233119f Mon Sep 17 00:00:00 2001 From: Jayant Kolhe Date: Wed, 25 Feb 2015 11:29:45 -0800 Subject: [PATCH 159/576] Update README.md Fixed repository listed in command line. --- cpp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/README.md b/cpp/README.md index 759e10bfe1f..e9e9962a9bc 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -15,7 +15,7 @@ following command: ```sh -$ git clone https://github.com/google/grpc-common.git +$ git clone https://github.com/grpc/grpc-common.git ``` Change your current directory to grpc-common/cpp/helloworld From b99d48190463c3cce7f4646f715a8a723924d192 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Wed, 25 Feb 2015 11:59:08 -0800 Subject: [PATCH 160/576] Update grpc-auth-support.md Fix method name. --- grpc-auth-support.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 9850b8b24ef..59d690d8a52 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -54,7 +54,7 @@ passed to the factory method. gRPC applications can use a simple API to create a credential that works in various deployment scenarios. ``` -std::unique_ptr creds = CredentialsFactory::DefaultGoogleCredentials(); +std::unique_ptr creds = GoogleDefaultGoogleDefaultCredentials(); // Create a channel, stub and make RPC calls (same as in the previous example) std::shared_ptr channel = CreateChannel(server_name, creds, channel_args); std::unique_ptr stub(Greeter::NewStub(channel)); From a08dc0a6ca1eebda2591d26bb0d3c8ce1db08a82 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Wed, 25 Feb 2015 12:00:47 -0800 Subject: [PATCH 161/576] Update grpc-auth-support.md Fix the method name, for real this time. --- grpc-auth-support.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 59d690d8a52..b1b576e7424 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -54,7 +54,7 @@ passed to the factory method. gRPC applications can use a simple API to create a credential that works in various deployment scenarios. ``` -std::unique_ptr creds = GoogleDefaultGoogleDefaultCredentials(); +std::unique_ptr creds = CredentialsFactory::GoogleDefaultCredentials(); // Create a channel, stub and make RPC calls (same as in the previous example) std::shared_ptr channel = CreateChannel(server_name, creds, channel_args); std::unique_ptr stub(Greeter::NewStub(channel)); From d84e9cede8d49a0e4e5f190a5dac793b03bb0403 Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Wed, 25 Feb 2015 12:13:03 -0800 Subject: [PATCH 162/576] Update README.md --- node/README.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/node/README.md b/node/README.md index f9df3b0a81d..076755a695f 100644 --- a/node/README.md +++ b/node/README.md @@ -10,9 +10,21 @@ INSTALL ------- - Clone this repository + + ```sh + $ git clone https://github.com/grpc/grpc-common.git + ``` - Follow the instructions in [INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL) to install the gRPC C core. - - Run `npm install` to install dependencies - - If `grpc` is not found, clone the [gRPC](https://github.com/grpc/grpc) repository and run `npm install path/to/grpc/src/node`. + - Install + + ```sh + $ cd grpc-common/node + $ npm install + # If node is not found, you'll need to clone the grpc repository (if you haven't already) + $ git clone https://github.com/grpc/grpc.git + $ npm install ~/grpc/src/node + ``` + Try it! ------- From ecc3d900ea81bf157d1f5c4fc0d16863d29fda14 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Wed, 25 Feb 2015 12:19:50 -0800 Subject: [PATCH 163/576] Update grpc-auth-support.md Address previous TODOs by providing the actual environment variable name and file path name where the service account keys are loaded from. --- grpc-auth-support.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 9850b8b24ef..a43f873e5d6 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -63,11 +63,13 @@ grpc::Status s = stub->sayHello(&context, *request, response); This credential works for applications using Service Accounts as well as for applications running in Google Compute Engine (GCE). In the former case, the -service account’s private keys are expected in file located at [TODO: well -known file fath for service account keys] or in the file named in the environment -variable [TODO: add the env var name here]. The keys are used at run-time to -generate bearer tokens that are attached to each outgoing RPC on the -corresponding channel. +service account’s private keys are loaded from the file named in the environment +variable `GOOGLE_APPLICATION_CREDENTIALS`. If that environment variable is not +set, the library attempts to load the keys from the file located at +`/.config/gcloud/application_default_credentials.json` where `` is +the relative path specified in the environment variable `HOME`. Once loaded, the +keys are used to generate bearer tokens that are attached to each outgoing RPC +on the corresponding channel. For applications running in GCE, a default service account and corresponding OAuth scopes can be configured during VM setup. At run-time, this credential From 03f702f5eab794b4ae720569da289dfaf0927dca Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Wed, 25 Feb 2015 12:48:44 -0800 Subject: [PATCH 164/576] Update grpc-auth-support.md --- grpc-auth-support.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index a43f873e5d6..8d715804d50 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -64,10 +64,7 @@ grpc::Status s = stub->sayHello(&context, *request, response); This credential works for applications using Service Accounts as well as for applications running in Google Compute Engine (GCE). In the former case, the service account’s private keys are loaded from the file named in the environment -variable `GOOGLE_APPLICATION_CREDENTIALS`. If that environment variable is not -set, the library attempts to load the keys from the file located at -`/.config/gcloud/application_default_credentials.json` where `` is -the relative path specified in the environment variable `HOME`. Once loaded, the +variable `GOOGLE_APPLICATION_CREDENTIALS`. The keys are used to generate bearer tokens that are attached to each outgoing RPC on the corresponding channel. From 038b0df466bd70663f7917a5e43901fea413c353 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:20:20 +0000 Subject: [PATCH 165/576] Update javatutorial.md Updated with @nmittler's edits. --- java/javatutorial.md | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/java/javatutorial.md b/java/javatutorial.md index e74573e0b44..7465a8ab0eb 100644 --- a/java/javatutorial.md +++ b/java/javatutorial.md @@ -6,7 +6,7 @@ This tutorial provides a basic Java programmer's introduction to working with gR - Generate server and client code using the protocol buffer compiler. - Use the Java gRPC API to write a simple client and server for your service. -It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release: you can see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository. +It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the [proto3](https://github.com/google/protobuf/releases) version of the protocol buffers language, which is currently in alpha release: you can see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository. This isn't a comprehensive guide to using gRPC in Java: more reference documentation is coming soon. @@ -36,7 +36,7 @@ You also should have the relevant tools installed to generate the server and cli Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-java/examples/src/main/proto/route_guide.proto`](https://github.com/grpc/grpc-java/blob/master/examples/src/main/proto/route_guide.proto). As we're generating Java code in this example, we've specified a `java_package` file option in our .proto: -``` +```proto option java_package = "io.grpc.examples"; ``` @@ -44,7 +44,7 @@ This specifies the package we want to use for our generated Java classes. If no To define a service, we specify a named `service` in the .proto file: -``` +```proto service RouteGuide { ... } @@ -53,13 +53,13 @@ service RouteGuide { Then we define `rpc` methods inside our service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service: - A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. -``` - // Obtains the feature at a given position. +```proto + // Obtains the feature at a given position. rpc GetFeature(Point) returns (Feature) {} ``` - A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. -``` +```proto // Obtains the Features available within the given Rectangle. Results are // streamed rather than returned at once (e.g. in a response message with a // repeated field), as the rectangle may cover a large area and contain a @@ -68,21 +68,21 @@ Then we define `rpc` methods inside our service definition, specifying their req ``` - A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type. -``` +```proto // Accepts a stream of Points on a route being traversed, returning a // RouteSummary when traversal is completed. rpc RecordRoute(stream Point) returns (RouteSummary) {} ``` - A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. -``` +```proto // Accepts a stream of RouteNotes sent while a route is being traversed, // while receiving other RouteNotes (e.g. from other users). rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} ``` Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: -``` +```proto // Points are represented as latitude-longitude pairs in the E7 representation // (degrees multiplied by 10**7 and rounded to the nearest integer). // Latitudes should be in the range +/- 90 degrees and longitude should be in @@ -109,7 +109,7 @@ which actually runs: [actual command] Running this command generates the following files: -- `RouteGuideOuterClass.java` [cheeeeeeck], which contains all the protocol buffer code to populate, serialize, and retrieve our request and response message types +- `RouteGuideOuterClass.java`, which contains all the protocol buffer code to populate, serialize, and retrieve our request and response message types - `RouteGuideGrpc.java` which contains (along with some other useful code): - an interface for `RouteGuide` servers to implement, `RouteGuideGrpc.Service`, with all the methods defined in the `RouteGuide` service. - *stub* classes that clients can use to talk to a `RouteGuide` server. These also implement the `RouteGuide` interface. @@ -135,7 +135,7 @@ private static class RouteGuideService implements RouteGuideGrpc.RouteGuide { ... } ``` - +#### Simple RPC `RouteGuideService` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. ```java @@ -170,7 +170,8 @@ To return our response to the client and complete the call: 2. We use the response observer's `onValue()` method to return the `Feature`. 3. We use the response observer's `onCompleted()` method to specify that we've finished dealing with the RPC. -Next let's look at a streaming RPC. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. +#### Server-side streaming RPC +Next let's look at one of our streaming RPCs. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. ```java private final Collection features; @@ -203,6 +204,7 @@ Like the simple RPC, this method gets a request object (the `Rectangle` in which This time, we get as many `Feature` objects as we need to return to the client (in this case, we select them from the service's feature collection based on whether they're inside our request `Rectangle`), and write them each in turn to the response observer using its `Write()` method. Finally, as in our simple RPC, we use the response observer's `onCompleted()` method to tell gRPC that we've finished writing responses. +#### Client-side streaming RPC Now let's look at something a little more complicated: the client-side streaming method `RecordRoute`, where we get a stream of `Point`s from the client and return a single `RouteSummary` with information about their trip. ```java @@ -252,6 +254,7 @@ In the method body we instantiate an anonymous `StreamObserver` to return, in wh - Override the `onValue()` method to get features and other information each time the client writes a `Point` to the message stream. - Override the `onCompleted()` method (called when the *client* has finished writing messages) to populate and build our `RouteSummary`. We then call our method's own response observer's `onValue()` with our `RouteSummary`, and then call its `onCompleted()` method to finish the call from the server side. +#### Bidirectional streaming RPC Finally, let's look at our bidirectional streaming RPC `RouteChat()`. ```cpp @@ -299,7 +302,9 @@ Once we've implemented all our methods, we also need to start up a gRPC server s ... } ``` -As you can see, we build and start our server using a `NettyServerBuilder`. To do this, we: +As you can see, we build and start our server using a `NettyServerBuilder`. This is a builder for servers based on the [Netty](http://netty.io/) transport framework. + +To do this, we: 1. Create an instance of our service implementation class `RouteGuideService` and pass it to the generated `RouteGuideGrpc` class's static `bindService()` method to get a service definition. 3. Specify the address and port we want to use to listen for client requests using the builder's `forPort()` method. @@ -340,12 +345,19 @@ Now let's look at how we call our service methods. -#### Streaming RPCs +#### Server-side streaming RPC + + + +#### Client-side streaming RPC + + +#### Bidirectional streaming RPC ## Try it out! -_[need build and run instructions here]_ +Follow the instructions in the example directory [README](https://github.com/grpc/grpc-java/blob/master/examples/README.md) to build and run the client and server From c4b28a9d362dab6128ca25a7cc912685860d6e92 Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Wed, 25 Feb 2015 14:22:46 -0800 Subject: [PATCH 166/576] Update README.md Added a background section. --- go/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/go/README.md b/go/README.md index 9fc49474d79..2ef89ff7a41 100644 --- a/go/README.md +++ b/go/README.md @@ -1,6 +1,10 @@ gRPC in 3 minutes (Go) ====================== +BACKGROUND +------------- +For this sample, we've already generated the server and client stubs from [helloworld.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto). + PREREQUISITES ------------- From 41df7de1a2d9077c66f7ae9d2d3a07f56f944067 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:25:47 +0000 Subject: [PATCH 167/576] Added note about using most recent compiler --- java/javatutorial.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/javatutorial.md b/java/javatutorial.md index 7465a8ab0eb..0b4fac0e69d 100644 --- a/java/javatutorial.md +++ b/java/javatutorial.md @@ -96,7 +96,7 @@ message Point { ## Generating client and server code -Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Java plugin. +Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Java plugin. Note that you need to use [version 3](https://github.com/google/protobuf/releases) of `protoc` in order to use the plugin. For simplicity, we've provided a [Gradle build file](https://github.com/grpc/grpc-java/blob/master/examples/build.gradle) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc-java) first): @@ -357,7 +357,7 @@ Now let's look at how we call our service methods. ## Try it out! -Follow the instructions in the example directory [README](https://github.com/grpc/grpc-java/blob/master/examples/README.md) to build and run the client and server +Follow the instructions in the example directory [README](https://github.com/grpc/grpc-java/blob/master/examples/README.md) to build and run the client and server. From e0faf3166b4cc77723abd5782639851a05cda4e8 Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Wed, 25 Feb 2015 14:29:11 -0800 Subject: [PATCH 168/576] Update README.md --- java/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/java/README.md b/java/README.md index 89724904d46..4c5e4c5902b 100644 --- a/java/README.md +++ b/java/README.md @@ -1,6 +1,10 @@ gRPC in 3 minutes (Java) ======================== +BACKGROUND +------------- +For this sample, we've already generated the server and client stubs from [helloworld.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto). + PREREQUISITES ------------- From b6bcf2e46dd5796f50a1cc2b52d76ddb44b8e874 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:30:00 +0000 Subject: [PATCH 169/576] made last added comment a bit simpler! --- java/javatutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/javatutorial.md b/java/javatutorial.md index 0b4fac0e69d..05c122b8fc1 100644 --- a/java/javatutorial.md +++ b/java/javatutorial.md @@ -96,7 +96,7 @@ message Point { ## Generating client and server code -Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Java plugin. Note that you need to use [version 3](https://github.com/google/protobuf/releases) of `protoc` in order to use the plugin. +Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Java plugin. You need to use the [proto3](https://github.com/google/protobuf/releases) compiler in order to generate gRPC services For simplicity, we've provided a [Gradle build file](https://github.com/grpc/grpc-java/blob/master/examples/build.gradle) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc-java) first): From 8813157abe55748c25210973b8636b1e8fb476ce Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:34:56 +0000 Subject: [PATCH 170/576] changed gradle command to ./gradlew --- java/javatutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/javatutorial.md b/java/javatutorial.md index 05c122b8fc1..d4f3216d464 100644 --- a/java/javatutorial.md +++ b/java/javatutorial.md @@ -101,7 +101,7 @@ Next we need to generate the gRPC client and server interfaces from our .proto s For simplicity, we've provided a [Gradle build file](https://github.com/grpc/grpc-java/blob/master/examples/build.gradle) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc-java) first): ```shell -gradle build +../gradlew build ``` which actually runs: From 5d6398c3ba5585a4f1042d579e744ee20168c407 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:39:07 +0000 Subject: [PATCH 171/576] small fixes --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 7360182c56c..f60e9c7176b 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,6 @@ Hello World method. - Create a Java client that accesses the Java server. - Create a Go client that accesses the same Java server. -- Update the service with a streaming RPC. The complete code for the example is available in the `grpc-common` GitHub repository. We use the Git versioning system for source code management: @@ -290,7 +289,7 @@ public static class GreeterStub extends Now let's write some code! First we'll create a server application to implement our service. Note that we're not going to go into a lot of detail about how to create a server in this section. More detailed information will be in the -tutorial for your chosen language (coming soon). +tutorial for your chosen language: check if there's one available yet in the relevant [quick start](#quickstart). Our server application has two classes: From 7dfd4abba5174bc73f848b898fce284493ae44fe Mon Sep 17 00:00:00 2001 From: Jan Tattermusch Date: Wed, 25 Feb 2015 15:00:46 -0800 Subject: [PATCH 172/576] added python helloworld --- python/helloworld/.gitignore | 1 + python/helloworld/README.md | 111 +++++++++++++++++++ python/helloworld/greeter_client.py | 44 ++++++++ python/helloworld/greeter_server.py | 56 ++++++++++ python/helloworld/helloworld.proto | 49 +++++++++ python/helloworld/helloworld_pb2.py | 158 ++++++++++++++++++++++++++++ python/helloworld/run_client.sh | 8 ++ python/helloworld/run_codegen.sh | 4 + python/helloworld/run_server.sh | 9 ++ 9 files changed, 440 insertions(+) create mode 100644 python/helloworld/.gitignore create mode 100644 python/helloworld/README.md create mode 100755 python/helloworld/greeter_client.py create mode 100644 python/helloworld/greeter_server.py create mode 100644 python/helloworld/helloworld.proto create mode 100644 python/helloworld/helloworld_pb2.py create mode 100755 python/helloworld/run_client.sh create mode 100755 python/helloworld/run_codegen.sh create mode 100755 python/helloworld/run_server.sh diff --git a/python/helloworld/.gitignore b/python/helloworld/.gitignore new file mode 100644 index 00000000000..0d20b6487c6 --- /dev/null +++ b/python/helloworld/.gitignore @@ -0,0 +1 @@ +*.pyc diff --git a/python/helloworld/README.md b/python/helloworld/README.md new file mode 100644 index 00000000000..2bbfc4b0178 --- /dev/null +++ b/python/helloworld/README.md @@ -0,0 +1,111 @@ +# gRPC Python Hello World Tutorial + +### Install gRPC +Make sure you have built gRPC Python from source on your system. Follow the instructions here: +[https://github.com/grpc/grpc/blob/master/src/python/README.md](https://github.com/grpc/grpc/blob/master/src/python/README.md). + +This gives you a python virtual environment with installed gRPC Python +in GRPC_ROOT/python2.7_virtual_environment. GRPC_ROOT is the path to which you +have cloned the [gRPC git repo](https://github.com/grpc/grpc). + +### Get the tutorial source code + +The example code for this and our other examples live in the `grpc-common` +GitHub repository. Clone this repository to your local machine by running the +following command: + + +```sh +$ git clone https://github.com/google/grpc-common.git +``` + +Change your current directory to grpc-common/python/helloworld + +```sh +$ cd grpc-common/python/helloworld/ +``` + +### Defining a service + +The first step in creating our example is to define a *service*: an RPC +service specifies the methods that can be called remotely with their parameters +and return types. As you saw in the +[overview](#protocolbuffers) above, gRPC does this using [protocol +buffers](https://developers.google.com/protocol-buffers/docs/overview). We +use the protocol buffers interface definition language (IDL) to define our +service methods, and define the parameters and return +types as protocol buffer message types. Both the client and the +server use interface code generated from the service definition. + +Here's our example service definition, defined using protocol buffers IDL in +[helloworld.proto](https://github.com/grpc/grpc-common/blob/master/python/helloworld/helloworld.proto). The `Greeting` +service has one method, `hello`, that lets the server receive a single +`HelloRequest` +message from the remote client containing the user's name, then send back +a greeting in a single `HelloReply`. This is the simplest type of RPC you +can specify in gRPC. + +``` +syntax = "proto2"; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply) {} +} + +// The request message containing the user's name. +message HelloRequest { + optional string name = 1; +} + +// The response message containing the greetings +message HelloReply { + optional string message = 1; +} + +``` + + +### Generating gRPC code + +Once we've defined our service, we use the protocol buffer compiler +`protoc` to generate the special client and server code we need to create +our application. The generated code contains both stub code for clients to +use and an abstract interface for servers to implement, both with the method +defined in our `Greeting` service. + +To generate the client and server side interfaces: + +```sh +$ ./run_codegen.sh +``` +Which internally invokes the proto-compiler as: + +```sh +$ protoc -I . --python_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_python_plugin` helloworld.proto +``` + +Optionally, you can just skip the code generation step as the generated python module has already +been generated for you (helloworld_pb2.py). + +### The client + +Client-side code can be found in [greeter_client.py](https://github.com/grpc/grpc-common/blob/master/python/helloworld/greeter_client.py). + +You can run the client using: + +```sh +$ ./run_client.sh +``` + + +### The server + +Server side code can be found in [greeter_server.py](https://github.com/grpc/grpc-common/blob/master/python/helloworld/greeter_server.py). + +You can run the server using: + +```sh +$ ./run_server.sh +``` diff --git a/python/helloworld/greeter_client.py b/python/helloworld/greeter_client.py new file mode 100755 index 00000000000..370ce467703 --- /dev/null +++ b/python/helloworld/greeter_client.py @@ -0,0 +1,44 @@ +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""The Python implementation of the GRPC helloworld.Greeter client.""" + +import helloworld_pb2 + +_TIMEOUT_SECONDS = 10 + + +def run(): + with helloworld_pb2.early_adopter_create_Greeter_stub('localhost', 50051) as stub: + response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), _TIMEOUT_SECONDS) + print "Greeter client received: " + response.message + + +if __name__ == '__main__': + run() diff --git a/python/helloworld/greeter_server.py b/python/helloworld/greeter_server.py new file mode 100644 index 00000000000..81353666b10 --- /dev/null +++ b/python/helloworld/greeter_server.py @@ -0,0 +1,56 @@ +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""The Python implementation of the GRPC helloworld.Greeter server.""" + +import time + +import helloworld_pb2 + +_ONE_DAY_IN_SECONDS = 60 * 60 * 24 + + +class Greeter(helloworld_pb2.EarlyAdopterGreeterServicer): + + def SayHello(self, request, context): + return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) + + +def serve(): + server = helloworld_pb2.early_adopter_create_Greeter_server( + Greeter(), 50051, None, None) + server.start() + try: + while True: + time.sleep(_ONE_DAY_IN_SECONDS) + except KeyboardInterrupt: + server.stop() + +if __name__ == '__main__': + serve() diff --git a/python/helloworld/helloworld.proto b/python/helloworld/helloworld.proto new file mode 100644 index 00000000000..1ade8fb2acb --- /dev/null +++ b/python/helloworld/helloworld.proto @@ -0,0 +1,49 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +//TODO: see https://github.com/grpc/grpc/issues/814 +//package examples; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply) {} +} + +// The request message containing the user's name. +message HelloRequest { + optional string name = 1; +} + +// The response message containing the greetings +message HelloReply { + optional string message = 1; +} diff --git a/python/helloworld/helloworld_pb2.py b/python/helloworld/helloworld_pb2.py new file mode 100644 index 00000000000..d35ebb77c66 --- /dev/null +++ b/python/helloworld/helloworld_pb2.py @@ -0,0 +1,158 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: helloworld.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='helloworld.proto', + package='', + serialized_pb=_b('\n\x10helloworld.proto\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t23\n\x07Greeter\x12(\n\x08SayHello\x12\r.HelloRequest\x1a\x0b.HelloReply\"\x00') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_HELLOREQUEST = _descriptor.Descriptor( + name='HelloRequest', + full_name='HelloRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='HelloRequest.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + serialized_start=20, + serialized_end=48, +) + + +_HELLOREPLY = _descriptor.Descriptor( + name='HelloReply', + full_name='HelloReply', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='message', full_name='HelloReply.message', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + serialized_start=50, + serialized_end=79, +) + +DESCRIPTOR.message_types_by_name['HelloRequest'] = _HELLOREQUEST +DESCRIPTOR.message_types_by_name['HelloReply'] = _HELLOREPLY + +HelloRequest = _reflection.GeneratedProtocolMessageType('HelloRequest', (_message.Message,), dict( + DESCRIPTOR = _HELLOREQUEST, + __module__ = 'helloworld_pb2' + # @@protoc_insertion_point(class_scope:HelloRequest) + )) +_sym_db.RegisterMessage(HelloRequest) + +HelloReply = _reflection.GeneratedProtocolMessageType('HelloReply', (_message.Message,), dict( + DESCRIPTOR = _HELLOREPLY, + __module__ = 'helloworld_pb2' + # @@protoc_insertion_point(class_scope:HelloReply) + )) +_sym_db.RegisterMessage(HelloReply) + + +import abc +from grpc._adapter import fore +from grpc._adapter import rear +from grpc.framework.assembly import implementations +from grpc.framework.assembly import utilities +class EarlyAdopterGreeterServicer(object): + """""" + __metaclass__ = abc.ABCMeta + @abc.abstractmethod + def SayHello(self, request): + raise NotImplementedError() +class EarlyAdopterGreeterServer(object): + """""" + __metaclass__ = abc.ABCMeta + @abc.abstractmethod + def start(self): + raise NotImplementedError() + @abc.abstractmethod + def stop(self): + raise NotImplementedError() +class EarlyAdopterGreeterStub(object): + """""" + __metaclass__ = abc.ABCMeta + @abc.abstractmethod + def SayHello(self, request): + raise NotImplementedError() + SayHello.async = None +def early_adopter_create_Greeter_server(servicer, port, root_certificates, key_chain_pairs): + method_implementations = { + "SayHello": utilities.unary_unary_inline(servicer.SayHello), + } + import helloworld_pb2 + request_deserializers = { + "SayHello": helloworld_pb2.HelloRequest.FromString, + } + response_serializers = { + "SayHello": lambda x: x.SerializeToString(), + } + link = fore.activated_fore_link(port, request_deserializers, response_serializers, root_certificates, key_chain_pairs) + return implementations.assemble_service(method_implementations, link) +def early_adopter_create_Greeter_stub(host, port): + method_implementations = { + "SayHello": utilities.unary_unary_inline(None), + } + import helloworld_pb2 + response_deserializers = { + "SayHello": helloworld_pb2.HelloReply.FromString, + } + request_serializers = { + "SayHello": lambda x: x.SerializeToString(), + } + link = rear.activated_rear_link(host, port, request_serializers, response_deserializers) + return implementations.assemble_dynamic_inline_stub(method_implementations, link) +# @@protoc_insertion_point(module_scope) diff --git a/python/helloworld/run_client.sh b/python/helloworld/run_client.sh new file mode 100755 index 00000000000..095e6bc2f0e --- /dev/null +++ b/python/helloworld/run_client.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +# This is where you have cloned out the https://github.com/grpc/grpc repository +# And built gRPC Python. +# ADJUST THIS PATH TO WHERE YOUR ACTUAL LOCATION IS +GRPC_ROOT=~/github/grpc + +$GRPC_ROOT/python2.7_virtual_environment/bin/python greeter_client.py diff --git a/python/helloworld/run_codegen.sh b/python/helloworld/run_codegen.sh new file mode 100755 index 00000000000..ed40386bc0c --- /dev/null +++ b/python/helloworld/run_codegen.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +# Runs the protoc with gRPC plugin to generate protocol messages and gRPC stubs. +protoc -I . --python_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_python_plugin` helloworld.proto diff --git a/python/helloworld/run_server.sh b/python/helloworld/run_server.sh new file mode 100755 index 00000000000..13b009e6cc7 --- /dev/null +++ b/python/helloworld/run_server.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# This is where you have cloned out the https://github.com/grpc/grpc repository +# And built gRPC Python. +# ADJUST THIS PATH TO WHERE YOUR ACTUAL LOCATION IS +GRPC_ROOT=~/github/grpc + +$GRPC_ROOT/python2.7_virtual_environment/bin/python greeter_server.py + From 1a0043c84826fc155fe980af0a76ee5a6ef0e876 Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Wed, 25 Feb 2015 15:16:07 -0800 Subject: [PATCH 173/576] Added route guide tutorial for Node.js --- node/route_guide/README.md | 375 +++++++++++++++++++++++++++++++++++++ 1 file changed, 375 insertions(+) create mode 100644 node/route_guide/README.md diff --git a/node/route_guide/README.md b/node/route_guide/README.md new file mode 100644 index 00000000000..175431258d2 --- /dev/null +++ b/node/route_guide/README.md @@ -0,0 +1,375 @@ +#gRPC Basics: Node.js + +This tutorial provides a basic Node.js programmer's introduction to working with gRPC. By walking through this example you'll learn how to: + +- Define a service in a .proto file. +- Generate server and client code using the protocol buffer compiler. +- Use the C++ gRPC API to write a simple client and server for your service. + +It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release: you can see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository. + +This isn't a comprehensive guide to using gRPC in Node.js: more reference documentation is coming soon. + +## Why use gRPC? + +Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. + +With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. + +## Example code and setup + +The example code for our tutorial is in [grpc/grpc-common/node/route_guide](https://github.com/grpc/grpc-common/tree/master/node/route_guide). To download the example, clone the `grpc-common` repository by running the following command: +```shell +$ git clone https://github.com/google/grpc-common.git +``` + +Then change your current directory to `grpc-common/node/route_guide`: +```shell +$ cd grpc-common/node/route_guide +``` + +You also should have the relevant tools installed to generate the server and client interface code - if yofu don't already, follow the setup instructions in [the Node.js quick start guide](https://github.com/grpc/grpc-common/tree/master/node). + + +## Defining the service + +Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto). + +To define a service, you specify a named `service` in your .proto file: + +```protobuf +service RouteGuide { + ... +} +``` + +Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service: + +- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. +```protobuf + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) {} +``` + +- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. +```protobuf + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) {} +``` + +- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type. +```protobuf + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} +``` + +- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. +```protobuf + // Accepts a stream of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} +``` + +Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: +```protobuf +// Points are represented as latitude-longitude pairs in the E7 representation +// (degrees multiplied by 10**7 and rounded to the nearest integer). +// Latitudes should be in the range +/- 90 degrees and longitude should be in +// the range +/- 180 degrees (inclusive). +message Point { + int32 latitude = 1; + int32 longitude = 2; +} +``` + + +## Generating client and server code + +Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC C++ plugin. + +For simplicity, we've provided a [makefile](https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/Makefile) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first): + +```shell +$ make route_guide.pb.cc +``` + +which actually runs: + +```shell +$ protoc -I ../../protos --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto +``` + +Running this command generates the following files in your current directory: +- `route_guide.pb.h`, the header which declares your generated classes +- `route_guide.pb.cc`, which contains the implementation of your classes + +These contain: +- All the protocol buffer code to populate, serialize, and retrieve our request and response message types +- A class called `RouteGuide` that contains + - a remote interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service. + - two abstract interfaces for servers to implement, also with the methods defined in the `RouteGuide` service. + + + +## Creating the server + +First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!). + +There are two parts to making our `RouteGuide` service do its job: +- Implementing the service interface generated from our service definition: doing the actual "work" of our service. +- Running a gRPC server to listen for requests from clients and return the service responses. + +You can find our example `RouteGuide` server in [grpc-common/node/route_guide/route_guide_server.js](https://github.com/grpc/grpc-common/blob/master/node/route_guide/route_guide_server.js). Let's take a closer look at how it works. + +### Implementing RouteGuide + +As you can see, our server has a `Server` constructor generated from the `RouteGuide.service` descriptor object + +```node +var Server = grpc.buildServer([examples.RouteGuide.service]); +``` +In this case we're implementing the *asynchronous* version of `RouteGuide`, which provides our default gRPC server behaviour. + +The functions in `route_guide_server.js` implement all our service methods. Let's look at the simplest type first, `getFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. + +```node +function checkFeature(point) { + var feature; + // Check if there is already a feature object for the given point + for (var i = 0; i < feature_list.length; i++) { + feature = feature_list[i]; + if (feature.location.latitude === point.latitude && + feature.location.longitude === point.longitude) { + return feature; + } + } + var name = ''; + feature = { + name: name, + location: point + }; + return feature; +} +function getFeature(call, callback) { + callback(null, checkFeature(call.request)); +} +``` + +The method is passed a call object for the RPC, which has the `Point` parameter as a property, and a callback to be passed the resulting `Feature`. In the method we populate a `Feature` corresponding to the given point and pass it to the callback, with a null first parameter to indicate that there is no error. + +Now let's look at something a bit more complicated - a streaming RPC. `listFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. + +```node +function listFeatures(call) { + var lo = call.request.lo; + var hi = call.request.hi; + var left = _.min([lo.longitude, hi.longitude]); + var right = _.max([lo.longitude, hi.longitude]); + var top = _.max([lo.latitude, hi.latitude]); + var bottom = _.min([lo.latitude, hi.latitude]); + // For each feature, check if it is in the given bounding box + _.each(feature_list, function(feature) { + if (feature.name === '') { + return; + } + if (feature.location.longitude >= left && + feature.location.longitude <= right && + feature.location.latitude >= bottom && + feature.location.latitude <= top) { + call.write(feature); + } + }); + call.end(); +} +``` + +As you can see, instead of getting the call object and callback in our method parameters, this time we get a call object that implements the `Writable` interface. In the method, we create as many `Feature` objects as we need to return, writing them to the `call` using its `write()` method. Finally, we call `call.end()` to indicate that we have sent all messages. + +If you look at the client-side streaming method `RecordRoute` you'll see it's quite similar to the unary call, except this time the `call` parameter implements the `Reader` interface. The `call`'s `'data'` event fires every time there is new data, and the `'end'` event fires when all data has been read. Like the unary case, we respond by calling the callback + +```node +call.on('data', function(point) { + // Process user data +}); +call.on('end', function() { + callback(null, result); +}); +``` + +Finally, let's look at our bidirectional streaming RPC `RouteChat()`. + +```node +function routeChat(call) { + call.on('data', function(note) { + var key = pointKey(note.location); + /* For each note sent, respond with all previous notes that correspond to + * the same point */ + if (route_notes.hasOwnProperty(key)) { + _.each(route_notes[key], function(note) { + call.write(note); + }); + } else { + route_notes[key] = []; + } + // Then add the new note to the list + route_notes[key].push(JSON.parse(JSON.stringify(note))); + }); + call.on('end', function() { + call.end(); + }); +} +``` + +This time we get a `call` implementing `Duplex` that can be used to read *and* write messages. The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. + +### Starting the server + +Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service: + +```node +function getServer() { + return new Server({ + 'examples.RouteGuide' : { + getFeature: getFeature, + listFeatures: listFeatures, + recordRoute: recordRoute, + routeChat: routeChat + } + }); +} +var routeServer = getServer(); +routeServer.bind('0.0.0.0:50051'); +routeServer.listen(); +``` + +As you can see, we build and start our server with the following steps: + + 1. Create a `Server` constructor from the `RouteGuide` service descriptor. + 2. Implement the service methods. + 3. Create an instance of the server by calling the `Server` constructor with the method implementations. + 4. Specify the address and port we want to use to listen for client requests using the instance's `bind()` method. + 5. Call `listen()` on the instance to start the RPC server. + + +## Creating the client + +In this section, we'll look at creating a Node.js client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/node/route_guide/route_guide_client.js](https://github.com/grpc/grpc-common/blob/master/node/route_guide/route_guide_client.js). + +### Creating a stub + +To call service methods, we first need to create a *stub*. To do this, we just need to call the RouteGuide stub constructor, specifying the server address and port. + +```node +new example.RouteGuide('localhost:50051'); +``` + +### Calling service methods + +Now let's look at how we call our service methods. Note that all of these methods are asynchronous: they use either events or callbacks to retrieve results. + +#### Simple RPC + +Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method. + +```node +var point = {latitude: 409146138, longitude: -746188906}; +stub.getFeature(point, function(err, feature) { + if (err) { + // process error + } else { + // process feature + } +}); +``` + +As you can see, we create and populate a request object. Finally, we call the method on the stub, passing it the request and callback. If there is no error, then we can read the response information from the server from our response object. + +```node + console.log('Found feature called "' + feature.name + '" at ' + + feature.location.latitude/COORD_FACTOR + ', ' + + feature.location.longitude/COORD_FACTOR); +``` + +#### Streaming RPCs + +Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s: + +```cpp +var call = client.listFeatures(rectangle); + call.on('data', function(feature) { + console.log('Found feature called "' + feature.name + '" at ' + + feature.location.latitude/COORD_FACTOR + ', ' + + feature.location.longitude/COORD_FACTOR); + }); + call.on('end', function() { + // The server has finished sending + }); + call.on('status', function(status) { + // process status + }); +``` + +Instead of passing the method a request and callback, we pass it a request and get a `Readable` stream object back. The client can use the `Readable`'s `'data'` event to read the server's responses. This event fires with each `Feature` message object until there are no more messages: the `'end'` event indicates that the call is done. Finally, the status event fires when the server sends the status. + +The client-side streaming method `RecordRoute` is similar, except there we pass the method a callback and get back a `Writable`. + +```cpp + var call = client.recordRoute(function(error, stats) { + if (error) { + callback(error); + } + console.log('Finished trip with', stats.point_count, 'points'); + console.log('Passed', stats.feature_count, 'features'); + console.log('Travelled', stats.distance, 'meters'); + console.log('It took', stats.elapsed_time, 'seconds'); + }); + function pointSender(lat, lng) { + return function(callback) { + console.log('Visiting point ' + lat/COORD_FACTOR + ', ' + + lng/COORD_FACTOR); + call.write({ + latitude: lat, + longitude: lng + }); + _.delay(callback, _.random(500, 1500)); + }; + } + var point_senders = []; + for (var i = 0; i < num_points; i++) { + var rand_point = feature_list[_.random(0, feature_list.length - 1)]; + point_senders[i] = pointSender(rand_point.location.latitude, + rand_point.location.longitude); + } + async.series(point_senders, function() { + call.end(); + }); +``` + +Once we've finished writing our client's requests to the stream using `write()`, we need to call `end()` on the stream to let gRPC know that we've finished writing. If the status is `OK`, the `stats` object will be populated with the server's response. + +Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `Duplex` stream object, which we can use to both write and read messages. + +```cpp +var call = client.routeChat(); +``` + +The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. + +## Try it out! + +Build client and server: +```shell +$ npm install +``` +Run the server, which will listen on port 50051: +```shell +$ node ./route_guide_server.js +``` +Run the client (in a different terminal): +```shell +$ node ./route_guide_client.js +``` From bc4b1cecb8ea6b4079da023dc70e93c0c8387052 Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Wed, 25 Feb 2015 15:22:58 -0800 Subject: [PATCH 174/576] Update README.md --- ruby/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ruby/README.md b/ruby/README.md index 3818b914330..c5902a3039b 100644 --- a/ruby/README.md +++ b/ruby/README.md @@ -1,6 +1,10 @@ gRPC in 3 minutes (Ruby) ======================== +BACKGROUND +------------- +For this sample, we've already generated the server and client stubs from [helloworld.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto). + PREREQUISITES ------------- From 83fed7a1377b44c23644d78ab13a2b5c713ede8e Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Wed, 25 Feb 2015 15:27:22 -0800 Subject: [PATCH 175/576] Added proto explanation, plus minor corrections --- node/route_guide/README.md | 39 +++++++++++++------------------------- 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/node/route_guide/README.md b/node/route_guide/README.md index 175431258d2..3e0549b19cc 100644 --- a/node/route_guide/README.md +++ b/node/route_guide/README.md @@ -3,8 +3,7 @@ This tutorial provides a basic Node.js programmer's introduction to working with gRPC. By walking through this example you'll learn how to: - Define a service in a .proto file. -- Generate server and client code using the protocol buffer compiler. -- Use the C++ gRPC API to write a simple client and server for your service. +- Use the Node.js gRPC API to write a simple client and server for your service. It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release: you can see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository. @@ -87,32 +86,20 @@ message Point { ``` -## Generating client and server code +## Loading service descriptors from proto files -Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC C++ plugin. +The Node.js library dynamically generates service descriptors and client stub definitions from `.proto` files loaded at runtime. -For simplicity, we've provided a [makefile](https://github.com/grpc/grpc-common/blob/master/cpp/route_guide/Makefile) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first): +To load a `.proto` file, simply `require` the gRPC library, then use its `load()` method to load the proto file: -```shell -$ make route_guide.pb.cc -``` - -which actually runs: - -```shell -$ protoc -I ../../protos --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto +```node +var grpc = require('grpc'); +var protoDescriptor = grpc.load(__dirname + '/route_guide.proto'); +// The protoDescriptor object has the full package hierarchy +var example = protoDescriptor.examples; ``` -Running this command generates the following files in your current directory: -- `route_guide.pb.h`, the header which declares your generated classes -- `route_guide.pb.cc`, which contains the implementation of your classes - -These contain: -- All the protocol buffer code to populate, serialize, and retrieve our request and response message types -- A class called `RouteGuide` that contains - - a remote interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service. - - two abstract interfaces for servers to implement, also with the methods defined in the `RouteGuide` service. - +Then, the stub constructor is in the examples namespace (`protoDescriptor.examples.RouteGuide`) and the service descriptor (which is used to create a server) is a property of the stub (`protoDescriptor.examples.RouteGuide.service`); ## Creating the server @@ -298,7 +285,7 @@ As you can see, we create and populate a request object. Finally, we call the me Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s: -```cpp +```node var call = client.listFeatures(rectangle); call.on('data', function(feature) { console.log('Found feature called "' + feature.name + '" at ' + @@ -317,7 +304,7 @@ Instead of passing the method a request and callback, we pass it a request and g The client-side streaming method `RecordRoute` is similar, except there we pass the method a callback and get back a `Writable`. -```cpp +```node var call = client.recordRoute(function(error, stats) { if (error) { callback(error); @@ -353,7 +340,7 @@ Once we've finished writing our client's requests to the stream using `write()`, Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `Duplex` stream object, which we can use to both write and read messages. -```cpp +```node var call = client.routeChat(); ``` From b224d6a50008f60ebe4983c87d5d386175d9d9c3 Mon Sep 17 00:00:00 2001 From: Daniel Wang Date: Wed, 25 Feb 2015 16:03:09 -0800 Subject: [PATCH 176/576] Update the comment of GetFeature to clarify its unintuitive behavior --- protos/route_guide.proto | 3 +++ 1 file changed, 3 insertions(+) diff --git a/protos/route_guide.proto b/protos/route_guide.proto index 7cda80efad8..37590490f44 100644 --- a/protos/route_guide.proto +++ b/protos/route_guide.proto @@ -38,6 +38,9 @@ service RouteGuide { // A simple RPC. // // Obtains the feature at a given position. + // + // A feature with an empty name is returned if there's no feature at the given + // position. rpc GetFeature(Point) returns (Feature) {} // A server-to-client streaming RPC. From 312f6a585bdfb6a6d9b77b6ed555c67a223564f7 Mon Sep 17 00:00:00 2001 From: Xiao Hang Date: Wed, 25 Feb 2015 16:21:24 -0800 Subject: [PATCH 177/576] gRPC Android Helloworld example --- android/GreeterGrpc.java | 184 ++++++++++++++++++++++++++++++++ android/Helloworld.java | 175 ++++++++++++++++++++++++++++++ android/HelloworldActivity.java | 92 ++++++++++++++++ android/README.md | 72 +++++++++++++ android/activity_helloworld.xml | 54 ++++++++++ 5 files changed, 577 insertions(+) create mode 100644 android/GreeterGrpc.java create mode 100644 android/Helloworld.java create mode 100644 android/HelloworldActivity.java create mode 100644 android/README.md create mode 100644 android/activity_helloworld.xml diff --git a/android/GreeterGrpc.java b/android/GreeterGrpc.java new file mode 100644 index 00000000000..eaef3679d2d --- /dev/null +++ b/android/GreeterGrpc.java @@ -0,0 +1,184 @@ +package io.grpc.examples; + +import static io.grpc.stub.Calls.createMethodDescriptor; +import static io.grpc.stub.Calls.asyncUnaryCall; +import static io.grpc.stub.Calls.asyncServerStreamingCall; +import static io.grpc.stub.Calls.asyncClientStreamingCall; +import static io.grpc.stub.Calls.duplexStreamingCall; +import static io.grpc.stub.Calls.blockingUnaryCall; +import static io.grpc.stub.Calls.blockingServerStreamingCall; +import static io.grpc.stub.Calls.unaryFutureCall; +import static io.grpc.stub.ServerCalls.createMethodDefinition; +import static io.grpc.stub.ServerCalls.asyncUnaryRequestCall; +import static io.grpc.stub.ServerCalls.asyncStreamingRequestCall; + +import java.io.IOException; + +public class GreeterGrpc { + + private static final io.grpc.stub.Method METHOD_SAY_HELLO = + io.grpc.stub.Method.create( + io.grpc.MethodType.UNARY, "SayHello", + io.grpc.nano.NanoUtils.marshaller( + new io.grpc.nano.Parser() { + @Override + public io.grpc.examples.Helloworld.HelloRequest parse(com.google.protobuf.nano.CodedInputByteBufferNano input) throws IOException { + return io.grpc.examples.Helloworld.HelloRequest.parseFrom(input); + } + }), + io.grpc.nano.NanoUtils.marshaller( + new io.grpc.nano.Parser() { + @Override + public io.grpc.examples.Helloworld.HelloReply parse(com.google.protobuf.nano.CodedInputByteBufferNano input) throws IOException { + return io.grpc.examples.Helloworld.HelloReply.parseFrom(input); + } + })); + + public static GreeterStub newStub(io.grpc.Channel channel) { + return new GreeterStub(channel, CONFIG); + } + + public static GreeterBlockingStub newBlockingStub( + io.grpc.Channel channel) { + return new GreeterBlockingStub(channel, CONFIG); + } + + public static GreeterFutureStub newFutureStub( + io.grpc.Channel channel) { + return new GreeterFutureStub(channel, CONFIG); + } + + public static final GreeterServiceDescriptor CONFIG = + new GreeterServiceDescriptor(); + + public static class GreeterServiceDescriptor extends + io.grpc.stub.AbstractServiceDescriptor { + public final io.grpc.MethodDescriptor sayHello; + + private GreeterServiceDescriptor() { + sayHello = createMethodDescriptor( + "helloworld.Greeter", METHOD_SAY_HELLO); + } + + private GreeterServiceDescriptor( + java.util.Map> methodMap) { + sayHello = (io.grpc.MethodDescriptor) methodMap.get( + CONFIG.sayHello.getName()); + } + + @java.lang.Override + protected GreeterServiceDescriptor build( + java.util.Map> methodMap) { + return new GreeterServiceDescriptor(methodMap); + } + + @java.lang.Override + public com.google.common.collect.ImmutableList> methods() { + return com.google.common.collect.ImmutableList.>of( + sayHello); + } + } + + public static interface Greeter { + + public void sayHello(io.grpc.examples.Helloworld.HelloRequest request, + io.grpc.stub.StreamObserver responseObserver); + } + + public static interface GreeterBlockingClient { + + public io.grpc.examples.Helloworld.HelloReply sayHello(io.grpc.examples.Helloworld.HelloRequest request); + } + + public static interface GreeterFutureClient { + + public com.google.common.util.concurrent.ListenableFuture sayHello( + io.grpc.examples.Helloworld.HelloRequest request); + } + + public static class GreeterStub extends + io.grpc.stub.AbstractStub + implements Greeter { + private GreeterStub(io.grpc.Channel channel, + GreeterServiceDescriptor config) { + super(channel, config); + } + + @java.lang.Override + protected GreeterStub build(io.grpc.Channel channel, + GreeterServiceDescriptor config) { + return new GreeterStub(channel, config); + } + + @java.lang.Override + public void sayHello(io.grpc.examples.Helloworld.HelloRequest request, + io.grpc.stub.StreamObserver responseObserver) { + asyncUnaryCall( + channel.newCall(config.sayHello), request, responseObserver); + } + } + + public static class GreeterBlockingStub extends + io.grpc.stub.AbstractStub + implements GreeterBlockingClient { + private GreeterBlockingStub(io.grpc.Channel channel, + GreeterServiceDescriptor config) { + super(channel, config); + } + + @java.lang.Override + protected GreeterBlockingStub build(io.grpc.Channel channel, + GreeterServiceDescriptor config) { + return new GreeterBlockingStub(channel, config); + } + + @java.lang.Override + public io.grpc.examples.Helloworld.HelloReply sayHello(io.grpc.examples.Helloworld.HelloRequest request) { + return blockingUnaryCall( + channel.newCall(config.sayHello), request); + } + } + + public static class GreeterFutureStub extends + io.grpc.stub.AbstractStub + implements GreeterFutureClient { + private GreeterFutureStub(io.grpc.Channel channel, + GreeterServiceDescriptor config) { + super(channel, config); + } + + @java.lang.Override + protected GreeterFutureStub build(io.grpc.Channel channel, + GreeterServiceDescriptor config) { + return new GreeterFutureStub(channel, config); + } + + @java.lang.Override + public com.google.common.util.concurrent.ListenableFuture sayHello( + io.grpc.examples.Helloworld.HelloRequest request) { + return unaryFutureCall( + channel.newCall(config.sayHello), request); + } + } + + public static io.grpc.ServerServiceDefinition bindService( + final Greeter serviceImpl) { + return io.grpc.ServerServiceDefinition.builder("helloworld.Greeter") + .addMethod(createMethodDefinition( + METHOD_SAY_HELLO, + asyncUnaryRequestCall( + new io.grpc.stub.ServerCalls.UnaryRequestMethod< + io.grpc.examples.Helloworld.HelloRequest, + io.grpc.examples.Helloworld.HelloReply>() { + @java.lang.Override + public void invoke( + io.grpc.examples.Helloworld.HelloRequest request, + io.grpc.stub.StreamObserver responseObserver) { + serviceImpl.sayHello(request, responseObserver); + } + }))).build(); + } +} diff --git a/android/Helloworld.java b/android/Helloworld.java new file mode 100644 index 00000000000..35dd5345129 --- /dev/null +++ b/android/Helloworld.java @@ -0,0 +1,175 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! + +package io.grpc.examples; + +@SuppressWarnings("hiding") +public interface Helloworld { + + public static final class HelloRequest extends + com.google.protobuf.nano.MessageNano { + + private static volatile HelloRequest[] _emptyArray; + public static HelloRequest[] emptyArray() { + // Lazily initializes the empty array + if (_emptyArray == null) { + synchronized ( + com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) { + if (_emptyArray == null) { + _emptyArray = new HelloRequest[0]; + } + } + } + return _emptyArray; + } + + // optional string name = 1; + public java.lang.String name; + + public HelloRequest() { + clear(); + } + + public HelloRequest clear() { + name = ""; + cachedSize = -1; + return this; + } + + @Override + public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output) + throws java.io.IOException { + if (!this.name.equals("")) { + output.writeString(1, this.name); + } + super.writeTo(output); + } + + @Override + protected int computeSerializedSize() { + int size = super.computeSerializedSize(); + if (!this.name.equals("")) { + size += com.google.protobuf.nano.CodedOutputByteBufferNano + .computeStringSize(1, this.name); + } + return size; + } + + @Override + public HelloRequest mergeFrom( + com.google.protobuf.nano.CodedInputByteBufferNano input) + throws java.io.IOException { + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + return this; + default: { + if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) { + return this; + } + break; + } + case 10: { + this.name = input.readString(); + break; + } + } + } + } + + public static HelloRequest parseFrom(byte[] data) + throws com.google.protobuf.nano.InvalidProtocolBufferNanoException { + return com.google.protobuf.nano.MessageNano.mergeFrom(new HelloRequest(), data); + } + + public static HelloRequest parseFrom( + com.google.protobuf.nano.CodedInputByteBufferNano input) + throws java.io.IOException { + return new HelloRequest().mergeFrom(input); + } + } + + public static final class HelloReply extends + com.google.protobuf.nano.MessageNano { + + private static volatile HelloReply[] _emptyArray; + public static HelloReply[] emptyArray() { + // Lazily initializes the empty array + if (_emptyArray == null) { + synchronized ( + com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) { + if (_emptyArray == null) { + _emptyArray = new HelloReply[0]; + } + } + } + return _emptyArray; + } + + // optional string message = 1; + public java.lang.String message; + + public HelloReply() { + clear(); + } + + public HelloReply clear() { + message = ""; + cachedSize = -1; + return this; + } + + @Override + public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output) + throws java.io.IOException { + if (!this.message.equals("")) { + output.writeString(1, this.message); + } + super.writeTo(output); + } + + @Override + protected int computeSerializedSize() { + int size = super.computeSerializedSize(); + if (!this.message.equals("")) { + size += com.google.protobuf.nano.CodedOutputByteBufferNano + .computeStringSize(1, this.message); + } + return size; + } + + @Override + public HelloReply mergeFrom( + com.google.protobuf.nano.CodedInputByteBufferNano input) + throws java.io.IOException { + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + return this; + default: { + if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) { + return this; + } + break; + } + case 10: { + this.message = input.readString(); + break; + } + } + } + } + + public static HelloReply parseFrom(byte[] data) + throws com.google.protobuf.nano.InvalidProtocolBufferNanoException { + return com.google.protobuf.nano.MessageNano.mergeFrom(new HelloReply(), data); + } + + public static HelloReply parseFrom( + com.google.protobuf.nano.CodedInputByteBufferNano input) + throws java.io.IOException { + return new HelloReply().mergeFrom(input); + } + } +} diff --git a/android/HelloworldActivity.java b/android/HelloworldActivity.java new file mode 100644 index 00000000000..eb4e93b5552 --- /dev/null +++ b/android/HelloworldActivity.java @@ -0,0 +1,92 @@ +package io.grpc.helloworld; + +import android.content.Context; +import android.support.v7.app.ActionBarActivity; +import android.os.Bundle; +import android.os.AsyncTask; +import android.text.TextUtils; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; + +import io.grpc.ChannelImpl; +import ex.grpc.GreeterGrpc; +import ex.grpc.Helloworld.HelloRequest; +import ex.grpc.Helloworld.HelloReply; +import io.grpc.transport.okhttp.OkHttpChannelBuilder; + +import java.util.concurrent.TimeUnit; + +public class Helloworld extends ActionBarActivity { + private Button mSendButton; + private EditText mHostEdit; + private EditText mPortEdit; + private EditText mMessageEdit; + private TextView mResultText; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_helloworld); + mSendButton = (Button) findViewById(R.id.send_button); + mHostEdit = (EditText) findViewById(R.id.host_edit_text); + mPortEdit = (EditText) findViewById(R.id.port_edit_text); + mMessageEdit = (EditText) findViewById(R.id.message_edit_text); + mResultText = (TextView) findViewById(R.id.grpc_response_text); + } + + public void sendMessage(View view) { + ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) + .hideSoftInputFromWindow(mHostEdit.getWindowToken(), 0); + mSendButton.setEnabled(false); + new GrpcTask().execute(); + } + + private class GrpcTask extends AsyncTask { + private String mHost; + private String mMessage; + private int mPort; + private ChannelImpl mChannel; + + @Override + protected void onPreExecute() { + mHost = mHostEdit.getText().toString(); + mMessage = mMessageEdit.getText().toString(); + String portStr = mPortEdit.getText().toString(); + mPort = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); + mResultText.setText(""); + } + + private String sayHello(ChannelImpl channel) { + GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); + HelloRequest message = new HelloRequest(); + message.name = mMessage; + HelloReply reply = stub.sayHello(message); + return reply.message; + } + + @Override + protected String doInBackground(Void... nothing) { + try { + mChannel = OkHttpChannelBuilder.forAddress(mHost, mPort).build(); + return sayHello(mChannel); + } catch (Exception e) { + return "Failed... : " + e.getMessage(); + } + } + + @Override + protected void onPostExecute(String result) { + try { + mChannel.shutdown().awaitTerminated(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + mResultText.setText(result); + mSendButton.setEnabled(true); + } + } +} \ No newline at end of file diff --git a/android/README.md b/android/README.md new file mode 100644 index 00000000000..013e20c754a --- /dev/null +++ b/android/README.md @@ -0,0 +1,72 @@ +gRPC Hello World Tutorial (gRPC Java on Android) +======================== + +BACKGROUND +------------- +For this sample, we've already generated the server and client stubs from [helloworld.proto](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto). + +PREREQUISITES +------------- +- [Java gRPC](https://github.com/grpc/grpc-java) + +- [Android Tutorial](https://developer.android.com/training/basics/firstapp/index.html) If you're new to Android development + +- We only have Android gRPC client in this example. Please follow examples in other languages to build and run a gRPC server. + +INSTALL +------- +1 Clone the gRPC Java git repo +```sh +$ cd $grpc_java_dir$ +$ git clone https://github.com/grpc/grpc-java +``` + +2 Install gRPC Java, as described in [How to Build](https://github.com/grpc/grpc-java#how-to-build) +```sh +$ # from this dir +$ cd grpc-java +$ # follow the instructions in 'How to Build' +``` + +3 [Create an Android project](https://developer.android.com/training/basics/firstapp/creating-project.html) under your working directory. +- Set Application name to "Helloworld Example" and set Company Domain to "grpc.io". Make sure your package name is "io.grpc.helloworldexample" +- Choose appropriate minimum SDK +- Use Blank Activity +- Set Activity Name to HelloworldActivity +- Set Layout Name to activity_helloworld + +4 Prepare the app +- Clone this git repo +```sh +$ git clone https://github.com/grpc/grpc-common + +``` +- Replace the generated HelloworldActivity.java and activity_helloworld.xml with the two files in this repo +- Copy GreeterGrpc.java and Helloworld.java under $working_dir$/app/src/main/java/io/grpc/examples/ +- In your AndroidManifest.xml, make sure you have +```sh + +``` +added outside your appplication tag + +5 Add dependencies. gRPC Java on Android depends on grpc-java, protobuf nano, okhttp +- Copy grpc-java .jar files to $working_dir$/app/libs/: + - $grpc-java-dir$/core/build/libs/*.jar + - $grpc-java-dir$/stub/build/libs/*.jar + - $grpc-java-dir$/nano/build/libs/*.jar + - $grpc-java-dir$/okhttp/build/libs/*.jar +- Copy or download other dependencies to $working_dir$/app/libs/: + - protobuf nano: +```sh +$ cp ~/.m2/repository/com/google/protobuf/nano/protobuf-javanano/2.6.2-pre/protobuf-javanano-2.6.2-pre.jar $working_dir$/app/libs/ +``` + - [Guava 18](http://search.maven.org/remotecontent?filepath=com/google/guava/guava/18.0/guava-18.0.jar) + - [okhttp 2.2.0](http://repo1.maven.org/maven2/com/squareup/okhttp/okhttp/2.2.0/okhttp-2.2.0.jar) +- Make sure your app/build.gradle contains: +```sh +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) +} +``` + +6 [Run your example app](https://developer.android.com/training/basics/firstapp/running-app.html) diff --git a/android/activity_helloworld.xml b/android/activity_helloworld.xml new file mode 100644 index 00000000000..41411d11aa5 --- /dev/null +++ b/android/activity_helloworld.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + - + - + + + + + + + @@ -47,7 +93,7 @@ - + diff --git a/objective-c/auth_sample/FirstViewController.h b/objective-c/auth_sample/SelectUserViewController.h similarity index 81% rename from objective-c/auth_sample/FirstViewController.h rename to objective-c/auth_sample/SelectUserViewController.h index 9630f4dd179..eb3c2cf5f04 100644 --- a/objective-c/auth_sample/FirstViewController.h +++ b/objective-c/auth_sample/SelectUserViewController.h @@ -31,8 +31,12 @@ * */ +#import #import -@interface FirstViewController : UIViewController - +@interface SelectUserViewController : UIViewController +@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton; +@property(weak, nonatomic) IBOutlet UIButton *signOutButton; +@property(weak, nonatomic) IBOutlet UILabel *mainLabel; +@property(weak, nonatomic) IBOutlet UILabel *subLabel; @end diff --git a/objective-c/auth_sample/FirstViewController.m b/objective-c/auth_sample/SelectUserViewController.m similarity index 58% rename from objective-c/auth_sample/FirstViewController.m rename to objective-c/auth_sample/SelectUserViewController.m index 1237c42fa7c..5e030565ef6 100644 --- a/objective-c/auth_sample/FirstViewController.m +++ b/objective-c/auth_sample/SelectUserViewController.m @@ -31,13 +31,46 @@ * */ -#import "FirstViewController.h" +#import "SelectUserViewController.h" -@implementation FirstViewController +@implementation SelectUserViewController - (void)viewDidLoad { [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. + + self.signOutButton.layer.cornerRadius = 5; + self.signOutButton.hidden = YES; + + // As instructed in https://developers.google.com/identity/sign-in/ios/sign-in + GIDSignIn.sharedInstance.delegate = self; + GIDSignIn.sharedInstance.uiDelegate = self; + + [GIDSignIn.sharedInstance signInSilently]; +} + +- (void)signIn:(GIDSignIn *)signIn +didSignInForUser:(GIDGoogleUser *)user + withError:(NSError *)error { + if (error) { + // The user probably cancelled the sign-in flow. + return; + } + + self.mainLabel.text = [NSString stringWithFormat:@"User: %@", user.profile.email]; + NSString *scopes = [user.accessibleScopes componentsJoinedByString:@", "]; + scopes = scopes.length ? scopes : @"(none)"; + self.subLabel.text = [NSString stringWithFormat:@"Scopes: %@", scopes]; + + self.signInButton.hidden = YES; + self.signOutButton.hidden = NO; +} + +- (IBAction)didTapSignOut { + [GIDSignIn.sharedInstance signOut]; + self.mainLabel.text = @"Please sign in."; + self.subLabel.text = @""; + self.signInButton.hidden = NO; + self.signOutButton.hidden = YES; } @end From 3600977997c6f1b5e9bbdde7513872c276f040eb Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Thu, 11 Jun 2015 13:10:38 -0700 Subject: [PATCH 360/576] Request test scope --- objective-c/auth_sample/SecondViewController.h | 3 ++- objective-c/auth_sample/SecondViewController.m | 4 ++++ .../auth_sample/SelectUserViewController.m | 16 +++++++++++++--- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/objective-c/auth_sample/SecondViewController.h b/objective-c/auth_sample/SecondViewController.h index 06a3ca012a8..3e5ccf95a44 100644 --- a/objective-c/auth_sample/SecondViewController.h +++ b/objective-c/auth_sample/SecondViewController.h @@ -33,6 +33,7 @@ #import -@interface SecondViewController : UIViewController +extern NSString * const kTestScope; +@interface SecondViewController : UIViewController @end diff --git a/objective-c/auth_sample/SecondViewController.m b/objective-c/auth_sample/SecondViewController.m index aa9e5b673e1..d5ba19a7aba 100644 --- a/objective-c/auth_sample/SecondViewController.m +++ b/objective-c/auth_sample/SecondViewController.m @@ -33,6 +33,10 @@ #import "SecondViewController.h" +#import + +NSString * const kTestScope = @"https://www.googleapis.com/auth/xapi.zoo"; + @implementation SecondViewController - (void)viewDidLoad { diff --git a/objective-c/auth_sample/SelectUserViewController.m b/objective-c/auth_sample/SelectUserViewController.m index 5e030565ef6..e54e9f866a5 100644 --- a/objective-c/auth_sample/SelectUserViewController.m +++ b/objective-c/auth_sample/SelectUserViewController.m @@ -33,6 +33,8 @@ #import "SelectUserViewController.h" +#import "SecondViewController.h" + @implementation SelectUserViewController - (void)viewDidLoad { @@ -42,10 +44,16 @@ self.signOutButton.hidden = YES; // As instructed in https://developers.google.com/identity/sign-in/ios/sign-in - GIDSignIn.sharedInstance.delegate = self; - GIDSignIn.sharedInstance.uiDelegate = self; + GIDSignIn *signIn = GIDSignIn.sharedInstance; + signIn.delegate = self; + signIn.uiDelegate = self; + + // As instructed in https://developers.google.com/identity/sign-in/ios/additional-scopes + if (![signIn.scopes containsObject:kTestScope]) { + signIn.scopes = [signIn.scopes arrayByAddingObject:kTestScope]; + } - [GIDSignIn.sharedInstance signInSilently]; + [signIn signInSilently]; } - (void)signIn:(GIDSignIn *)signIn @@ -67,8 +75,10 @@ didSignInForUser:(GIDGoogleUser *)user - (IBAction)didTapSignOut { [GIDSignIn.sharedInstance signOut]; + self.mainLabel.text = @"Please sign in."; self.subLabel.text = @""; + self.signInButton.hidden = NO; self.signOutButton.hidden = YES; } From 64428acf977dfe761cd1348c4486a6a2a6bfcb8e Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Thu, 11 Jun 2015 15:21:55 -0700 Subject: [PATCH 361/576] Add MakeRPCViewController with authenticated RPC --- .../AuthSample.xcodeproj/project.pbxproj | 12 +-- ...ewController.h => MakeRPCViewController.h} | 3 +- .../auth_sample/MakeRPCViewController.m | 89 +++++++++++++++++++ .../Misc/Base.lproj/Main.storyboard | 27 +++--- .../auth_sample/SecondViewController.m | 47 ---------- .../auth_sample/SelectUserViewController.m | 2 +- 6 files changed, 110 insertions(+), 70 deletions(-) rename objective-c/auth_sample/{SecondViewController.h => MakeRPCViewController.h} (93%) create mode 100644 objective-c/auth_sample/MakeRPCViewController.m delete mode 100644 objective-c/auth_sample/SecondViewController.m diff --git a/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj b/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj index dd4778ebeb5..1e983ca3613 100644 --- a/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj +++ b/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj @@ -10,7 +10,7 @@ 63E1E9821B28CB2100EF0978 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 63E1E9811B28CB2100EF0978 /* main.m */; }; 63E1E9851B28CB2100EF0978 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 63E1E9841B28CB2100EF0978 /* AppDelegate.m */; }; 63E1E9881B28CB2100EF0978 /* SelectUserViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 63E1E9871B28CB2100EF0978 /* SelectUserViewController.m */; }; - 63E1E98B1B28CB2100EF0978 /* SecondViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 63E1E98A1B28CB2100EF0978 /* SecondViewController.m */; }; + 63E1E98B1B28CB2100EF0978 /* MakeRPCViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 63E1E98A1B28CB2100EF0978 /* MakeRPCViewController.m */; }; 63E1E98E1B28CB2100EF0978 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 63E1E98C1B28CB2100EF0978 /* Main.storyboard */; }; 63E1E9901B28CB2100EF0978 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 63E1E98F1B28CB2100EF0978 /* Images.xcassets */; }; 63F5DE481B28F5C100CDD07E /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 63F5DE471B28F5C100CDD07E /* GoogleService-Info.plist */; }; @@ -25,8 +25,8 @@ 63E1E9841B28CB2100EF0978 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 63E1E9861B28CB2100EF0978 /* SelectUserViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SelectUserViewController.h; sourceTree = ""; }; 63E1E9871B28CB2100EF0978 /* SelectUserViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SelectUserViewController.m; sourceTree = ""; }; - 63E1E9891B28CB2100EF0978 /* SecondViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SecondViewController.h; sourceTree = ""; }; - 63E1E98A1B28CB2100EF0978 /* SecondViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SecondViewController.m; sourceTree = ""; }; + 63E1E9891B28CB2100EF0978 /* MakeRPCViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MakeRPCViewController.h; sourceTree = ""; }; + 63E1E98A1B28CB2100EF0978 /* MakeRPCViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MakeRPCViewController.m; sourceTree = ""; }; 63E1E98D1B28CB2100EF0978 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 63E1E98F1B28CB2100EF0978 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; 63F5DE471B28F5C100CDD07E /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; @@ -87,8 +87,8 @@ children = ( 63E1E9861B28CB2100EF0978 /* SelectUserViewController.h */, 63E1E9871B28CB2100EF0978 /* SelectUserViewController.m */, - 63E1E9891B28CB2100EF0978 /* SecondViewController.h */, - 63E1E98A1B28CB2100EF0978 /* SecondViewController.m */, + 63E1E9891B28CB2100EF0978 /* MakeRPCViewController.h */, + 63E1E98A1B28CB2100EF0978 /* MakeRPCViewController.m */, 63F5DE471B28F5C100CDD07E /* GoogleService-Info.plist */, 63E1E97F1B28CB2100EF0978 /* Supporting Files */, ); @@ -214,7 +214,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 63E1E98B1B28CB2100EF0978 /* SecondViewController.m in Sources */, + 63E1E98B1B28CB2100EF0978 /* MakeRPCViewController.m in Sources */, 63E1E9851B28CB2100EF0978 /* AppDelegate.m in Sources */, 63E1E9881B28CB2100EF0978 /* SelectUserViewController.m in Sources */, 63E1E9821B28CB2100EF0978 /* main.m in Sources */, diff --git a/objective-c/auth_sample/SecondViewController.h b/objective-c/auth_sample/MakeRPCViewController.h similarity index 93% rename from objective-c/auth_sample/SecondViewController.h rename to objective-c/auth_sample/MakeRPCViewController.h index 3e5ccf95a44..c75a8b3180f 100644 --- a/objective-c/auth_sample/SecondViewController.h +++ b/objective-c/auth_sample/MakeRPCViewController.h @@ -35,5 +35,6 @@ extern NSString * const kTestScope; -@interface SecondViewController : UIViewController +@interface MakeRPCViewController : UIViewController +@property(weak, nonatomic) IBOutlet UILabel *mainLabel; @end diff --git a/objective-c/auth_sample/MakeRPCViewController.m b/objective-c/auth_sample/MakeRPCViewController.m new file mode 100644 index 00000000000..410ae7d92bd --- /dev/null +++ b/objective-c/auth_sample/MakeRPCViewController.m @@ -0,0 +1,89 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#import "MakeRPCViewController.h" + +#import +#import +#import +#include + +NSString * const kTestScope = @"https://www.googleapis.com/auth/xapi.zoo"; + +static NSString * const kTestHostAddress = @"grpc-test.sandbox.google.com"; + +@implementation MakeRPCViewController + +- (void)viewWillAppear:(BOOL)animated { + + // Create a service client and a proto request as usual. + AUTHTestService *client = [[AUTHTestService alloc] initWithHost:kTestHostAddress]; + + AUTHRequest *request = [AUTHRequest message]; + request.fillUsername = YES; + request.fillOauthScope = YES; + + // Create a not-yet-started RPC. We want to set the request headers on this object before starting + // it. + __block ProtoRPC *call = + [client RPCToUnaryCallWithRequest:request handler:^(AUTHResponse *response, NSError *error) { + if (response) { + // This test server responds with the email and scope of the access token it receives. + self.mainLabel.text = [NSString stringWithFormat:@"Used scope: %@ on behalf of user %@", + response.oauthScope, response.username]; + + } else if (error.code == GRPC_STATUS_UNAUTHENTICATED) { + // Authentication error. OAuth2 specifies we'll receive a challenge header. + NSString *challengeHeader = call.responseMetadata[@"www-authenticate"][0] ?: @""; + self.mainLabel.text = + [@"Invalid credentials. Server challenge:\n" stringByAppendingString:challengeHeader]; + + } else { + // Any other error. + self.mainLabel.text = [NSString stringWithFormat:@"Unexpected RPC error %li: %@", + (long)error.code, error.localizedDescription]; + } + }]; + + // Set the access token to be used. + NSString *accessToken = GIDSignIn.sharedInstance.currentUser.authentication.accessToken; + call.requestMetadata = [NSMutableDictionary dictionaryWithDictionary: + @{@"Authorization": [@"Bearer " stringByAppendingString:accessToken]}]; + + // Start the RPC. + [call start]; + + self.mainLabel.text = @"Waiting for RPC to complete..."; +} + +@end diff --git a/objective-c/auth_sample/Misc/Base.lproj/Main.storyboard b/objective-c/auth_sample/Misc/Base.lproj/Main.storyboard index 761e7bffb0d..fb29c124e28 100644 --- a/objective-c/auth_sample/Misc/Base.lproj/Main.storyboard +++ b/objective-c/auth_sample/Misc/Base.lproj/Main.storyboard @@ -2,6 +2,7 @@ + @@ -90,10 +91,10 @@ - + - + @@ -102,29 +103,25 @@ - - - - + + - + + + + diff --git a/objective-c/auth_sample/SecondViewController.m b/objective-c/auth_sample/SecondViewController.m deleted file mode 100644 index d5ba19a7aba..00000000000 --- a/objective-c/auth_sample/SecondViewController.m +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#import "SecondViewController.h" - -#import - -NSString * const kTestScope = @"https://www.googleapis.com/auth/xapi.zoo"; - -@implementation SecondViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. -} - -@end diff --git a/objective-c/auth_sample/SelectUserViewController.m b/objective-c/auth_sample/SelectUserViewController.m index e54e9f866a5..954c531f3fb 100644 --- a/objective-c/auth_sample/SelectUserViewController.m +++ b/objective-c/auth_sample/SelectUserViewController.m @@ -33,7 +33,7 @@ #import "SelectUserViewController.h" -#import "SecondViewController.h" +#import "MakeRPCViewController.h" @implementation SelectUserViewController From 98cbb3f1982fddafcff9d2b2ac364be8f7ccb46e Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Fri, 12 Jun 2015 12:38:16 -0700 Subject: [PATCH 362/576] Move OAuth2 plist into Misc folder --- objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj | 2 +- objective-c/auth_sample/{ => Misc}/GoogleService-Info.plist | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename objective-c/auth_sample/{ => Misc}/GoogleService-Info.plist (100%) diff --git a/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj b/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj index 1e983ca3613..51a39c578c7 100644 --- a/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj +++ b/objective-c/auth_sample/AuthSample.xcodeproj/project.pbxproj @@ -89,7 +89,6 @@ 63E1E9871B28CB2100EF0978 /* SelectUserViewController.m */, 63E1E9891B28CB2100EF0978 /* MakeRPCViewController.h */, 63E1E98A1B28CB2100EF0978 /* MakeRPCViewController.m */, - 63F5DE471B28F5C100CDD07E /* GoogleService-Info.plist */, 63E1E97F1B28CB2100EF0978 /* Supporting Files */, ); name = AuthSample; @@ -99,6 +98,7 @@ isa = PBXGroup; children = ( 63E1E98C1B28CB2100EF0978 /* Main.storyboard */, + 63F5DE471B28F5C100CDD07E /* GoogleService-Info.plist */, 63E1E98F1B28CB2100EF0978 /* Images.xcassets */, 63E1E9801B28CB2100EF0978 /* Info.plist */, 63E1E9831B28CB2100EF0978 /* AppDelegate.h */, diff --git a/objective-c/auth_sample/GoogleService-Info.plist b/objective-c/auth_sample/Misc/GoogleService-Info.plist similarity index 100% rename from objective-c/auth_sample/GoogleService-Info.plist rename to objective-c/auth_sample/Misc/GoogleService-Info.plist From 3ea5cc927c733b8e8bba9f8bbce1f2ac8634ceb9 Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Fri, 12 Jun 2015 16:06:37 -0700 Subject: [PATCH 363/576] Fixed path names in README --- objective-c/helloworld/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/objective-c/helloworld/README.md b/objective-c/helloworld/README.md index cb25882867c..8f6d0d3a8d0 100644 --- a/objective-c/helloworld/README.md +++ b/objective-c/helloworld/README.md @@ -17,10 +17,10 @@ following command: $ git clone https://github.com/grpc/grpc-common.git ``` -Change your current directory to `grpc-common/objective-c/HelloWorld` +Change your current directory to `grpc-common/objective-c/helloworld` ```sh -$ cd grpc-common/objective-c/HelloWorld +$ cd grpc-common/objective-c/helloworld ``` ### Try it! @@ -41,7 +41,7 @@ $ pod install This might have to compile OpenSSL, which takes around 15 minutes if Cocoapods doesn't have it yet on your computer's cache). -Finally, open the XCode workspace created by Cocoapods, and run the app. You can check the calling code in `Supporting Files/main.m` and see the results in XCode's log console. +Finally, open the XCode workspace created by Cocoapods, and run the app. You can check the calling code in `main.m` and see the results in XCode's log console. The code sends a `HLWHelloRequest` containing the string "Objective-C" to a local server. The server responds with a `HLWHelloResponse`, which contains a string that is then output to the log. From a0117adab0f764f499e839eea922e070418c6f14 Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Fri, 12 Jun 2015 16:08:18 -0700 Subject: [PATCH 364/576] Moved main.m up a level --- objective-c/helloworld/HelloWorld.xcodeproj/project.pbxproj | 2 +- objective-c/helloworld/{HelloWorld => }/main.m | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename objective-c/helloworld/{HelloWorld => }/main.m (100%) diff --git a/objective-c/helloworld/HelloWorld.xcodeproj/project.pbxproj b/objective-c/helloworld/HelloWorld.xcodeproj/project.pbxproj index 018e722cb70..8d92247a913 100644 --- a/objective-c/helloworld/HelloWorld.xcodeproj/project.pbxproj +++ b/objective-c/helloworld/HelloWorld.xcodeproj/project.pbxproj @@ -30,7 +30,7 @@ 0C432EF610DB15C0F47A66BB /* Pods-HelloWorld.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-HelloWorld.release.xcconfig"; path = "Pods/Target Support Files/Pods-HelloWorld/Pods-HelloWorld.release.xcconfig"; sourceTree = ""; }; 5E3690601B2A23800040F884 /* HelloWorld.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HelloWorld.app; sourceTree = BUILT_PRODUCTS_DIR; }; 5E3690641B2A23800040F884 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 5E3690651B2A23800040F884 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = main.m; path = HelloWorld/main.m; sourceTree = ""; }; + 5E3690651B2A23800040F884 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 5E3690671B2A23800040F884 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 5E3690681B2A23800040F884 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 5E36906A1B2A23800040F884 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; diff --git a/objective-c/helloworld/HelloWorld/main.m b/objective-c/helloworld/main.m similarity index 100% rename from objective-c/helloworld/HelloWorld/main.m rename to objective-c/helloworld/main.m From 5fd27c9a52e518dc1fca74579badbe7d9fd40eec Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Thu, 11 Jun 2015 09:29:06 -0700 Subject: [PATCH 365/576] PHP route guide --- php/greeter_client.php | 4 +- php/route_guide/README.md | 232 +++++++ php/route_guide/route_guide.php | 731 ++++++++++++++++++++++ php/route_guide/route_guide.proto | 120 ++++ php/route_guide/route_guide_client.php | 205 ++++++ php/route_guide/run_route_guide_client.sh | 36 ++ php/run_greeter_client.sh | 18 +- 7 files changed, 1329 insertions(+), 17 deletions(-) create mode 100644 php/route_guide/README.md create mode 100644 php/route_guide/route_guide.php create mode 100644 php/route_guide/route_guide.proto create mode 100644 php/route_guide/route_guide_client.php create mode 100755 php/route_guide/run_route_guide_client.sh diff --git a/php/greeter_client.php b/php/greeter_client.php index 663ed7d5d77..8ae19ae46c5 100644 --- a/php/greeter_client.php +++ b/php/greeter_client.php @@ -32,8 +32,8 @@ * */ -require 'vendor/autoload.php'; -require 'helloworld.php'; +require dirname(__FILE__) . '/vendor/autoload.php'; +require dirname(__FILE__) . '/helloworld.php'; function greet($name) { $client = new helloworld\GreeterClient( diff --git a/php/route_guide/README.md b/php/route_guide/README.md new file mode 100644 index 00000000000..2d3c4d311de --- /dev/null +++ b/php/route_guide/README.md @@ -0,0 +1,232 @@ +#gRPC Basics: PHP + +This tutorial provides a basic PHP programmer's introduction to working with gRPC. By walking through this example you'll learn how to: + +- Define a service in a .proto file. +- Use the PHP gRPC API to write a simple client for your service. + +It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). + +This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon. + +## Why use gRPC? + +Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. + +With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. + +## Example code and setup + +The example code for our tutorial is in [grpc/grpc-common/php/route_guide](https://github.com/grpc/grpc-common/tree/master/php/route_guide). To download the example, clone the `grpc-common` repository by running the following command: +```shell +$ git clone https://github.com/grpc/grpc-common.git +``` + +Then change your current directory to `grpc-common/php/route_guide`: +```shell +$ cd grpc-common/php/route_guide +``` + +You also should have the relevant tools installed to generate the client interface code - if you don't already, follow the setup instructions in [the PHP quick start guide](https://github.com/grpc/grpc-common/tree/master/php). + +Please note that currently we only support gRPC clients implemented in PHP. Please see other supported languages (e.g. [Node.js](https://github.com/grpc/grpc-common/tree/master/node/route_guide)) to see how gRPC servers are implemented. + + +## Defining the service + +Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto). + +To define a service, you specify a named `service` in your .proto file: + +```protobuf +service RouteGuide { + ... +} +``` + +Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service: + +- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. +```protobuf + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) {} +``` + +- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. +```protobuf + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) {} +``` + +- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type. +```protobuf + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} +``` + +- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. +```protobuf + // Accepts a stream of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} +``` + +Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: +```protobuf +// Points are represented as latitude-longitude pairs in the E7 representation +// (degrees multiplied by 10**7 and rounded to the nearest integer). +// Latitudes should be in the range +/- 90 degrees and longitude should be in +// the range +/- 180 degrees (inclusive). +message Point { + int32 latitude = 1; + int32 longitude = 2; +} +``` + + +## Generating client stub from proto files + +The PHP client stub implementation of the proto files can be generated by the [`protoc-gen-php`](https://github.com/datto/protobuf-php) tool. + +```sh +$ cd grpc-common/php +$ php composer.phar install +$ cd vendor/datto/protobuf-php +$ gem install rake ronn +$ rake pear:package version=1.0 +$ sudo pear install Protobuf-1.0.tgz +``` + +To generate the client stub implementation .php file: + +```sh +$ cd php/route_guide +$ protoc-gen-php -i . -o . ./route_guide.proto +``` + +A `route_guide.php` file will be generated in the `php/route_guide` directory. You do not need to modify the file. + +To load the generated client stub file, simply `require` it in your PHP application: + +```php +require dirname(__FILE__) . '/route_guide.php'; +``` + +Once you've done this, the client classes are in the `examples\` namespace (e.g. `examples\RouteGuideClient`). + + + +## Creating the client + +In this section, we'll look at creating a PHP client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/php/route_guide/route_guide_client.php](https://github.com/grpc/grpc-common/blob/master/php/route_guide/route_guide_client.php). Again, please consult other languages (e.g. [Node.js](https://github.com/grpc/grpc-common/blob/master/node/route_guide/) to see how to start the route guide example server. + +### Creating a stub + +To call service methods, we first need to create a *stub*. To do this, we just need to call the RouteGuide stub constructor, specifying the server address and port. + +```php +$client = new examples\RouteGuideClient(new Grpc\BaseStub('localhost:50051', [])); +``` + +### Calling service methods + +Now let's look at how we call our service methods. + +#### Simple RPC + +Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method. + +```php +$point = new examples\Point(); +$point->setLatitude(409146138); +$point->setLongitude(-746188906); +list($feature, $status) = $client->GetFeature($point)->wait(); +``` + +As you can see, we create and populate a request object, i.e. an `examples\Point` object. Then, we call the method on the stub, passing it the request object. If there is no error, then we can read the response information from the server from our response object, i.e. an `examples\Feature` object. + +```php + print sprintf("Found %s \n at %f, %f\n", $feature->getName(), + $feature->getLocation()->getLatitude() / COORD_FACTOR, + $feature->getLocation()->getLongitude() / COORD_FACTOR); +``` + +#### Streaming RPCs + +Now let's look at our streaming methods. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s: + +```php + $lo_point = new examples\Point(); + $hi_point = new examples\Point(); + + $lo_point->setLatitude(400000000); + $lo_point->setLongitude(-750000000); + $hi_point->setLatitude(420000000); + $hi_point->setLongitude(-730000000); + + $rectangle = new examples\Rectangle(); + $rectangle->setLo($lo_point); + $rectangle->setHi($hi_point); + + $call = $client->ListFeatures($rectangle); + // an iterator over the server streaming responses + $features = $call->responses(); + foreach ($features as $feature) { + // process each feature + } // the loop will end when the server indicates there is no more responses to be sent. +``` + +The `$call->responses()` method call returns an iterator. When the server sends a response, a `$feature` object will be returned in the `foreach` loop, until the server indiciates that there will be no more responses to be sent. + +The client-side streaming method `RecordRoute` is similar, except there we pass the method an iterator and get back a `examples\RouteSummary`. + +```php + $points_iter = function($db) { + for ($i = 0; $i < $num_points; $i++) { + $point = new examples\Point(); + $point->setLatitude($lat); + $point->setLongitude($long); + yield $point; + } + }; + // $points_iter is an iterator simulating client streaming + list($route_summary, $status) = + $client->RecordRoute($points_iter($db))->wait(); +``` + +Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `Duplex` stream object, which we can use to both write and read messages. + +```php +$call = $client->RouteChat(); +``` + +To write messages from the client: + +```php + foreach ($notes as $n) { + $route_note = new examples\RouteNote(); + $call->write($route_note); + } + $call->writesDone(); +``` + +To read messages from the server: + +```php + while ($route_note_reply = $call->read()) { + // process $route_note_reply + } +``` + +Each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. + +## Try it out! + +Run the client (in a different terminal): +```shell +$ ./run_route_guide_client.sh +``` diff --git a/php/route_guide/route_guide.php b/php/route_guide/route_guide.php new file mode 100644 index 00000000000..a836e03b55b --- /dev/null +++ b/php/route_guide/route_guide.php @@ -0,0 +1,731 @@ +number = 1; + $f->name = "latitude"; + $f->type = \DrSlump\Protobuf::TYPE_INT32; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->default = 0; + $descriptor->addField($f); + + // OPTIONAL INT32 longitude = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "longitude"; + $f->type = \DrSlump\Protobuf::TYPE_INT32; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->default = 0; + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + return $descriptor; + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasLatitude(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \examples\Point + */ + public function clearLatitude(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return int + */ + public function getLatitude(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param int $value + * @return \examples\Point + */ + public function setLatitude( $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasLongitude(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \examples\Point + */ + public function clearLongitude(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @return int + */ + public function getLongitude(){ + return $this->_get(2); + } + + /** + * Set value + * + * @param int $value + * @return \examples\Point + */ + public function setLongitude( $value){ + return $this->_set(2, $value); + } + } +} + +namespace examples { + + class Rectangle extends \DrSlump\Protobuf\Message { + + /** @var \examples\Point */ + public $lo = null; + + /** @var \examples\Point */ + public $hi = null; + + + /** @var \Closure[] */ + protected static $__extensions = array(); + + public static function descriptor() + { + $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'examples.Rectangle'); + + // OPTIONAL MESSAGE lo = 1 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 1; + $f->name = "lo"; + $f->type = \DrSlump\Protobuf::TYPE_MESSAGE; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->reference = '\examples\Point'; + $descriptor->addField($f); + + // OPTIONAL MESSAGE hi = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "hi"; + $f->type = \DrSlump\Protobuf::TYPE_MESSAGE; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->reference = '\examples\Point'; + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + return $descriptor; + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasLo(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \examples\Rectangle + */ + public function clearLo(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return \examples\Point + */ + public function getLo(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param \examples\Point $value + * @return \examples\Rectangle + */ + public function setLo(\examples\Point $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasHi(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \examples\Rectangle + */ + public function clearHi(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @return \examples\Point + */ + public function getHi(){ + return $this->_get(2); + } + + /** + * Set value + * + * @param \examples\Point $value + * @return \examples\Rectangle + */ + public function setHi(\examples\Point $value){ + return $this->_set(2, $value); + } + } +} + +namespace examples { + + class Feature extends \DrSlump\Protobuf\Message { + + /** @var string */ + public $name = null; + + /** @var \examples\Point */ + public $location = null; + + + /** @var \Closure[] */ + protected static $__extensions = array(); + + public static function descriptor() + { + $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'examples.Feature'); + + // OPTIONAL STRING name = 1 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 1; + $f->name = "name"; + $f->type = \DrSlump\Protobuf::TYPE_STRING; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $descriptor->addField($f); + + // OPTIONAL MESSAGE location = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "location"; + $f->type = \DrSlump\Protobuf::TYPE_MESSAGE; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->reference = '\examples\Point'; + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + return $descriptor; + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasName(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \examples\Feature + */ + public function clearName(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return string + */ + public function getName(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param string $value + * @return \examples\Feature + */ + public function setName( $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasLocation(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \examples\Feature + */ + public function clearLocation(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @return \examples\Point + */ + public function getLocation(){ + return $this->_get(2); + } + + /** + * Set value + * + * @param \examples\Point $value + * @return \examples\Feature + */ + public function setLocation(\examples\Point $value){ + return $this->_set(2, $value); + } + } +} + +namespace examples { + + class RouteNote extends \DrSlump\Protobuf\Message { + + /** @var \examples\Point */ + public $location = null; + + /** @var string */ + public $message = null; + + + /** @var \Closure[] */ + protected static $__extensions = array(); + + public static function descriptor() + { + $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'examples.RouteNote'); + + // OPTIONAL MESSAGE location = 1 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 1; + $f->name = "location"; + $f->type = \DrSlump\Protobuf::TYPE_MESSAGE; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->reference = '\examples\Point'; + $descriptor->addField($f); + + // OPTIONAL STRING message = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "message"; + $f->type = \DrSlump\Protobuf::TYPE_STRING; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + return $descriptor; + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasLocation(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \examples\RouteNote + */ + public function clearLocation(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return \examples\Point + */ + public function getLocation(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param \examples\Point $value + * @return \examples\RouteNote + */ + public function setLocation(\examples\Point $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasMessage(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \examples\RouteNote + */ + public function clearMessage(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @return string + */ + public function getMessage(){ + return $this->_get(2); + } + + /** + * Set value + * + * @param string $value + * @return \examples\RouteNote + */ + public function setMessage( $value){ + return $this->_set(2, $value); + } + } +} + +namespace examples { + + class RouteSummary extends \DrSlump\Protobuf\Message { + + /** @var int */ + public $point_count = 0; + + /** @var int */ + public $feature_count = 0; + + /** @var int */ + public $distance = 0; + + /** @var int */ + public $elapsed_time = 0; + + + /** @var \Closure[] */ + protected static $__extensions = array(); + + public static function descriptor() + { + $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'examples.RouteSummary'); + + // OPTIONAL INT32 point_count = 1 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 1; + $f->name = "point_count"; + $f->type = \DrSlump\Protobuf::TYPE_INT32; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->default = 0; + $descriptor->addField($f); + + // OPTIONAL INT32 feature_count = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "feature_count"; + $f->type = \DrSlump\Protobuf::TYPE_INT32; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->default = 0; + $descriptor->addField($f); + + // OPTIONAL INT32 distance = 3 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 3; + $f->name = "distance"; + $f->type = \DrSlump\Protobuf::TYPE_INT32; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->default = 0; + $descriptor->addField($f); + + // OPTIONAL INT32 elapsed_time = 4 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 4; + $f->name = "elapsed_time"; + $f->type = \DrSlump\Protobuf::TYPE_INT32; + $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; + $f->default = 0; + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + return $descriptor; + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasPointCount(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \examples\RouteSummary + */ + public function clearPointCount(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return int + */ + public function getPointCount(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param int $value + * @return \examples\RouteSummary + */ + public function setPointCount( $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasFeatureCount(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \examples\RouteSummary + */ + public function clearFeatureCount(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @return int + */ + public function getFeatureCount(){ + return $this->_get(2); + } + + /** + * Set value + * + * @param int $value + * @return \examples\RouteSummary + */ + public function setFeatureCount( $value){ + return $this->_set(2, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasDistance(){ + return $this->_has(3); + } + + /** + * Clear value + * + * @return \examples\RouteSummary + */ + public function clearDistance(){ + return $this->_clear(3); + } + + /** + * Get value + * + * @return int + */ + public function getDistance(){ + return $this->_get(3); + } + + /** + * Set value + * + * @param int $value + * @return \examples\RouteSummary + */ + public function setDistance( $value){ + return $this->_set(3, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasElapsedTime(){ + return $this->_has(4); + } + + /** + * Clear value + * + * @return \examples\RouteSummary + */ + public function clearElapsedTime(){ + return $this->_clear(4); + } + + /** + * Get value + * + * @return int + */ + public function getElapsedTime(){ + return $this->_get(4); + } + + /** + * Set value + * + * @param int $value + * @return \examples\RouteSummary + */ + public function setElapsedTime( $value){ + return $this->_set(4, $value); + } + } +} + +namespace examples { + + class RouteGuideClient{ + + private $rpc_impl; + + public function __construct($rpc_impl) { + $this->rpc_impl = $rpc_impl; + } + /** + * @param examples\Point $input + */ + public function GetFeature(\examples\Point $argument, $metadata = array()) { + return $this->rpc_impl->_simpleRequest('/examples.RouteGuide/GetFeature', $argument, '\examples\Feature::deserialize', $metadata); + } + /** + * @param examples\Rectangle $input + */ + public function ListFeatures($argument, $metadata = array()) { + return $this->rpc_impl->_serverStreamRequest('/examples.RouteGuide/ListFeatures', $argument, '\examples\Feature::deserialize', $metadata); + } + /** + * @param examples\Point $input + */ + public function RecordRoute($arguments, $metadata = array()) { + return $this->rpc_impl->_clientStreamRequest('/examples.RouteGuide/RecordRoute', $arguments, '\examples\RouteSummary::deserialize', $metadata); + } + /** + * @param examples\RouteNote $input + */ + public function RouteChat($metadata = array()) { + return $this->rpc_impl->_bidiRequest('/examples.RouteGuide/RouteChat', '\examples\RouteNote::deserialize', $metadata); + } + } +} diff --git a/php/route_guide/route_guide.proto b/php/route_guide/route_guide.proto new file mode 100644 index 00000000000..0947184dbbd --- /dev/null +++ b/php/route_guide/route_guide.proto @@ -0,0 +1,120 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +option java_package = "io.grpc.examples"; + +package examples; + +// Interface exported by the server. +service RouteGuide { + // A simple RPC. + // + // Obtains the feature at a given position. + rpc GetFeature(Point) returns (Feature) {} + + // A server-to-client streaming RPC. + // + // Obtains the Features available within the given Rectangle. Results are + // streamed rather than returned at once (e.g. in a response message with a + // repeated field), as the rectangle may cover a large area and contain a + // huge number of features. + rpc ListFeatures(Rectangle) returns (stream Feature) {} + + // A client-to-server streaming RPC. + // + // Accepts a stream of Points on a route being traversed, returning a + // RouteSummary when traversal is completed. + rpc RecordRoute(stream Point) returns (RouteSummary) {} + + // A Bidirectional streaming RPC. + // + // Accepts a stream of RouteNotes sent while a route is being traversed, + // while receiving other RouteNotes (e.g. from other users). + rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} +} + +// Points are represented as latitude-longitude pairs in the E7 representation +// (degrees multiplied by 10**7 and rounded to the nearest integer). +// Latitudes should be in the range +/- 90 degrees and longitude should be in +// the range +/- 180 degrees (inclusive). +message Point { + optional int32 latitude = 1 [default = 0]; + optional int32 longitude = 2 [default = 0]; +} + +// A latitude-longitude rectangle, represented as two diagonally opposite +// points "lo" and "hi". +message Rectangle { + // One corner of the rectangle. + optional Point lo = 1; + + // The other corner of the rectangle. + optional Point hi = 2; +} + +// A feature names something at a given point. +// +// If a feature could not be named, the name is empty. +message Feature { + // The name of the feature. + optional string name = 1; + + // The point where the feature is detected. + optional Point location = 2; +} + +// A RouteNote is a message sent while at a given point. +message RouteNote { + // The location from which the message is sent. + optional Point location = 1; + + // The message to be sent. + optional string message = 2; +} + +// A RouteSummary is received in response to a RecordRoute rpc. +// +// It contains the number of individual points received, the number of +// detected features, and the total distance covered as the cumulative sum of +// the distance between each point. +message RouteSummary { + // The number of points received. + optional int32 point_count = 1 [default = 0]; + + // The number of known features passed while traversing the route. + optional int32 feature_count = 2 [default = 0]; + + // The distance covered in metres. + optional int32 distance = 3 [default = 0]; + + // The duration of the traversal in seconds. + optional int32 elapsed_time = 4 [default = 0]; +} diff --git a/php/route_guide/route_guide_client.php b/php/route_guide/route_guide_client.php new file mode 100644 index 00000000000..6d9ae58b66c --- /dev/null +++ b/php/route_guide/route_guide_client.php @@ -0,0 +1,205 @@ +getName(); + if (!$name) { + $name_str = "no feature"; + } else { + $name_str = "feature called $name"; + } + print sprintf("Found %s \n at %f, %f\n", $name_str, + $feature->getLocation()->getLatitude() / COORD_FACTOR, + $feature->getLocation()->getLongitude() / COORD_FACTOR); +} + +/** + * Run the getFeature demo. Calls getFeature with a point known to have a + * feature and a point known not to have a feature. + */ +function runGetFeature() { + print "Running GetFeature...\n"; + global $client; + + $point = new examples\Point(); + $points = array( + array(409146138, -746188906), + array(0, 0), + ); + + foreach ($points as $p) { + $point->setLatitude($p[0]); + $point->setLongitude($p[1]); + // make a unary grpc call + list($feature, $status) = $client->GetFeature($point)->wait(); + printFeature($feature); + } +} + +/** + * Run the listFeatures demo. Calls listFeatures with a rectangle + * containing all of the features in the pre-generated + * database. Prints each response as it comes in. + */ +function runListFeatures() { + print "Running ListFeatures...\n"; + global $client; + + $lo_point = new examples\Point(); + $hi_point = new examples\Point(); + + $lo_point->setLatitude(400000000); + $lo_point->setLongitude(-750000000); + $hi_point->setLatitude(420000000); + $hi_point->setLongitude(-730000000); + + $rectangle = new examples\Rectangle(); + $rectangle->setLo($lo_point); + $rectangle->setHi($hi_point); + + $call = $client->ListFeatures($rectangle); + // an iterator over the server streaming responses + $features = $call->responses(); + foreach ($features as $feature) { + printFeature($feature); + } +} + +/** + * Run the recordRoute demo. Sends several randomly chosen points from the + * pre-generated feature database with a variable delay in between. Prints + * the statistics when they are sent from the server. + */ +function runRecordRoute() { + print "Running RecordRoute...\n"; + global $client, $argv; + + $db = json_decode(file_get_contents($argv[1]), true); + $points_iter = function($db) { + $num_points_in_db = count($db); + $num_points = 10; + for ($i = 0; $i < $num_points; $i++) { + $point = new examples\Point(); + $index = rand(0, $num_points_in_db - 1); + $lat = $db[$index]['location']['latitude']; + $long = $db[$index]['location']['longitude']; + $feature_name = $db[$index]['name']; + $point->setLatitude($lat); + $point->setLongitude($long); + print sprintf("Visiting point %f, %f,\n with feature name: %s\n", + $lat / COORD_FACTOR, $long / COORD_FACTOR, + $feature_name ? $feature_name : ''); + usleep(rand(300000, 800000)); + yield $point; + } + }; + // $points_iter is an iterator simulating client streaming + list($route_summary, $status) = + $client->RecordRoute($points_iter($db))->wait(); + print sprintf("Finished trip with %d points\nPassed %d features\n". + "Travelled %d meters\nIt took %d seconds\n", + $route_summary->getPointCount(), + $route_summary->getFeatureCount(), + $route_summary->getDistance(), + $route_summary->getElapsedTime()); +} + +/** + * Run the routeChat demo. Send some chat messages, and print any chat + * messages that are sent from the server. + */ +function runRouteChat() { + print "Running RouteChat...\n"; + global $client; + + // start the bidirectional streaming call + $call = $client->RouteChat(); + + $notes = array( + array(1, 1, 'first message'), + array(1, 2, 'second message'), + array(2, 1, 'third message'), + array(1, 1, 'fourth message'), + array(1, 1, 'fifth message'), + ); + + foreach ($notes as $n) { + $point = new examples\Point(); + $point->setLatitude($lat = $n[0]); + $point->setLongitude($long = $n[1]); + + $route_note = new examples\RouteNote(); + $route_note->setLocation($point); + $route_note->setMessage($message = $n[2]); + + print sprintf("Sending message: '%s' at (%d, %d)\n", + $message, $lat, $long); + // send a bunch of messages to the server + $call->write($route_note); + } + $call->writesDone(); + + // read from the server until there's no more + while ($route_note_reply = $call->read()) { + print sprintf("Previous left message at (%d, %d): '%s'\n", + $route_note_reply->getLocation()->getLatitude(), + $route_note_reply->getLocation()->getLongitude(), + $route_note_reply->getMessage()); + } +} + +/** + * Run all of the demos in order + */ +function main() { + runGetFeature(); + runListFeatures(); + runRecordRoute(); + runRouteChat(); +} + +if (empty($argv[1])) { + print "Usage: php -d extension=grpc.so route_guide_client.php " . + "\n"; + exit(1); +} +main(); diff --git a/php/route_guide/run_route_guide_client.sh b/php/route_guide/run_route_guide_client.sh new file mode 100755 index 00000000000..e5ca07796be --- /dev/null +++ b/php/route_guide/run_route_guide_client.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +set -e +cd $(dirname $0) +command -v brew >/dev/null 2>&1 && \ + extension_dir="-d extension_dir="`brew --prefix`/opt/grpc-php +php $extension_dir -d extension=grpc.so \ + route_guide_client.php ../../node/route_guide/route_guide_db.json diff --git a/php/run_greeter_client.sh b/php/run_greeter_client.sh index 4fdea897f96..2906de9af89 100755 --- a/php/run_greeter_client.sh +++ b/php/run_greeter_client.sh @@ -30,18 +30,6 @@ set -e cd $(dirname $0) -which brew >> /dev/null || { echo 'please make sure brew is in the PATH'; exit 1; } -default_extension_dir=`php -i 2>/dev/null | grep extension_dir | sed 's/.*=> //g'` -brew_home=`brew --prefix` -module_dir=$brew_home/opt/grpc-php - -# sym-link in system supplied extensions -for f in $default_extension_dir/*.so -do - ln -s $f $module_dir/$(basename $f) &> /dev/null || true -done - -php \ - -d extension_dir=$module_dir \ - -d extension=grpc.so \ - greeter_client.php +command -v brew >/dev/null 2>&1 && \ + extension_dir="-d extension_dir="`brew --prefix`/opt/grpc-php +php $extension_dir -d extension=grpc.so greeter_client.php $1 From dcfa963d6e3b1f10ae89a0f16d05b6668af8a505 Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Tue, 16 Jun 2015 08:17:42 -0700 Subject: [PATCH 366/576] Fix readme as per feedback --- php/route_guide/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php/route_guide/README.md b/php/route_guide/README.md index 2d3c4d311de..39a9a56d7e6 100644 --- a/php/route_guide/README.md +++ b/php/route_guide/README.md @@ -29,7 +29,7 @@ $ cd grpc-common/php/route_guide You also should have the relevant tools installed to generate the client interface code - if you don't already, follow the setup instructions in [the PHP quick start guide](https://github.com/grpc/grpc-common/tree/master/php). -Please note that currently we only support gRPC clients implemented in PHP. Please see other supported languages (e.g. [Node.js](https://github.com/grpc/grpc-common/tree/master/node/route_guide)) to see how gRPC servers are implemented. +Please note that currently we only support gRPC clients implemented in PHP. See the tutorials for our other supported languages (e.g. [Node.js](https://github.com/grpc/grpc-common/tree/master/node/route_guide)) to see how gRPC servers are implemented. ## Defining the service From 45e4380ebd9f56d21494391507967ed466e25eb2 Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Tue, 16 Jun 2015 08:59:07 -0700 Subject: [PATCH 367/576] restructure PHP route guide README using the Objective-C one as guideline --- php/route_guide/README.md | 73 +++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 23 deletions(-) diff --git a/php/route_guide/README.md b/php/route_guide/README.md index 39a9a56d7e6..931dd0c68a1 100644 --- a/php/route_guide/README.md +++ b/php/route_guide/README.md @@ -3,18 +3,28 @@ This tutorial provides a basic PHP programmer's introduction to working with gRPC. By walking through this example you'll learn how to: - Define a service in a .proto file. +- Generate client code using the protocol buffer compiler. - Use the PHP gRPC API to write a simple client for your service. -It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). +It assumes a passing familiarity with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto2 version of the protocol buffers language. This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon. +- [Why use gRPC?](#why-grpc) +- [Example code and setup](#setup) +- [Defining the service](#proto) +- [Generating client code](#protoc) +- [Creating the client](#client) +- [Try it out!](#try) + + + ## Why use gRPC? -Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. +With gRPC you can define your service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. You also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. -With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. + ## Example code and setup The example code for our tutorial is in [grpc/grpc-common/php/route_guide](https://github.com/grpc/grpc-common/tree/master/php/route_guide). To download the example, clone the `grpc-common` repository by running the following command: @@ -27,14 +37,17 @@ Then change your current directory to `grpc-common/php/route_guide`: $ cd grpc-common/php/route_guide ``` -You also should have the relevant tools installed to generate the client interface code - if you don't already, follow the setup instructions in [the PHP quick start guide](https://github.com/grpc/grpc-common/tree/master/php). +Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. + +You also should have the relevant tools installed to generate the client interface code (and a server in another language, for testing). You can obtain the latter by following [these setup instructions](https://github.com/grpc/homebrew-grpc). -Please note that currently we only support gRPC clients implemented in PHP. See the tutorials for our other supported languages (e.g. [Node.js](https://github.com/grpc/grpc-common/tree/master/node/route_guide)) to see how gRPC servers are implemented. +The next sections guide you step-by-step through how this proto service is defined, how to generate a client library from it, and how to create a client stub that uses that library. + ## Defining the service -Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto). +First let's look at how the service we're using is defined. A gRPC *service* and its method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file for our example in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto). To define a service, you specify a named `service` in your .proto file: @@ -44,15 +57,15 @@ service RouteGuide { } ``` -Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service: +Then you define `rpc` methods inside your service definition, specifying their request and response types. Protocol buffers let you define four kinds of service method, all of which are used in the `RouteGuide` service: -- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. +- A *simple RPC* where the client sends a request to the server and receives a response later, just like a normal remote procedure call. ```protobuf // Obtains the feature at a given position. rpc GetFeature(Point) returns (Feature) {} ``` -- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. +- A *response-streaming RPC* where the client sends a request to the server and gets back a stream of response messages. You specify a response-streaming method by placing the `stream` keyword before the *response* type. ```protobuf // Obtains the Features available within the given Rectangle. Results are // streamed rather than returned at once (e.g. in a response message with a @@ -61,14 +74,14 @@ Then you define `rpc` methods inside your service definition, specifying their r rpc ListFeatures(Rectangle) returns (stream Feature) {} ``` -- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type. +- A *request-streaming RPC* where the client sends a sequence of messages to the server. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a request-streaming method by placing the `stream` keyword before the *request* type. ```protobuf // Accepts a stream of Points on a route being traversed, returning a // RouteSummary when traversal is completed. rpc RecordRoute(stream Point) returns (RouteSummary) {} ``` -- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. +- A *bidirectional streaming RPC* where both sides send a sequence of messages to the other. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. ```protobuf // Accepts a stream of RouteNotes sent while a route is being traversed, // while receiving other RouteNotes (e.g. from other users). @@ -88,9 +101,10 @@ message Point { ``` -## Generating client stub from proto files + +## Generating client code -The PHP client stub implementation of the proto files can be generated by the [`protoc-gen-php`](https://github.com/datto/protobuf-php) tool. +The PHP client stub implementation of the proto files can be generated by the [`protoc-gen-php`](https://github.com/datto/protobuf-php) tool. To install the tool: ```sh $ cd grpc-common/php @@ -116,17 +130,19 @@ To load the generated client stub file, simply `require` it in your PHP applicat require dirname(__FILE__) . '/route_guide.php'; ``` -Once you've done this, the client classes are in the `examples\` namespace (e.g. `examples\RouteGuideClient`). +The file contains: +- All the protocol buffer code to populate, serialize, and retrieve our request and response message types. +- A class called `examples\RouteGuideClient` that lets clients call the methods defined in the `RouteGuide` service. ## Creating the client -In this section, we'll look at creating a PHP client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/php/route_guide/route_guide_client.php](https://github.com/grpc/grpc-common/blob/master/php/route_guide/route_guide_client.php). Again, please consult other languages (e.g. [Node.js](https://github.com/grpc/grpc-common/blob/master/node/route_guide/) to see how to start the route guide example server. +In this section, we'll look at creating a PHP client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/php/route_guide/route_guide_client.php](https://github.com/grpc/grpc-common/blob/master/php/route_guide/route_guide_client.php). -### Creating a stub +### Constructing a client object -To call service methods, we first need to create a *stub*. To do this, we just need to call the RouteGuide stub constructor, specifying the server address and port. +To call service methods, we first need to create a client object, an instance of the generated `RouteGuideClient` class. The constructor of the class expects the server address and port we want to connect to: ```php $client = new examples\RouteGuideClient(new Grpc\BaseStub('localhost:50051', [])); @@ -141,10 +157,10 @@ Now let's look at how we call our service methods. Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method. ```php -$point = new examples\Point(); -$point->setLatitude(409146138); -$point->setLongitude(-746188906); -list($feature, $status) = $client->GetFeature($point)->wait(); + $point = new examples\Point(); + $point->setLatitude(409146138); + $point->setLongitude(-746188906); + list($feature, $status) = $client->GetFeature($point)->wait(); ``` As you can see, we create and populate a request object, i.e. an `examples\Point` object. Then, we call the method on the stub, passing it the request object. If there is no error, then we can read the response information from the server from our response object, i.e. an `examples\Feature` object. @@ -198,7 +214,7 @@ The client-side streaming method `RecordRoute` is similar, except there we pass $client->RecordRoute($points_iter($db))->wait(); ``` -Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `Duplex` stream object, which we can use to both write and read messages. +Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `BidiStreamingCall` stream object, which we can use to both write and read messages. ```php $call = $client->RouteChat(); @@ -224,9 +240,20 @@ To read messages from the server: Each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. + ## Try it out! -Run the client (in a different terminal): +To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the Node.js server in this repository: + +```shell +$ cd ../../node +$ npm install +$ cd route_guide +$ nodejs ./route_guide_server.js --db_path=route_guide_db.json +``` + +Run the PHP client (in a different terminal): + ```shell $ ./run_route_guide_client.sh ``` From 3508c9a5b85e41b4a7c9a68e10a6838108232170 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Tue, 16 Jun 2015 22:21:48 -0700 Subject: [PATCH 368/576] Add README for the auth example --- objective-c/auth_sample/README.md | 174 ++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 objective-c/auth_sample/README.md diff --git a/objective-c/auth_sample/README.md b/objective-c/auth_sample/README.md new file mode 100644 index 00000000000..06812323bc4 --- /dev/null +++ b/objective-c/auth_sample/README.md @@ -0,0 +1,174 @@ +#OAuth2 on gRPC: Objective-C + +This example application demostrates how to use OAuth2 on gRPC to make authenticated API calls on +behalf of a user. By walking through it you'll learn how to use the Objective-C gRPC API to: + +- Initialize and configure a remote call object before the RPC is started. +- Set request metadata elements on a call, which are semantically equivalent to HTTP request +headers. +- Read response metadata from a call, which is equivalent to HTTP response headers and trailers. + +It assumes you know the basics on how to make gRPC API calls using the Objective-C client library, +as shown in the [Hello World](https://github.com/grpc/grpc-common/tree/master/objective-c/helloworld) +or [Route Guide](https://github.com/grpc/grpc-common/tree/master/objective-c/route_guide) tutorials, +and familiarity with OAuth2 concepts like _access token_. + +- [Example code and setup](#setup) +- [Try it out!](#try) +- [Create an RPC object and start it later](#rpc-object) +- [Set request metadata of a call: Authorization header with an access token](#request-metadata) +- [Get response metadata of a call: Auth challenge header](#response-metadata) + + +## Example code and setup + +The example code for our tutorial is in [grpc/grpc-common/objective-c/auth_sample](https://github.com/grpc/grpc-common/tree/master/objective-c/auth_sample). +To download the example, clone the `grpc-common` repository by running the following command: +```shell +$ git clone https://github.com/grpc/grpc-common.git +``` + +Then change your current directory to `grpc-common/objective-c/auth_sample`: +```shell +$ cd grpc-common/objective-c/auth_sample +``` + +Our example is a simple application with two views. The first one lets a user sign in and out using +the OAuth2 flow of Google's [iOS SignIn library](https://developers.google.com/identity/sign-in/ios/). +(Google's library is used in this example because the test gRPC service we are going to call expects +Google account credentials, but neither gRPC nor the Objective-C client library is tied to any +specific OAuth2 provider). The second view makes a gRPC request to the test server, using the +access token obtained by the first view. + +Note: OAuth2 libraries need the application to register and obtain an ID from the identity provider +(in the case of this example app, Google). The app's XCode project is configured using that ID, so +you shouldn't copy this project as is for your own app: It would result in your app being identified +in the consent screen as "gRPC-AuthSample", and not having access to real Google services. Instead, +configure your XCode project following the [instructions here](https://developers.google.com/identity/sign-in/ios/). + +As with the other examples, you also should have [Cocoapods](https://cocoapods.org/#install) +installed, as well as the relevant tools to generate the client library code. You can obtain the +latter by following [these setup instructions](https://github.com/grpc/homebrew-grpc). + + + +## Try it out! + +To try the sample app, first have Cocoapods generate and install the client library for our .proto +files: + +```shell +$ pod install +``` + +(This might have to compile OpenSSL, which takes around 15 minutes if Cocoapods doesn't have it yet +on your computer's cache). + +Finally, open the XCode workspace created by Cocoapods, and run the app. + +The first view, `SelectUserViewController.h/m`, asks you to sign in with your Google account, and to +give the "gRPC-AuthSample" app the following permissions: + +- View your email address. +- View your basic profile info. +- "Test scope for access to the Zoo service". + +This last permission, corresponding to the scope `https://www.googleapis.com/auth/xapi.zoo` doesn't +grant any real capability: It's only used for testing. You can log out at any moment. + +The second view, `MakeRPCViewController.h/m`, makes a gRPC request to a test server at +https://grpc-test.sandbox.google.com, sending the access token along with the request. The test +service simply validates the token and writes in its response which user it belongs to, and which +scopes it gives access to. (The client application already knows those two values; it's a way to +verify that everything went as expected). + +The next sections guide you step-by-step through how the gRPC call in `MakeRPCViewController` is +performed. + + +## Create an RPC object and start it later + +The other basic tutorials show how to invoke an RPC by calling an asynchronous method in a generated +client object. This shows how to initialize an object that represents the RPC, and configure it +before starting the network request. + +Assume you have a proto service definition like this: + +```protobuf +option objc_class_prefix = "AUTH"; + +service TestService { + rpc UnaryCall(Request) returns (Response); +} +``` + +A `unaryCallWithRequest:handler:` method is generated, with which you're already familiar, is +generated for the `AUTHTestService` class: + +```objective-c +[client unaryCallWithRequest:request handler:^(AUTHResponse *response, NSError *error) { + ... +}]; +``` + +And a second `RPCToUnaryCallWithRequest:handler:` method is generated, which returns a +not-yet-started RPC object: + +```objective-c +#import + +ProtoRPC *call = + [client RPCToUnaryCallWithRequest:request handler:^(AUTHResponse *response, NSError *error) { + ... + }]; +``` + +The RPC represented by this object can be started at any later time like this: + +```objective-c +[call start]; +``` + + +## Set request metadata of a call: Authorization header with an access token + +The `ProtoRPC` class has a `requestMetadata` property defined like this: + +```objective-c +@property(nonatomic, readwrite) NSMutableDictionary *requestMetadata; +``` + +Setting it to a dictionary of metadata keys and values will have them sent on the wire when the call +is started. + +```objective-c +call.requestMetadata = [NSMutableDictionary dictionaryWithDictionary: + @{@"My-Header": @"Value for this header", + @"Another-Header": @"Its value"}]; +``` + +If you have an access token, OAuth2 specifies it is to be sent in this format: + +```objective-c +@{@"Authorization": [@"Bearer " stringByAppendingString:accessToken]} +``` + + +## Get response metadata of a call: Auth challenge header + +Analogously to the request metadata, the `ProtoRPC` class has a `responseMetadata` property defined +this way: + +```objective-c +@property(atomic, readonly) NSDictionary *responseMetadata; +``` + +Because gRPC metadata keys can be repeated, the values of the `responseMetadata` dictionary are +always `NSArray`s. Thus, to access OAuth2's authentication challenge header you write: + +```objective-c +call.responseMetadata[@"www-authenticate"][0] +``` + +Note that, as gRPC metadata elements are mapped to HTTP/2 headers (or trailers), the keys of the +response metadata are always ASCII strings in lowercase. From 777fee23d8ae78d01d8f2fce47c6aa566d6e4887 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Tue, 16 Jun 2015 11:03:20 -0700 Subject: [PATCH 369/576] Add Objective-C sections to the common auth README --- grpc-auth-support.md | 56 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 9b97203276b..597f4434d2a 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -114,6 +114,22 @@ var channel = new Channel("localhost:50051", credentials); var client = new Greeter.GreeterClient(channel); ``` +###SSL/TLS for server authentication and encryption (Objective-C) + +The default for Objective-C is to use SSL/TLS, as that's the most common use case when accessing +remote APIs. + +```objective-c +// Base case - With server authentication SSL/TLS +HLWGreeter *client = [[HLWGreeter alloc] initWithHost:@"localhost:50051"]; +// Same as using @"https://localhost:50051". +... + +// No encryption +HLWGreeter *client = [[HLWGreeter alloc] initWithHost:@"http://localhost:50051"]; +// Specifying the HTTP scheme explicitly forces no encryption. +``` + ###Authenticating with Google (Ruby) ```ruby # Base case - No encryption/authorization @@ -174,3 +190,43 @@ if (authorization.IsCreateScopedRequired) var client = new Greeter.GreeterClient(channel, new StubConfiguration(OAuth2InterceptorFactory.Create(credential))); ``` + +###Authenticating with Google (Objective-C) + +This example uses the [Google iOS Sign-In library](https://developers.google.com/identity/sign-in/ios/), +but it's easily extrapolated to any other OAuth2 library. + +```objective-c +// Base case - No authentication +[client sayHelloWithRequest:request handler:^(HLWHelloReply *response, NSError *error) { + ... +}]; + +... + +// Authenticating with Google + +// When signing the user in, ask her for the relevant scopes. +GIDSignIn.sharedInstance.scopes = @[@"https://www.googleapis.com/auth/grpc-testing"]; + +... + +#import + +// Create a not-yet-started RPC. We want to set the request headers on this object before starting +// it. +ProtoRPC *call = + [client RPCToSayHelloWithRequest:request handler:^(HLWHelloReply *response, NSError *error) { + ... + }]; + +// Set the access token to be used. +NSString *accessToken = GIDSignIn.sharedInstance.currentUser.authentication.accessToken; +call.requestMetadata = [NSMutableDictionary dictionaryWithDictionary: + @{@"Authorization": [@"Bearer " stringByAppendingString:accessToken]}]; + +// Start the RPC. +[call start]; +``` + +You can see a working example app, with a more detailed explanation, [here](https://github.com/grpc/grpc-common/tree/master/objective-c/auth_sample). From fd7627691f13b1c62e97014253b3ac011e5e4b94 Mon Sep 17 00:00:00 2001 From: Yang Gao Date: Wed, 17 Jun 2015 16:31:39 -0700 Subject: [PATCH 370/576] Move to new Status API --- cpp/helloworld/greeter_async_client.cc | 2 +- cpp/helloworld/greeter_client.cc | 2 +- cpp/route_guide/route_guide_client.cc | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cpp/helloworld/greeter_async_client.cc b/cpp/helloworld/greeter_async_client.cc index b88ba0e74ad..561b880ecb6 100644 --- a/cpp/helloworld/greeter_async_client.cc +++ b/cpp/helloworld/greeter_async_client.cc @@ -79,7 +79,7 @@ class GreeterClient { GPR_ASSERT(ok); GPR_ASSERT(got_tag == (void*)1); - if (status.IsOk()) { + if (status.ok()) { return reply.message(); } else { return "Rpc failed"; diff --git a/cpp/helloworld/greeter_client.cc b/cpp/helloworld/greeter_client.cc index c0aec1696a4..44e4447f1f9 100644 --- a/cpp/helloworld/greeter_client.cc +++ b/cpp/helloworld/greeter_client.cc @@ -64,7 +64,7 @@ class GreeterClient { ClientContext context; Status status = stub_->SayHello(&context, request, &reply); - if (status.IsOk()) { + if (status.ok()) { return reply.message(); } else { return "Rpc failed"; diff --git a/cpp/route_guide/route_guide_client.cc b/cpp/route_guide/route_guide_client.cc index 91e1cebfc7a..734ea9fb8ad 100644 --- a/cpp/route_guide/route_guide_client.cc +++ b/cpp/route_guide/route_guide_client.cc @@ -124,7 +124,7 @@ class RouteGuideClient { << feature.location().longitude()/kCoordFactor_ << std::endl; } Status status = reader->Finish(); - if (status.IsOk()) { + if (status.ok()) { std::cout << "ListFeatures rpc succeeded." << std::endl; } else { std::cout << "ListFeatures rpc failed." << std::endl; @@ -160,7 +160,7 @@ class RouteGuideClient { } writer->WritesDone(); Status status = writer->Finish(); - if (status.IsOk()) { + if (status.ok()) { std::cout << "Finished trip with " << stats.point_count() << " points\n" << "Passed " << stats.feature_count() << " features\n" << "Travelled " << stats.distance() << " meters\n" @@ -200,7 +200,7 @@ class RouteGuideClient { } writer.join(); Status status = stream->Finish(); - if (!status.IsOk()) { + if (!status.ok()) { std::cout << "RouteChat rpc failed." << std::endl; } } @@ -210,7 +210,7 @@ class RouteGuideClient { bool GetOneFeature(const Point& point, Feature* feature) { ClientContext context; Status status = stub_->GetFeature(&context, point, feature); - if (!status.IsOk()) { + if (!status.ok()) { std::cout << "GetFeature rpc failed." << std::endl; return false; } From 5bcf4671e479ce73e47bcc1c8aafc21a2208498d Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Thu, 18 Jun 2015 08:23:17 -0700 Subject: [PATCH 371/576] update PHP route guide README as per feedback --- php/route_guide/README.md | 41 +++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/php/route_guide/README.md b/php/route_guide/README.md index 931dd0c68a1..084661a5eba 100644 --- a/php/route_guide/README.md +++ b/php/route_guide/README.md @@ -8,14 +8,16 @@ This tutorial provides a basic PHP programmer's introduction to working with gRP It assumes a passing familiarity with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto2 version of the protocol buffers language. +Also note that currently you can only create clients in PHP for gRPC services - you can find out how to create gRPC servers in our other tutorials, e.g. [Node.js](https://github.com/grpc/grpc-common/tree/master/node/route_guide). + This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon. - [Why use gRPC?](#why-grpc) - [Example code and setup](#setup) +- [Try it out!](#try) - [Defining the service](#proto) - [Generating client code](#protoc) - [Creating the client](#client) -- [Try it out!](#try) @@ -41,6 +43,25 @@ Our example is a simple route mapping application that lets clients get informat You also should have the relevant tools installed to generate the client interface code (and a server in another language, for testing). You can obtain the latter by following [these setup instructions](https://github.com/grpc/homebrew-grpc). + + +## Try it out! + +To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the Node.js server in this repository: + +```shell +$ cd ../../node +$ npm install +$ cd route_guide +$ nodejs ./route_guide_server.js --db_path=route_guide_db.json +``` + +Run the PHP client (in a different terminal): + +```shell +$ ./run_route_guide_client.sh +``` + The next sections guide you step-by-step through how this proto service is defined, how to generate a client library from it, and how to create a client stub that uses that library. @@ -239,21 +260,3 @@ To read messages from the server: ``` Each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. - - -## Try it out! - -To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the Node.js server in this repository: - -```shell -$ cd ../../node -$ npm install -$ cd route_guide -$ nodejs ./route_guide_server.js --db_path=route_guide_db.json -``` - -Run the PHP client (in a different terminal): - -```shell -$ ./run_route_guide_client.sh -``` From 40dc223f07ec31e0b9acf1796b574109cf965c3b Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Tue, 23 Jun 2015 17:35:04 -0700 Subject: [PATCH 372/576] Add PHP Google Auth example --- grpc-auth-support.md | 21 +++++++++++ php/composer.json | 1 + php/greeter_client_with_auth.php | 57 +++++++++++++++++++++++++++++ php/run_greeter_client_with_auth.sh | 37 +++++++++++++++++++ 4 files changed, 116 insertions(+) create mode 100644 php/greeter_client_with_auth.php create mode 100755 php/run_greeter_client_with_auth.sh diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 9b97203276b..aff952a0503 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -174,3 +174,24 @@ if (authorization.IsCreateScopedRequired) var client = new Greeter.GreeterClient(channel, new StubConfiguration(OAuth2InterceptorFactory.Create(credential))); ``` + +###Authenticating with Google (PHP) +```php +// Base case - No encryption/authorization +$client = new helloworld\GreeterClient( + new Grpc\BaseStub('localhost:50051', [])); +... + +// Authenticating with Google +// the environment variable "GOOGLE_APPLICATION_CREDENTIALS" needs to be set +$scope = "https://www.googleapis.com/auth/grpc-testing"; +$auth = Google\Auth\ApplicationDefaultCredentials::getCredentials($scope); +$opts = [ + 'credentials' => Grpc\Credentials::createSsl(file_get_contents('ca.pem')); + 'update_metadata' => $auth->getUpdateMetadataFunc(), +]; + +$client = new helloworld\GreeterClient( + new Grpc\BaseStub('localhost:50051', $opts)); + +``` diff --git a/php/composer.json b/php/composer.json index d1c4bd2a183..f0ce3a2aff4 100644 --- a/php/composer.json +++ b/php/composer.json @@ -11,6 +11,7 @@ "require": { "php": ">=5.5.0", "datto/protobuf-php": "dev-master", + "google/auth": "dev-master", "grpc/grpc": "dev-master" } } diff --git a/php/greeter_client_with_auth.php b/php/greeter_client_with_auth.php new file mode 100644 index 00000000000..39e28fcb80b --- /dev/null +++ b/php/greeter_client_with_auth.php @@ -0,0 +1,57 @@ + Grpc\Credentials::createSsl( + // file_get_contents(getenv('SSL_CERT_FILE'))), + 'update_metadata' => $auth->getUpdateMetadataFunc(), + ]; + $client = new helloworld\GreeterClient( + new Grpc\BaseStub('localhost:50051', $opts)); + + $request = new helloworld\HelloRequest(); + $request->setName($name); + list($reply, $status) = $client->SayHello($request)->wait(); + $message = $reply->getMessage(); + return $message; +} + +$name = !empty($argv[1]) ? $argv[1] : 'world'; +print(greet($name)."\n"); diff --git a/php/run_greeter_client_with_auth.sh b/php/run_greeter_client_with_auth.sh new file mode 100755 index 00000000000..b367096b9b3 --- /dev/null +++ b/php/run_greeter_client_with_auth.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Copyright 2015, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +set -e +cd $(dirname $0) +command -v brew >/dev/null 2>&1 && \ + extension_dir="-d extension_dir="`brew --prefix`/opt/grpc-php +# path to project credentials .json file +export GOOGLE_APPLICATION_CREDENTIALS='' +php $extension_dir -d extension=grpc.so greeter_client_with_auth.php $1 From 20f68f6a63713ab2a9d59732cbc6c8a956c8735e Mon Sep 17 00:00:00 2001 From: Misha Brukman Date: Wed, 24 Jun 2015 09:44:39 -0400 Subject: [PATCH 373/576] Add syntax highlighting for C++ code samples. --- grpc-auth-support.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 6a5ef0fa3d0..78dfd9ade2a 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -31,7 +31,7 @@ Tokens to each request being made on the channel. This is the simplest authentication scenario, where a client just wants to authenticate the server and encrypt all data. -``` +```cpp SslCredentialsOptions ssl_opts; // Options to override SSL params, empty by default // Create the credentials object by providing service account key in constructor std::unique_ptr creds = CredentialsFactory::SslCredentials(ssl_opts); @@ -52,7 +52,7 @@ passed to the factory method. gRPC applications can use a simple API to create a credential that works in various deployment scenarios. -``` +```cpp std::unique_ptr creds = CredentialsFactory::GoogleDefaultCredentials(); // Create a channel, stub and make RPC calls (same as in the previous example) std::shared_ptr channel = CreateChannel(server_name, creds, channel_args); From 05514b042497a4584ec092f40af09d811f904da5 Mon Sep 17 00:00:00 2001 From: Misha Brukman Date: Wed, 24 Jun 2015 09:45:20 -0400 Subject: [PATCH 374/576] Fix comments: code blocks ignore MarkDown. --- grpc-auth-support.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grpc-auth-support.md b/grpc-auth-support.md index 78dfd9ade2a..7f538d1a841 100644 --- a/grpc-auth-support.md +++ b/grpc-auth-support.md @@ -108,7 +108,7 @@ stub = Helloworld::Greeter::Stub.new('localhost:50051') ... # Authenticating with Google -require 'googleauth' # from [googleauth](http://www.rubydoc.info/gems/googleauth/0.1.0) +require 'googleauth' # from http://www.rubydoc.info/gems/googleauth/0.1.0 ... creds = GRPC::Core::Credentials.new(load_certs) # load_certs typically loads a CA roots file scope = 'https://www.googleapis.com/auth/grpc-testing' From 865deaeee9ff5c89864dd89c360b0e2c2b1e2c7c Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Wed, 24 Jun 2015 11:24:17 -0700 Subject: [PATCH 375/576] remove with_auth example because no ssl --- php/greeter_client_with_auth.php | 57 ----------------------------- php/run_greeter_client_with_auth.sh | 37 ------------------- 2 files changed, 94 deletions(-) delete mode 100644 php/greeter_client_with_auth.php delete mode 100755 php/run_greeter_client_with_auth.sh diff --git a/php/greeter_client_with_auth.php b/php/greeter_client_with_auth.php deleted file mode 100644 index 39e28fcb80b..00000000000 --- a/php/greeter_client_with_auth.php +++ /dev/null @@ -1,57 +0,0 @@ - Grpc\Credentials::createSsl( - // file_get_contents(getenv('SSL_CERT_FILE'))), - 'update_metadata' => $auth->getUpdateMetadataFunc(), - ]; - $client = new helloworld\GreeterClient( - new Grpc\BaseStub('localhost:50051', $opts)); - - $request = new helloworld\HelloRequest(); - $request->setName($name); - list($reply, $status) = $client->SayHello($request)->wait(); - $message = $reply->getMessage(); - return $message; -} - -$name = !empty($argv[1]) ? $argv[1] : 'world'; -print(greet($name)."\n"); diff --git a/php/run_greeter_client_with_auth.sh b/php/run_greeter_client_with_auth.sh deleted file mode 100755 index b367096b9b3..00000000000 --- a/php/run_greeter_client_with_auth.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -# Copyright 2015, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set -e -cd $(dirname $0) -command -v brew >/dev/null 2>&1 && \ - extension_dir="-d extension_dir="`brew --prefix`/opt/grpc-php -# path to project credentials .json file -export GOOGLE_APPLICATION_CREDENTIALS='' -php $extension_dir -d extension=grpc.so greeter_client_with_auth.php $1 From 1f0d49bb6e91571cb2a56f3bed2be76a3ea3ec92 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Wed, 8 Jul 2015 16:44:55 -0700 Subject: [PATCH 376/576] Fixes per the review. --- objective-c/auth_sample/README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/objective-c/auth_sample/README.md b/objective-c/auth_sample/README.md index 06812323bc4..b6776860a11 100644 --- a/objective-c/auth_sample/README.md +++ b/objective-c/auth_sample/README.md @@ -11,7 +11,7 @@ headers. It assumes you know the basics on how to make gRPC API calls using the Objective-C client library, as shown in the [Hello World](https://github.com/grpc/grpc-common/tree/master/objective-c/helloworld) or [Route Guide](https://github.com/grpc/grpc-common/tree/master/objective-c/route_guide) tutorials, -and familiarity with OAuth2 concepts like _access token_. +and are familiar with OAuth2 concepts like _access token_. - [Example code and setup](#setup) - [Try it out!](#try) @@ -42,9 +42,9 @@ access token obtained by the first view. Note: OAuth2 libraries need the application to register and obtain an ID from the identity provider (in the case of this example app, Google). The app's XCode project is configured using that ID, so -you shouldn't copy this project as is for your own app: It would result in your app being identified -in the consent screen as "gRPC-AuthSample", and not having access to real Google services. Instead, -configure your XCode project following the [instructions here](https://developers.google.com/identity/sign-in/ios/). +you shouldn't copy this project "as is" for your own app: it would result in your app being +identified in the consent screen as "gRPC-AuthSample", and not having access to real Google +services. Instead, configure your own XCode project following the [instructions here](https://developers.google.com/identity/sign-in/ios/). As with the other examples, you also should have [Cocoapods](https://cocoapods.org/#install) installed, as well as the relevant tools to generate the client library code. You can obtain the @@ -74,7 +74,7 @@ give the "gRPC-AuthSample" app the following permissions: - "Test scope for access to the Zoo service". This last permission, corresponding to the scope `https://www.googleapis.com/auth/xapi.zoo` doesn't -grant any real capability: It's only used for testing. You can log out at any moment. +grant any real capability: it's only used for testing. You can log out at any time. The second view, `MakeRPCViewController.h/m`, makes a gRPC request to a test server at https://grpc-test.sandbox.google.com, sending the access token along with the request. The test @@ -102,8 +102,8 @@ service TestService { } ``` -A `unaryCallWithRequest:handler:` method is generated, with which you're already familiar, is -generated for the `AUTHTestService` class: +A `unaryCallWithRequest:handler:` method, with which you're already familiar, is generated for the +`AUTHTestService` class: ```objective-c [client unaryCallWithRequest:request handler:^(AUTHResponse *response, NSError *error) { @@ -111,7 +111,7 @@ generated for the `AUTHTestService` class: }]; ``` -And a second `RPCToUnaryCallWithRequest:handler:` method is generated, which returns a +In addition, an `RPCToUnaryCallWithRequest:handler:` method is generated, which returns a not-yet-started RPC object: ```objective-c @@ -156,8 +156,8 @@ If you have an access token, OAuth2 specifies it is to be sent in this format: ## Get response metadata of a call: Auth challenge header -Analogously to the request metadata, the `ProtoRPC` class has a `responseMetadata` property defined -this way: +The `ProtoRPC` class also has a `responseMetadata` property, analogous to the request metadata we +just looked at. It's defined like this: ```objective-c @property(atomic, readonly) NSDictionary *responseMetadata; From 71e4c9679fa556d24f390adb3fc89f8675f3ec53 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Thu, 9 Jul 2015 10:10:15 -0700 Subject: [PATCH 377/576] Explain a bit more what metadata is. --- objective-c/auth_sample/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/objective-c/auth_sample/README.md b/objective-c/auth_sample/README.md index b6776860a11..335e29f98b0 100644 --- a/objective-c/auth_sample/README.md +++ b/objective-c/auth_sample/README.md @@ -139,7 +139,8 @@ The `ProtoRPC` class has a `requestMetadata` property defined like this: ``` Setting it to a dictionary of metadata keys and values will have them sent on the wire when the call -is started. +is started. gRPC metadata are pieces of information about the call sent by the client to the server +(and vice versa). They take the form of key-value pairs and are essentially opaque to gRPC itself. ```objective-c call.requestMetadata = [NSMutableDictionary dictionaryWithDictionary: From 03515a50c74749f84d8279837c988eaa17f55920 Mon Sep 17 00:00:00 2001 From: Jan Tattermusch Date: Thu, 9 Jul 2015 21:59:48 -0700 Subject: [PATCH 378/576] upgrade greeter to use 0.6.0 release packages --- csharp/.nuget/packages.config | 2 +- csharp/Greeter/Greeter.csproj | 19 ++++++++++--------- csharp/Greeter/packages.config | 8 ++++---- csharp/GreeterClient/GreeterClient.csproj | 19 ++++++++++--------- csharp/GreeterClient/packages.config | 8 ++++---- csharp/GreeterServer/GreeterServer.csproj | 19 ++++++++++--------- csharp/GreeterServer/packages.config | 8 ++++---- 7 files changed, 43 insertions(+), 40 deletions(-) diff --git a/csharp/.nuget/packages.config b/csharp/.nuget/packages.config index 966d46a2833..b14373069f1 100644 --- a/csharp/.nuget/packages.config +++ b/csharp/.nuget/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/csharp/Greeter/Greeter.csproj b/csharp/Greeter/Greeter.csproj index 8899836e97a..b8f965dbd22 100644 --- a/csharp/Greeter/Greeter.csproj +++ b/csharp/Greeter/Greeter.csproj @@ -1,6 +1,6 @@  - + @@ -13,7 +13,7 @@ Greeter Greeter v4.5 - 4d99595a + 927432a0 true @@ -40,13 +40,14 @@ ..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - + False - ..\packages\Grpc.Core.0.5.1\lib\net45\Grpc.Core.dll + ..\packages\Grpc.Core.0.6.0\lib\net45\Grpc.Core.dll - - ..\packages\Microsoft.Bcl.Immutable.1.0.34\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + + False + ..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll ..\packages\Ix-Async.1.2.3\lib\net45\System.Interactive.Async.dll @@ -71,10 +72,10 @@ - - + + - + \ No newline at end of file diff --git a/csharp/Greeter/packages.config b/csharp/Greeter/packages.config index 481390ef9d0..5922553bc37 100644 --- a/csharp/Greeter/packages.config +++ b/csharp/Greeter/packages.config @@ -1,11 +1,11 @@  - - + + - + - + \ No newline at end of file diff --git a/csharp/GreeterClient/GreeterClient.csproj b/csharp/GreeterClient/GreeterClient.csproj index 3a1feb367ef..59b768af018 100644 --- a/csharp/GreeterClient/GreeterClient.csproj +++ b/csharp/GreeterClient/GreeterClient.csproj @@ -1,6 +1,6 @@  - + @@ -13,7 +13,7 @@ GreeterClient GreeterClient v4.5 - 9e922694 + 985ca8be true @@ -40,13 +40,14 @@ ..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - + False - ..\packages\Grpc.Core.0.5.1\lib\net45\Grpc.Core.dll + ..\packages\Grpc.Core.0.6.0\lib\net45\Grpc.Core.dll - - ..\packages\Microsoft.Bcl.Immutable.1.0.34\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + + False + ..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll ..\packages\Ix-Async.1.2.3\lib\net45\System.Interactive.Async.dll @@ -74,10 +75,10 @@ - - + + - + \ No newline at end of file diff --git a/csharp/GreeterClient/packages.config b/csharp/GreeterClient/packages.config index 481390ef9d0..5922553bc37 100644 --- a/csharp/GreeterClient/packages.config +++ b/csharp/GreeterClient/packages.config @@ -1,11 +1,11 @@  - - + + - + - + \ No newline at end of file diff --git a/csharp/GreeterServer/GreeterServer.csproj b/csharp/GreeterServer/GreeterServer.csproj index da73168dc5e..cd50d6cd529 100644 --- a/csharp/GreeterServer/GreeterServer.csproj +++ b/csharp/GreeterServer/GreeterServer.csproj @@ -1,6 +1,6 @@  - + @@ -13,7 +13,7 @@ GreeterServer GreeterServer v4.5 - d79af25e + a1eeb1d8 true @@ -40,13 +40,14 @@ ..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - + False - ..\packages\Grpc.Core.0.5.1\lib\net45\Grpc.Core.dll + ..\packages\Grpc.Core.0.6.0\lib\net45\Grpc.Core.dll - - ..\packages\Microsoft.Bcl.Immutable.1.0.34\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + + False + ..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll ..\packages\Ix-Async.1.2.3\lib\net45\System.Interactive.Async.dll @@ -74,10 +75,10 @@ - - + + - + \ No newline at end of file diff --git a/csharp/GreeterServer/packages.config b/csharp/GreeterServer/packages.config index 481390ef9d0..5922553bc37 100644 --- a/csharp/GreeterServer/packages.config +++ b/csharp/GreeterServer/packages.config @@ -1,11 +1,11 @@  - - + + - + - + \ No newline at end of file From 0ea1009381dc4efe8cebb833857513e4c53e90c8 Mon Sep 17 00:00:00 2001 From: Jan Tattermusch Date: Thu, 9 Jul 2015 22:03:52 -0700 Subject: [PATCH 379/576] update route guide to use 0.6.0 release packages --- csharp/route_guide/.nuget/packages.config | 2 +- .../route_guide/RouteGuide/RouteGuide.csproj | 19 ++++++++++--------- csharp/route_guide/RouteGuide/packages.config | 8 ++++---- .../RouteGuideClient/RouteGuideClient.csproj | 19 ++++++++++--------- .../RouteGuideClient/packages.config | 8 ++++---- .../RouteGuideServer/RouteGuideServer.csproj | 19 ++++++++++--------- .../RouteGuideServer/packages.config | 8 ++++---- 7 files changed, 43 insertions(+), 40 deletions(-) diff --git a/csharp/route_guide/.nuget/packages.config b/csharp/route_guide/.nuget/packages.config index 966d46a2833..b14373069f1 100644 --- a/csharp/route_guide/.nuget/packages.config +++ b/csharp/route_guide/.nuget/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/csharp/route_guide/RouteGuide/RouteGuide.csproj b/csharp/route_guide/RouteGuide/RouteGuide.csproj index 3de2417c708..8358974aac0 100644 --- a/csharp/route_guide/RouteGuide/RouteGuide.csproj +++ b/csharp/route_guide/RouteGuide/RouteGuide.csproj @@ -1,6 +1,6 @@  - + @@ -14,7 +14,7 @@ RouteGuide v4.5 512 - 58253d57 + 214cccda true @@ -40,17 +40,18 @@ ..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - + False - ..\packages\Grpc.Core.0.5.1\lib\net45\Grpc.Core.dll + ..\packages\Grpc.Core.0.6.0\lib\net45\Grpc.Core.dll False ..\packages\Newtonsoft.Json.7.0.1-beta2\lib\net45\Newtonsoft.Json.dll - - ..\packages\Microsoft.Bcl.Immutable.1.0.34\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + + False + ..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll @@ -84,12 +85,12 @@ - - + + - + + + + + + + + + + + + + + + + + + + diff --git a/src/objective-c/examples/SwiftSample/Images.xcassets/AppIcon.appiconset/Contents.json b/src/objective-c/examples/SwiftSample/Images.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000000..36d2c80d889 --- /dev/null +++ b/src/objective-c/examples/SwiftSample/Images.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/src/objective-c/examples/SwiftSample/Info.plist b/src/objective-c/examples/SwiftSample/Info.plist new file mode 100644 index 00000000000..10f0450b346 --- /dev/null +++ b/src/objective-c/examples/SwiftSample/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + io.grpc.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + Main + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..fcfa890241f --- /dev/null +++ b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj @@ -0,0 +1,286 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 633BFFC81B950B210007E424 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633BFFC71B950B210007E424 /* AppDelegate.swift */; }; + 633BFFCA1B950B210007E424 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633BFFC91B950B210007E424 /* ViewController.swift */; }; + 633BFFCD1B950B210007E424 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 633BFFCB1B950B210007E424 /* Main.storyboard */; }; + 633BFFCF1B950B210007E424 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 633BFFCE1B950B210007E424 /* Images.xcassets */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 633BFFC21B950B210007E424 /* SwiftSample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftSample.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 633BFFC61B950B210007E424 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 633BFFC71B950B210007E424 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 633BFFC91B950B210007E424 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 633BFFCC1B950B210007E424 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 633BFFCE1B950B210007E424 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 633BFFBF1B950B210007E424 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 633BFFB91B950B210007E424 = { + isa = PBXGroup; + children = ( + 633BFFC41B950B210007E424 /* SwiftSample */, + 633BFFC31B950B210007E424 /* Products */, + ); + sourceTree = ""; + }; + 633BFFC31B950B210007E424 /* Products */ = { + isa = PBXGroup; + children = ( + 633BFFC21B950B210007E424 /* SwiftSample.app */, + ); + name = Products; + sourceTree = ""; + }; + 633BFFC41B950B210007E424 /* SwiftSample */ = { + isa = PBXGroup; + children = ( + 633BFFC71B950B210007E424 /* AppDelegate.swift */, + 633BFFC91B950B210007E424 /* ViewController.swift */, + 633BFFCB1B950B210007E424 /* Main.storyboard */, + 633BFFCE1B950B210007E424 /* Images.xcassets */, + 633BFFC51B950B210007E424 /* Supporting Files */, + ); + name = SwiftSample; + sourceTree = SOURCE_ROOT; + }; + 633BFFC51B950B210007E424 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 633BFFC61B950B210007E424 /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 633BFFC11B950B210007E424 /* SwiftSample */ = { + isa = PBXNativeTarget; + buildConfigurationList = 633BFFE11B950B210007E424 /* Build configuration list for PBXNativeTarget "SwiftSample" */; + buildPhases = ( + 633BFFBE1B950B210007E424 /* Sources */, + 633BFFBF1B950B210007E424 /* Frameworks */, + 633BFFC01B950B210007E424 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftSample; + productName = SwiftSample; + productReference = 633BFFC21B950B210007E424 /* SwiftSample.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 633BFFBA1B950B210007E424 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0640; + ORGANIZATIONNAME = gRPC; + TargetAttributes = { + 633BFFC11B950B210007E424 = { + CreatedOnToolsVersion = 6.4; + }; + }; + }; + buildConfigurationList = 633BFFBD1B950B210007E424 /* Build configuration list for PBXProject "SwiftSample" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 633BFFB91B950B210007E424; + productRefGroup = 633BFFC31B950B210007E424 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 633BFFC11B950B210007E424 /* SwiftSample */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 633BFFC01B950B210007E424 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 633BFFCD1B950B210007E424 /* Main.storyboard in Resources */, + 633BFFCF1B950B210007E424 /* Images.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 633BFFBE1B950B210007E424 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 633BFFCA1B950B210007E424 /* ViewController.swift in Sources */, + 633BFFC81B950B210007E424 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 633BFFCB1B950B210007E424 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 633BFFCC1B950B210007E424 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 633BFFDF1B950B210007E424 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 633BFFE01B950B210007E424 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 633BFFE21B950B210007E424 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 633BFFE31B950B210007E424 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 633BFFBD1B950B210007E424 /* Build configuration list for PBXProject "SwiftSample" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 633BFFDF1B950B210007E424 /* Debug */, + 633BFFE01B950B210007E424 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 633BFFE11B950B210007E424 /* Build configuration list for PBXNativeTarget "SwiftSample" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 633BFFE21B950B210007E424 /* Debug */, + 633BFFE31B950B210007E424 /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; +/* End XCConfigurationList section */ + }; + rootObject = 633BFFBA1B950B210007E424 /* Project object */; +} diff --git a/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..3b0f1c15b24 --- /dev/null +++ b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/src/objective-c/examples/SwiftSample/ViewController.swift b/src/objective-c/examples/SwiftSample/ViewController.swift new file mode 100644 index 00000000000..73dd9531679 --- /dev/null +++ b/src/objective-c/examples/SwiftSample/ViewController.swift @@ -0,0 +1,43 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } +} + From 5e5733b36c89ec0e90c0f672c4be2cfce4b7019e Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Mon, 31 Aug 2015 15:58:16 -0700 Subject: [PATCH 562/576] Test Podfile --- src/objective-c/examples/SwiftSample/Podfile | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 src/objective-c/examples/SwiftSample/Podfile diff --git a/src/objective-c/examples/SwiftSample/Podfile b/src/objective-c/examples/SwiftSample/Podfile new file mode 100644 index 00000000000..0caa8cae8b2 --- /dev/null +++ b/src/objective-c/examples/SwiftSample/Podfile @@ -0,0 +1,8 @@ +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' + +pod 'gRPC', :path => "../../../.." +# pod 'RemoteTest', :path => "../../generated_libraries/RemoteTestClient" + +target 'SwiftSample' do +end From fd09d84f66f2f2bc4a377a0e51285fdf42e55d5b Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Mon, 31 Aug 2015 15:58:48 -0700 Subject: [PATCH 563/576] Install pods in project --- .../SwiftSample.xcodeproj/project.pbxproj | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj index fcfa890241f..4f176b2923c 100644 --- a/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj +++ b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 253D3A297105CA46DA960A11 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = DC58ACA18DCCB1553531B885 /* libPods.a */; }; 633BFFC81B950B210007E424 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633BFFC71B950B210007E424 /* AppDelegate.swift */; }; 633BFFCA1B950B210007E424 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633BFFC91B950B210007E424 /* ViewController.swift */; }; 633BFFCD1B950B210007E424 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 633BFFCB1B950B210007E424 /* Main.storyboard */; }; @@ -14,12 +15,15 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 12C7B447AA80E624D93B5C54 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; 633BFFC21B950B210007E424 /* SwiftSample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftSample.app; sourceTree = BUILT_PRODUCTS_DIR; }; 633BFFC61B950B210007E424 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 633BFFC71B950B210007E424 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 633BFFC91B950B210007E424 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; 633BFFCC1B950B210007E424 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 633BFFCE1B950B210007E424 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; + C335CBC4C160E0D9EDEE646B /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + DC58ACA18DCCB1553531B885 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -27,17 +31,29 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 253D3A297105CA46DA960A11 /* libPods.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 31F283C976AE97586C17CCD9 /* Pods */ = { + isa = PBXGroup; + children = ( + 12C7B447AA80E624D93B5C54 /* Pods.debug.xcconfig */, + C335CBC4C160E0D9EDEE646B /* Pods.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; 633BFFB91B950B210007E424 = { isa = PBXGroup; children = ( 633BFFC41B950B210007E424 /* SwiftSample */, 633BFFC31B950B210007E424 /* Products */, + 31F283C976AE97586C17CCD9 /* Pods */, + 9D63A7F6423989BA306810CA /* Frameworks */, ); sourceTree = ""; }; @@ -69,6 +85,14 @@ name = "Supporting Files"; sourceTree = ""; }; + 9D63A7F6423989BA306810CA /* Frameworks */ = { + isa = PBXGroup; + children = ( + DC58ACA18DCCB1553531B885 /* libPods.a */, + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -76,9 +100,11 @@ isa = PBXNativeTarget; buildConfigurationList = 633BFFE11B950B210007E424 /* Build configuration list for PBXNativeTarget "SwiftSample" */; buildPhases = ( + 6BEEB33CA2705D7D2F2210E6 /* Check Pods Manifest.lock */, 633BFFBE1B950B210007E424 /* Sources */, 633BFFBF1B950B210007E424 /* Frameworks */, 633BFFC01B950B210007E424 /* Resources */, + AC2F6F9AB1C090BB0BEE6E4D /* Copy Pods Resources */, ); buildRules = ( ); @@ -133,6 +159,39 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 6BEEB33CA2705D7D2F2210E6 /* Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + AC2F6F9AB1C090BB0BEE6E4D /* Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 633BFFBE1B950B210007E424 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -242,6 +301,7 @@ }; 633BFFE21B950B210007E424 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 12C7B447AA80E624D93B5C54 /* Pods.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = Info.plist; @@ -252,6 +312,7 @@ }; 633BFFE31B950B210007E424 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = C335CBC4C160E0D9EDEE646B /* Pods.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = Info.plist; @@ -279,6 +340,7 @@ 633BFFE31B950B210007E424 /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; From 587c2550dd83b92ef454f4f7f5f3ad44f9934e7d Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Mon, 31 Aug 2015 16:17:15 -0700 Subject: [PATCH 564/576] Add empty bridging header --- .../examples/SwiftSample/Bridging-Header.h | 38 +++++++++++++++++++ .../SwiftSample.xcodeproj/project.pbxproj | 6 +++ 2 files changed, 44 insertions(+) create mode 100644 src/objective-c/examples/SwiftSample/Bridging-Header.h diff --git a/src/objective-c/examples/SwiftSample/Bridging-Header.h b/src/objective-c/examples/SwiftSample/Bridging-Header.h new file mode 100644 index 00000000000..a85f7f7a5ac --- /dev/null +++ b/src/objective-c/examples/SwiftSample/Bridging-Header.h @@ -0,0 +1,38 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef SwiftSample_Bridging_Header_h +#define SwiftSample_Bridging_Header_h + + +#endif diff --git a/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj index 4f176b2923c..cfccdd453f7 100644 --- a/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj +++ b/src/objective-c/examples/SwiftSample/SwiftSample.xcodeproj/project.pbxproj @@ -22,6 +22,7 @@ 633BFFC91B950B210007E424 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; 633BFFCC1B950B210007E424 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 633BFFCE1B950B210007E424 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; + 6367AD231B951655007FD3A4 /* Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bridging-Header.h"; sourceTree = ""; }; C335CBC4C160E0D9EDEE646B /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; DC58ACA18DCCB1553531B885 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -73,6 +74,7 @@ 633BFFCB1B950B210007E424 /* Main.storyboard */, 633BFFCE1B950B210007E424 /* Images.xcassets */, 633BFFC51B950B210007E424 /* Supporting Files */, + 6367AD231B951655007FD3A4 /* Bridging-Header.h */, ); name = SwiftSample; sourceTree = SOURCE_ROOT; @@ -307,6 +309,8 @@ INFOPLIST_FILE = Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Bridging-Header.h"; + USER_HEADER_SEARCH_PATHS = "Pods/**"; }; name = Debug; }; @@ -318,6 +322,8 @@ INFOPLIST_FILE = Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Bridging-Header.h"; + USER_HEADER_SEARCH_PATHS = "Pods/**"; }; name = Release; }; From 875d1d15c85358c735d449c347d1e6b3c015e594 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Mon, 31 Aug 2015 18:05:56 -0700 Subject: [PATCH 565/576] Add Swift example with non-generated code :D --- .../examples/SwiftSample/Bridging-Header.h | 5 +++++ .../examples/SwiftSample/ViewController.swift | 22 +++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/objective-c/examples/SwiftSample/Bridging-Header.h b/src/objective-c/examples/SwiftSample/Bridging-Header.h index a85f7f7a5ac..3b2ae74d8b4 100644 --- a/src/objective-c/examples/SwiftSample/Bridging-Header.h +++ b/src/objective-c/examples/SwiftSample/Bridging-Header.h @@ -34,5 +34,10 @@ #ifndef SwiftSample_Bridging_Header_h #define SwiftSample_Bridging_Header_h +#import +#import +#import +#import +#import #endif diff --git a/src/objective-c/examples/SwiftSample/ViewController.swift b/src/objective-c/examples/SwiftSample/ViewController.swift index 73dd9531679..dedcce20e7c 100644 --- a/src/objective-c/examples/SwiftSample/ViewController.swift +++ b/src/objective-c/examples/SwiftSample/ViewController.swift @@ -37,7 +37,25 @@ class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - // Do any additional setup after loading the view, typically from a nib. + + let RemoteHost = "grpc-test.sandbox.google.com" + + // Same example call using the generic gRPC client library: + + let method = ProtoMethod(package: "grpc.testing", service: "TestService", method: "UnaryCall") + + let requestsWriter = GRXWriter(value: NSData()) + + let call = GRPCCall(host: RemoteHost, path: method.HTTPPath, requestsWriter: requestsWriter) + + let responsesWriteable = GRXWriteable { (value: AnyObject?, error: NSError?) in + if let value = value as? NSData { + NSLog("Received response:\n\(value)") + } else { + NSLog("Finished with error: \(error!)") + } + } + + call.startWithWriteable(responsesWriteable) } } - From 0bf6b20876e14769abf4f2c871abe25d3fa8b3f7 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Mon, 31 Aug 2015 18:17:46 -0700 Subject: [PATCH 566/576] =?UTF-8?q?Create=20RemoteTest=20proto=20client=20?= =?UTF-8?q?that=20doesn=E2=80=99t=20depend=20on=20the=20tests=20framework?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RemoteTestClient/RemoteTest.podspec | 28 ++++ .../examples/RemoteTestClient/empty.proto | 44 ++++++ .../examples/RemoteTestClient/messages.proto | 133 ++++++++++++++++++ .../examples/RemoteTestClient/test.proto | 73 ++++++++++ 4 files changed, 278 insertions(+) create mode 100644 src/objective-c/examples/RemoteTestClient/RemoteTest.podspec create mode 100644 src/objective-c/examples/RemoteTestClient/empty.proto create mode 100644 src/objective-c/examples/RemoteTestClient/messages.proto create mode 100644 src/objective-c/examples/RemoteTestClient/test.proto diff --git a/src/objective-c/examples/RemoteTestClient/RemoteTest.podspec b/src/objective-c/examples/RemoteTestClient/RemoteTest.podspec new file mode 100644 index 00000000000..dcb0c4e500e --- /dev/null +++ b/src/objective-c/examples/RemoteTestClient/RemoteTest.podspec @@ -0,0 +1,28 @@ +Pod::Spec.new do |s| + s.name = "RemoteTest" + s.version = "0.0.1" + s.license = "New BSD" + + s.ios.deployment_target = "6.0" + s.osx.deployment_target = "10.8" + + # Run protoc with the Objective-C and gRPC plugins to generate protocol messages and gRPC clients. + s.prepare_command = <<-CMD + protoc --objc_out=. --objcgrpc_out=. *.proto + CMD + + s.subspec "Messages" do |ms| + ms.source_files = "*.pbobjc.{h,m}" + ms.header_mappings_dir = "." + ms.requires_arc = false + ms.dependency "Protobuf", "~> 3.0.0-alpha-3" + end + + s.subspec "Services" do |ss| + ss.source_files = "*.pbrpc.{h,m}" + ss.header_mappings_dir = "." + ss.requires_arc = true + ss.dependency "gRPC", "~> 0.5" + ss.dependency "#{s.name}/Messages" + end +end diff --git a/src/objective-c/examples/RemoteTestClient/empty.proto b/src/objective-c/examples/RemoteTestClient/empty.proto new file mode 100644 index 00000000000..a678048289e --- /dev/null +++ b/src/objective-c/examples/RemoteTestClient/empty.proto @@ -0,0 +1,44 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package grpc.testing; + +option objc_class_prefix = "RMT"; + +// An empty message that you can re-use to avoid defining duplicated empty +// messages in your project. A typical example is to use it as argument or the +// return value of a service API. For instance: +// +// service Foo { +// rpc Bar (grpc.testing.Empty) returns (grpc.testing.Empty) { }; +// }; +// +message Empty {} diff --git a/src/objective-c/examples/RemoteTestClient/messages.proto b/src/objective-c/examples/RemoteTestClient/messages.proto new file mode 100644 index 00000000000..85d93c2ff96 --- /dev/null +++ b/src/objective-c/examples/RemoteTestClient/messages.proto @@ -0,0 +1,133 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Message definitions to be used by integration test service definitions. + +syntax = "proto3"; + +package grpc.testing; + +option objc_class_prefix = "RMT"; + +// The type of payload that should be returned. +enum PayloadType { + // Compressable text format. + COMPRESSABLE = 0; + + // Uncompressable binary format. + UNCOMPRESSABLE = 1; + + // Randomly chosen from all other formats defined in this enum. + RANDOM = 2; +} + +// A block of data, to simply increase gRPC message size. +message Payload { + // The type of data in body. + PayloadType type = 1; + // Primary contents of payload. + bytes body = 2; +} + +// Unary request. +message SimpleRequest { + // Desired payload type in the response from the server. + // If response_type is RANDOM, server randomly chooses one from other formats. + PayloadType response_type = 1; + + // Desired payload size in the response from the server. + // If response_type is COMPRESSABLE, this denotes the size before compression. + int32 response_size = 2; + + // Optional input payload sent along with the request. + Payload payload = 3; + + // Whether SimpleResponse should include username. + bool fill_username = 4; + + // Whether SimpleResponse should include OAuth scope. + bool fill_oauth_scope = 5; +} + +// Unary response, as configured by the request. +message SimpleResponse { + // Payload to increase message size. + Payload payload = 1; + // The user the request came from, for verifying authentication was + // successful when the client expected it. + string username = 2; + // OAuth scope. + string oauth_scope = 3; +} + +// Client-streaming request. +message StreamingInputCallRequest { + // Optional input payload sent along with the request. + Payload payload = 1; + + // Not expecting any payload from the response. +} + +// Client-streaming response. +message StreamingInputCallResponse { + // Aggregated size of payloads received from the client. + int32 aggregated_payload_size = 1; +} + +// Configuration for a particular response. +message ResponseParameters { + // Desired payload sizes in responses from the server. + // If response_type is COMPRESSABLE, this denotes the size before compression. + int32 size = 1; + + // Desired interval between consecutive responses in the response stream in + // microseconds. + int32 interval_us = 2; +} + +// Server-streaming request. +message StreamingOutputCallRequest { + // Desired payload type in the response from the server. + // If response_type is RANDOM, the payload from each response in the stream + // might be of different types. This is to simulate a mixed type of payload + // stream. + PayloadType response_type = 1; + + // Configuration for each expected response message. + repeated ResponseParameters response_parameters = 2; + + // Optional input payload sent along with the request. + Payload payload = 3; +} + +// Server-streaming response, as configured by the request and parameters. +message StreamingOutputCallResponse { + // Payload to increase response size. + Payload payload = 1; +} diff --git a/src/objective-c/examples/RemoteTestClient/test.proto b/src/objective-c/examples/RemoteTestClient/test.proto new file mode 100644 index 00000000000..2f5a5489b3d --- /dev/null +++ b/src/objective-c/examples/RemoteTestClient/test.proto @@ -0,0 +1,73 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// An integration test service that covers all the method signature permutations +// of unary/streaming requests/responses. +syntax = "proto3"; + +import "empty.proto"; +import "messages.proto"; + +package grpc.testing; + +option objc_class_prefix = "RMT"; + +// A simple service to test the various types of RPCs and experiment with +// performance with various types of payload. +service TestService { + // One empty request followed by one empty response. + rpc EmptyCall(grpc.testing.Empty) returns (grpc.testing.Empty); + + // One request followed by one response. + // TODO(Issue 527): Describe required server behavior. + rpc UnaryCall(SimpleRequest) returns (SimpleResponse); + + // One request followed by a sequence of responses (streamed download). + // The server returns the payload with client desired type and sizes. + rpc StreamingOutputCall(StreamingOutputCallRequest) + returns (stream StreamingOutputCallResponse); + + // A sequence of requests followed by one response (streamed upload). + // The server returns the aggregated size of client payload as the result. + rpc StreamingInputCall(stream StreamingInputCallRequest) + returns (StreamingInputCallResponse); + + // A sequence of requests with each request served by the server immediately. + // As one request could lead to multiple responses, this interface + // demonstrates the idea of full duplexing. + rpc FullDuplexCall(stream StreamingOutputCallRequest) + returns (stream StreamingOutputCallResponse); + + // A sequence of requests followed by a sequence of responses. + // The server buffers all the client requests and then serves them in order. A + // stream of responses are returned to the client when the server starts with + // first request. + rpc HalfDuplexCall(stream StreamingOutputCallRequest) + returns (stream StreamingOutputCallResponse); +} From d4a0785569c78486b0917a5fc949034fbb53dd01 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Mon, 31 Aug 2015 18:18:07 -0700 Subject: [PATCH 567/576] Point to the new RemoteTest pod --- src/objective-c/examples/SwiftSample/Podfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/objective-c/examples/SwiftSample/Podfile b/src/objective-c/examples/SwiftSample/Podfile index 0caa8cae8b2..7b5941eef79 100644 --- a/src/objective-c/examples/SwiftSample/Podfile +++ b/src/objective-c/examples/SwiftSample/Podfile @@ -2,7 +2,7 @@ source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' pod 'gRPC', :path => "../../../.." -# pod 'RemoteTest', :path => "../../generated_libraries/RemoteTestClient" +pod 'RemoteTest', :path => "../RemoteTestClient" target 'SwiftSample' do end From 9fffc2618740111691454acaec65854c99027f53 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Mon, 31 Aug 2015 19:15:21 -0700 Subject: [PATCH 568/576] Example with generated code :) --- .../examples/SwiftSample/Bridging-Header.h | 1 + .../examples/SwiftSample/ViewController.swift | 20 +++++++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/objective-c/examples/SwiftSample/Bridging-Header.h b/src/objective-c/examples/SwiftSample/Bridging-Header.h index 3b2ae74d8b4..33db2dd1cbc 100644 --- a/src/objective-c/examples/SwiftSample/Bridging-Header.h +++ b/src/objective-c/examples/SwiftSample/Bridging-Header.h @@ -39,5 +39,6 @@ #import #import #import +#import #endif diff --git a/src/objective-c/examples/SwiftSample/ViewController.swift b/src/objective-c/examples/SwiftSample/ViewController.swift index dedcce20e7c..e4e7aeae49b 100644 --- a/src/objective-c/examples/SwiftSample/ViewController.swift +++ b/src/objective-c/examples/SwiftSample/ViewController.swift @@ -40,17 +40,33 @@ class ViewController: UIViewController { let RemoteHost = "grpc-test.sandbox.google.com" + let request = RMTSimpleRequest() + request.responseSize = 10 + request.fillUsername = true + request.fillOauthScope = true + + // Example gRPC call using a generated proto client library: + + let service = RMTTestService(host: RemoteHost) + service.unaryCallWithRequest(request) { (response: RMTSimpleResponse?, error: NSError?) in + if let response = response { + NSLog("Finished successfully with response:\n\(response)") + } else { + NSLog("Finished with error: \(error!)") + } + } + // Same example call using the generic gRPC client library: let method = ProtoMethod(package: "grpc.testing", service: "TestService", method: "UnaryCall") - let requestsWriter = GRXWriter(value: NSData()) + let requestsWriter = GRXWriter(value: request.data()) let call = GRPCCall(host: RemoteHost, path: method.HTTPPath, requestsWriter: requestsWriter) let responsesWriteable = GRXWriteable { (value: AnyObject?, error: NSError?) in if let value = value as? NSData { - NSLog("Received response:\n\(value)") + NSLog("Received response:\n\(RMTSimpleResponse(data: value, error: nil))") } else { NSLog("Finished with error: \(error!)") } From d5904820aa3388961284b1b23d94e9c9a5fbcdc9 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Mon, 31 Aug 2015 21:30:58 -0700 Subject: [PATCH 569/576] Windows tweak --- tools/run_tests/run_tests.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/run_tests/run_tests.py b/tools/run_tests/run_tests.py index 64900b62008..20abc7df1aa 100755 --- a/tools/run_tests/run_tests.py +++ b/tools/run_tests/run_tests.py @@ -281,7 +281,10 @@ class CSharpLanguage(object): def make_targets(self): # For Windows, this target doesn't really build anything, # everything is build by buildall script later. - return ['grpc_csharp_ext'] + if self.platform == 'windows': + return [] + else: + return ['grpc_csharp_ext'] def build_steps(self): if self.platform == 'windows': From bd4e378445395bc752139e190bc21fd3b5182a11 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Tue, 1 Sep 2015 06:48:55 -0700 Subject: [PATCH 570/576] Windows tweak --- tools/run_tests/run_tests.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tools/run_tests/run_tests.py b/tools/run_tests/run_tests.py index 20abc7df1aa..8e7dd06cad0 100755 --- a/tools/run_tests/run_tests.py +++ b/tools/run_tests/run_tests.py @@ -455,7 +455,6 @@ build_configs = set(cfg.build_config for cfg in run_configs) if args.travis: _FORCE_ENVIRON_FOR_WRAPPERS = {'GRPC_TRACE': 'surface,batch'} -make_targets = [] languages = set(_LANGUAGES[l] for l in itertools.chain.from_iterable( _LANGUAGES.iterkeys() if x == 'all' else [x] @@ -481,10 +480,12 @@ else: 'CONFIG=%s' % cfg] + targets, timeout_seconds=30*60) -build_steps = [make_jobspec(cfg, - list(set(itertools.chain.from_iterable( - l.make_targets() for l in languages)))) - for cfg in build_configs] +make_targets = list(set(itertools.chain.from_iterable( + l.make_targets() for l in languages))) +build_steps = [] +if make_targets: + build_steps.extend(set(make_jobspec(cfg, make_targets) + for cfg in build_configs)) build_steps.extend(set( jobset.JobSpec(cmdline, environ={'CONFIG': cfg}) for cfg in build_configs From 6277569023f5ab25a2c5e6563ecbd366f7e4ce58 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Tue, 1 Sep 2015 07:08:01 -0700 Subject: [PATCH 571/576] Fix sanity --- tools/run_tests/run_sanity.sh | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tools/run_tests/run_sanity.sh b/tools/run_tests/run_sanity.sh index 2737e564c6d..dd096ce2c27 100755 --- a/tools/run_tests/run_sanity.sh +++ b/tools/run_tests/run_sanity.sh @@ -36,13 +36,11 @@ export TEST=true cd `dirname $0`/../.. -./tools/buildgen/generate_projects.sh - -submodules=`mktemp` - -git submodule > $submodules +submodules=`mktemp /tmp/submXXXXXX` +want_submodules=`mktemp /tmp/submXXXXXX` -diff -u $submodules - << EOF +git submodule | awk '{ print $1 }' | sort > $submodules +cat << EOF | awk '{ print $1 }' | sort > $want_submodules 05b155ff59114735ec8cd089f669c4c3d8f59029 third_party/gflags (v2.1.0-45-g05b155f) c99458533a9b4c743ed51537e25989ea55944908 third_party/googletest (release-1.7.0) 33dd08320648ac71d7d9d732be774ed3818dccc5 third_party/openssl (OpenSSL_1_0_2d) @@ -50,7 +48,11 @@ diff -u $submodules - << EOF 50893291621658f355bc5b4d450a8d06a563053d third_party/zlib (v1.2.8) EOF -if [ -f cache.mk ] ; then +diff -u $submodules $want_submodules + +if git ls-files cache.mk --error-unmatch &> /dev/null ; then echo "Please don't commit cache.mk" exit 1 fi + +./tools/buildgen/generate_projects.sh From 49198ec928e1bbe30e1e51a61e7632abe4fba188 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Tue, 1 Sep 2015 07:10:03 -0700 Subject: [PATCH 572/576] Tidy up --- tools/run_tests/run_sanity.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/run_tests/run_sanity.sh b/tools/run_tests/run_sanity.sh index dd096ce2c27..32e25661fa9 100755 --- a/tools/run_tests/run_sanity.sh +++ b/tools/run_tests/run_sanity.sh @@ -50,6 +50,8 @@ EOF diff -u $submodules $want_submodules +rm $submodules $want_submodules + if git ls-files cache.mk --error-unmatch &> /dev/null ; then echo "Please don't commit cache.mk" exit 1 From 2402078be383845a45b314d0385543d8cd5347c0 Mon Sep 17 00:00:00 2001 From: Nathaniel Manista Date: Tue, 1 Sep 2015 15:13:59 +0000 Subject: [PATCH 573/576] Bump Python version to 0.11 and status to Beta --- src/python/README.md | 2 +- src/python/grpcio/setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/python/README.md b/src/python/README.md index a21deb33efa..67d1a173a27 100644 --- a/src/python/README.md +++ b/src/python/README.md @@ -4,7 +4,7 @@ The Python facility of gRPC. Status ------- -Alpha : Ready for early adopters +Beta : Core behavior well-used and proven; bugs lurk off the beaten path. PREREQUISITES ------------- diff --git a/src/python/grpcio/setup.py b/src/python/grpcio/setup.py index caa71a4f7c8..4735ce080b0 100644 --- a/src/python/grpcio/setup.py +++ b/src/python/grpcio/setup.py @@ -104,7 +104,7 @@ _COMMAND_CLASS = { setuptools.setup( name='grpcio', - version='0.10.0a0', + version='0.11.0', ext_modules=_EXTENSION_MODULES, packages=list(_PACKAGES), package_dir=_PACKAGE_DIRECTORIES, From 0d728c1e9eb9f685eedc27788e6923378d115459 Mon Sep 17 00:00:00 2001 From: "Nicolas \"Pixel\" Noble" Date: Tue, 1 Sep 2015 20:23:09 +0200 Subject: [PATCH 574/576] Bumping revision to 0.11 for beta. --- Makefile | 2 +- build.yaml | 2 +- src/core/surface/version.c | 2 +- tools/doxygen/Doxyfile.c++ | 2 +- tools/doxygen/Doxyfile.c++.internal | 2 +- tools/doxygen/Doxyfile.core | 2 +- tools/doxygen/Doxyfile.core.internal | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index b724ee2a7c9..00875cd8e7d 100644 --- a/Makefile +++ b/Makefile @@ -309,7 +309,7 @@ E = @echo Q = @ endif -VERSION = 0.10.1.0 +VERSION = 0.11.0.0 CPPFLAGS_NO_ARCH += $(addprefix -I, $(INCLUDES)) $(addprefix -D, $(DEFINES)) CPPFLAGS += $(CPPFLAGS_NO_ARCH) $(ARCH_FLAGS) diff --git a/build.yaml b/build.yaml index 183c0ae78fd..31a1e328a8a 100644 --- a/build.yaml +++ b/build.yaml @@ -3,7 +3,7 @@ '#3': Please refer to the templates directory for more information. settings: '#': The public version number of the library. - version: {major: 0, minor: 10, micro: 1, build: 0} + version: {major: 0, minor: 11, micro: 0, build: 0} filegroups: - name: census public_headers: [include/grpc/census.h] diff --git a/src/core/surface/version.c b/src/core/surface/version.c index d7aaba3868e..4b90e06a043 100644 --- a/src/core/surface/version.c +++ b/src/core/surface/version.c @@ -37,5 +37,5 @@ #include const char *grpc_version_string(void) { - return "0.10.1.0"; + return "0.11.0.0"; } diff --git a/tools/doxygen/Doxyfile.c++ b/tools/doxygen/Doxyfile.c++ index 96708c06227..a3523417743 100644 --- a/tools/doxygen/Doxyfile.c++ +++ b/tools/doxygen/Doxyfile.c++ @@ -40,7 +40,7 @@ PROJECT_NAME = "GRPC C++" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 0.10.1.0 +PROJECT_NUMBER = 0.11.0.0 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/tools/doxygen/Doxyfile.c++.internal b/tools/doxygen/Doxyfile.c++.internal index 185d24720ce..dfaeb43ca7a 100644 --- a/tools/doxygen/Doxyfile.c++.internal +++ b/tools/doxygen/Doxyfile.c++.internal @@ -40,7 +40,7 @@ PROJECT_NAME = "GRPC C++" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 0.10.1.0 +PROJECT_NUMBER = 0.11.0.0 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/tools/doxygen/Doxyfile.core b/tools/doxygen/Doxyfile.core index 4c83e22b7f1..beb0128e41a 100644 --- a/tools/doxygen/Doxyfile.core +++ b/tools/doxygen/Doxyfile.core @@ -40,7 +40,7 @@ PROJECT_NAME = "GRPC Core" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 0.10.1.0 +PROJECT_NUMBER = 0.11.0.0 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/tools/doxygen/Doxyfile.core.internal b/tools/doxygen/Doxyfile.core.internal index 729f8bf2ff7..fdc32c77765 100644 --- a/tools/doxygen/Doxyfile.core.internal +++ b/tools/doxygen/Doxyfile.core.internal @@ -40,7 +40,7 @@ PROJECT_NAME = "GRPC Core" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 0.10.1.0 +PROJECT_NUMBER = 0.11.0.0 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a From 7fa51677bc025a565181ce4ee0dd0f6b71260505 Mon Sep 17 00:00:00 2001 From: "Nicolas \"Pixel\" Noble" Date: Wed, 2 Sep 2015 02:29:09 +0200 Subject: [PATCH 575/576] Removing pessimizing moves. These have been reported by a (very recent) build of clang and its new -Wpessimizing-move option. --- test/cpp/end2end/async_end2end_test.cc | 5 ++--- test/cpp/end2end/end2end_test.cc | 5 ++--- test/cpp/end2end/mock_test.cc | 2 +- test/cpp/end2end/shutdown_test.cc | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/test/cpp/end2end/async_end2end_test.cc b/test/cpp/end2end/async_end2end_test.cc index 686e7627b98..cfb6c21edc9 100644 --- a/test/cpp/end2end/async_end2end_test.cc +++ b/test/cpp/end2end/async_end2end_test.cc @@ -200,7 +200,7 @@ class AsyncEnd2endTest : public ::testing::TestWithParam { void ResetStub() { std::shared_ptr channel = CreateChannel(server_address_.str(), InsecureCredentials()); - stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel)); + stub_ = grpc::cpp::test::util::TestService::NewStub(channel); } void SendRpc(int num_rpcs) { @@ -751,8 +751,7 @@ TEST_P(AsyncEnd2endTest, UnimplementedRpc) { std::shared_ptr channel = CreateChannel(server_address_.str(), InsecureCredentials()); std::unique_ptr stub; - stub = - std::move(grpc::cpp::test::util::UnimplementedService::NewStub(channel)); + stub = grpc::cpp::test::util::UnimplementedService::NewStub(channel); EchoRequest send_request; EchoResponse recv_response; Status recv_status; diff --git a/test/cpp/end2end/end2end_test.cc b/test/cpp/end2end/end2end_test.cc index 10a4c5ac26c..bd829d96e1d 100644 --- a/test/cpp/end2end/end2end_test.cc +++ b/test/cpp/end2end/end2end_test.cc @@ -380,7 +380,7 @@ class End2endTest : public ::testing::TestWithParam { channel_ = CreateChannel(proxyaddr.str(), InsecureCredentials()); } - stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel_)); + stub_ = grpc::cpp::test::util::TestService::NewStub(channel_); } bool is_server_started_; @@ -1080,8 +1080,7 @@ TEST_F(End2endTest, ChannelState) { TEST_F(End2endTest, NonExistingService) { ResetChannel(); std::unique_ptr stub; - stub = - std::move(grpc::cpp::test::util::UnimplementedService::NewStub(channel_)); + stub = grpc::cpp::test::util::UnimplementedService::NewStub(channel_); EchoRequest request; EchoResponse response; diff --git a/test/cpp/end2end/mock_test.cc b/test/cpp/end2end/mock_test.cc index 4450e29f09f..9c35fede8f6 100644 --- a/test/cpp/end2end/mock_test.cc +++ b/test/cpp/end2end/mock_test.cc @@ -245,7 +245,7 @@ class MockTest : public ::testing::Test { void ResetStub() { std::shared_ptr channel = CreateChannel(server_address_.str(), InsecureCredentials()); - stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel)); + stub_ = grpc::cpp::test::util::TestService::NewStub(channel); } std::unique_ptr stub_; diff --git a/test/cpp/end2end/shutdown_test.cc b/test/cpp/end2end/shutdown_test.cc index a25f85cc75a..0549bb8b5f7 100644 --- a/test/cpp/end2end/shutdown_test.cc +++ b/test/cpp/end2end/shutdown_test.cc @@ -94,7 +94,7 @@ class ShutdownTest : public ::testing::Test { void ResetStub() { string target = "dns:localhost:" + to_string(port_); channel_ = CreateChannel(target, InsecureCredentials()); - stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel_)); + stub_ = grpc::cpp::test::util::TestService::NewStub(channel_); } string to_string(const int number) { From f95390a74eb23a5894c3ed7289c8e2aa276e9ba4 Mon Sep 17 00:00:00 2001 From: Donna Dionne Date: Wed, 2 Sep 2015 09:33:11 -0700 Subject: [PATCH 576/576] Updating service account as service account is regenerated for the project. --- tools/gce_setup/grpc_docker.sh | 28 ++++++++++++------------- tools/gce_setup/shared_startup_funcs.sh | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/tools/gce_setup/grpc_docker.sh b/tools/gce_setup/grpc_docker.sh index ea7c798f408..3fbd342b4c5 100755 --- a/tools/gce_setup/grpc_docker.sh +++ b/tools/gce_setup/grpc_docker.sh @@ -1129,7 +1129,7 @@ grpc_cloud_prod_auth_service_account_creds_gen_python_cmd() { local gfe_flags=$(_grpc_prod_gfe_flags) local added_gfe_flags=$(_grpc_default_creds_test_flags) local env_prefix="SSL_CERT_FILE=/cacerts/roots.pem" - env_prefix+=" GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json" + env_prefix+=" GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json" local the_cmd="$cmd_prefix '$env_prefix python -B -m interop.client --use_tls $gfe_flags $added_gfe_flags $@'" echo $the_cmd } @@ -1207,7 +1207,7 @@ grpc_cloud_prod_auth_service_account_creds_gen_ruby_cmd() { local gfe_flags=$(_grpc_prod_gfe_flags) local added_gfe_flags=$(_grpc_default_creds_test_flags) local env_prefix="SSL_CERT_FILE=/cacerts/roots.pem" - env_prefix+=" GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json" + env_prefix+=" GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json" local the_cmd="$cmd_prefix '$env_prefix ruby $test_script $gfe_flags $added_gfe_flags $@'" echo $the_cmd } @@ -1239,7 +1239,7 @@ grpc_cloud_prod_auth_jwt_token_creds_gen_ruby_cmd() { local test_script+=" --use_tls" local gfe_flags=$(_grpc_prod_gfe_flags) local env_prefix="SSL_CERT_FILE=/cacerts/roots.pem" - env_prefix+=" GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json" + env_prefix+=" GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json" local the_cmd="$cmd_prefix '$env_prefix ruby $test_script $gfe_flags $added_gfe_flags $@'" echo $the_cmd } @@ -1362,7 +1362,7 @@ grpc_cloud_prod_gen_php_cmd() { # cmd=$($grpc_gen_test_cmd $flags) grpc_cloud_prod_auth_service_account_creds_gen_php_cmd() { local env_flag="-e SSL_CERT_FILE=/cacerts/roots.pem " - env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local cmd_prefix="sudo docker run $env_flag grpc/php"; local test_script="/var/local/git/grpc/src/php/bin/interop_client.sh"; local gfe_flags=$(_grpc_prod_gfe_flags); @@ -1393,7 +1393,7 @@ grpc_cloud_prod_auth_compute_engine_creds_gen_php_cmd() { # cmd=$($grpc_gen_test_cmd $flags) grpc_cloud_prod_auth_jwt_token_creds_gen_php_cmd() { local env_flag="-e SSL_CERT_FILE=/cacerts/roots.pem " - env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local cmd_prefix="sudo docker run $env_flag grpc/php"; local test_script="/var/local/git/grpc/src/php/bin/interop_client.sh"; local gfe_flags=$(_grpc_prod_gfe_flags); @@ -1434,7 +1434,7 @@ grpc_cloud_prod_gen_node_cmd() { # cmd=$($grpc_gen_test_cmd $flags) grpc_cloud_prod_auth_service_account_creds_gen_node_cmd() { local env_flag="-e SSL_CERT_FILE=/cacerts/roots.pem " - env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local cmd_prefix="sudo docker run $env_flag grpc/node"; local test_script="/usr/bin/nodejs /var/local/git/grpc/src/node/interop/interop_client.js --use_tls=true"; local gfe_flags=$(_grpc_prod_gfe_flags); @@ -1586,7 +1586,7 @@ grpc_cloud_prod_gen_csharp_dotnet_cmd() { grpc_cloud_prod_auth_service_account_creds_gen_csharp_mono_cmd() { local workdir_flag="-w /var/local/git/grpc/src/csharp/Grpc.IntegrationTesting.Client/bin/Debug" local env_flag="-e SSL_CERT_FILE=/cacerts/roots.pem " - env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local cmd_prefix="sudo docker run $workdir_flag $env_flag grpc/csharp_mono"; local test_script="mono Grpc.IntegrationTesting.Client.exe --use_tls=true"; local gfe_flags=$(_grpc_prod_gfe_flags); @@ -1603,7 +1603,7 @@ grpc_cloud_prod_auth_service_account_creds_gen_csharp_dotnet_cmd() { local set_workdir="cd /cygdrive/c/github/grpc/src/csharp/Grpc.IntegrationTesting.Client/bin/Debug &&" local test_script="./Grpc.IntegrationTesting.Client.exe --use_tls=true"; local set_certfile="SSL_CERT_FILE=/cacerts/roots.pem " - local set_creds="GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + local set_creds="GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local gfe_flags=$(_grpc_prod_gfe_flags); local the_cmd="$set_workdir $set_certfile $set_creds $test_script $gfe_flags $@"; echo $the_cmd @@ -1646,7 +1646,7 @@ grpc_cloud_prod_auth_compute_engine_creds_gen_csharp_dotnet_cmd() { grpc_cloud_prod_auth_oauth2_auth_token_gen_csharp_mono_cmd() { local workdir_flag="-w /var/local/git/grpc/src/csharp/Grpc.IntegrationTesting.Client/bin/Debug" local env_flag="-e SSL_CERT_FILE=/cacerts/roots.pem " - env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local cmd_prefix="sudo docker run $workdir_flag $env_flag grpc/csharp_mono"; local test_script="mono Grpc.IntegrationTesting.Client.exe --use_tls=true"; local gfe_flags=$(_grpc_prod_gfe_flags); @@ -1663,7 +1663,7 @@ grpc_cloud_prod_auth_oauth2_auth_token_gen_csharp_dotnet_cmd() { local set_workdir="cd /cygdrive/c/github/grpc/src/csharp/Grpc.IntegrationTesting.Client/bin/Debug &&" local test_script="./Grpc.IntegrationTesting.Client.exe --use_tls=true"; local set_certfile="SSL_CERT_FILE=/cacerts/roots.pem " - local set_creds="GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + local set_creds="GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local gfe_flags=$(_grpc_prod_gfe_flags); local the_cmd="$set_workdir $set_certfile $set_creds $test_script $gfe_flags $@"; echo $the_cmd @@ -1677,7 +1677,7 @@ grpc_cloud_prod_auth_oauth2_auth_token_gen_csharp_dotnet_cmd() { grpc_cloud_prod_auth_per_rpc_creds_gen_csharp_mono_cmd() { local workdir_flag="-w /var/local/git/grpc/src/csharp/Grpc.IntegrationTesting.Client/bin/Debug" local env_flag="-e SSL_CERT_FILE=/cacerts/roots.pem " - env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + env_flag+="-e GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local cmd_prefix="sudo docker run $workdir_flag $env_flag grpc/csharp_mono"; local test_script="mono Grpc.IntegrationTesting.Client.exe --use_tls=true"; local gfe_flags=$(_grpc_prod_gfe_flags); @@ -1694,7 +1694,7 @@ grpc_cloud_prod_auth_per_rpc_creds_gen_csharp_dotnet_cmd() { local set_workdir="cd /cygdrive/c/github/grpc/src/csharp/Grpc.IntegrationTesting.Client/bin/Debug &&" local test_script="./Grpc.IntegrationTesting.Client.exe --use_tls=true"; local set_certfile="SSL_CERT_FILE=/cacerts/roots.pem " - local set_creds="GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-7dd63462c60c.json " + local set_creds="GOOGLE_APPLICATION_CREDENTIALS=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json " local gfe_flags=$(_grpc_prod_gfe_flags); local the_cmd="$set_workdir $set_certfile $set_creds $test_script $gfe_flags $@"; echo $the_cmd @@ -1707,12 +1707,12 @@ _grpc_prod_gfe_flags() { # outputs the flags passed to the service account auth tests _grpc_svc_acc_test_flags() { - echo " --service_account_key_file=/service_account/stubbyCloudTestingTest-7dd63462c60c.json --oauth_scope=https://www.googleapis.com/auth/xapi.zoo" + echo " --service_account_key_file=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json --oauth_scope=https://www.googleapis.com/auth/xapi.zoo" } # outputs the flags passed to the service account auth tests _grpc_jwt_token_test_flags() { - echo " --service_account_key_file=/service_account/stubbyCloudTestingTest-7dd63462c60c.json" + echo " --service_account_key_file=/service_account/stubbyCloudTestingTest-ee3fce360ac5.json" } # default credentials test flag diff --git a/tools/gce_setup/shared_startup_funcs.sh b/tools/gce_setup/shared_startup_funcs.sh index 60cd9f6897b..ffa08751535 100755 --- a/tools/gce_setup/shared_startup_funcs.sh +++ b/tools/gce_setup/shared_startup_funcs.sh @@ -552,8 +552,8 @@ grpc_docker_sync_service_account() { local gcs_admin_root=$(dirname $gs_dockerfile_root) # cp the file from gsutil to a known local area - local gcs_acct_path=$gcs_admin_root/service_account/stubbyCloudTestingTest-7dd63462c60c.json - local local_acct_path=$target_dir/stubbyCloudTestingTest-7dd63462c60c.json + local gcs_acct_path=$gcs_admin_root/service_account/stubbyCloudTestingTest-ee3fce360ac5.json + local local_acct_path=$target_dir/stubbyCloudTestingTest-ee3fce360ac5.json mkdir -p $target_dir || { echo "$FUNCNAME: could not create dir: $target_dir" 1>&2 return 1