From 813112ec4222436c6466b56f35a85e0f8f2351bc Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 6 Feb 2015 13:09:20 -0800 Subject: [PATCH 01/38] Moves java overview project to a subdirectory --- pom.xml | 105 +++ run_greetings_client.sh | 10 + run_greetings_server.sh | 9 + src/main/java/ex/grpc/GreetingsClient.java | 55 ++ src/main/java/ex/grpc/GreetingsGrpc.java | 172 ++++ src/main/java/ex/grpc/GreetingsImpl.java | 16 + src/main/java/ex/grpc/GreetingsServer.java | 51 ++ src/main/java/ex/grpc/Helloworld.java | 951 +++++++++++++++++++++ src/main/proto/helloworld.proto | 22 + 9 files changed, 1391 insertions(+) create mode 100644 pom.xml create mode 100755 run_greetings_client.sh create mode 100755 run_greetings_server.sh create mode 100644 src/main/java/ex/grpc/GreetingsClient.java create mode 100644 src/main/java/ex/grpc/GreetingsGrpc.java create mode 100644 src/main/java/ex/grpc/GreetingsImpl.java create mode 100644 src/main/java/ex/grpc/GreetingsServer.java create mode 100644 src/main/java/ex/grpc/Helloworld.java create mode 100644 src/main/proto/helloworld.proto diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000000..da0ee205f7 --- /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 + + + + + + + + + diff --git a/run_greetings_client.sh b/run_greetings_client.sh new file mode 100755 index 0000000000..8155589adf --- /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 0000000000..248229e129 --- /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" diff --git a/src/main/java/ex/grpc/GreetingsClient.java b/src/main/java/ex/grpc/GreetingsClient.java new file mode 100644 index 0000000000..4ae2e7076b --- /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(); + } + } +} diff --git a/src/main/java/ex/grpc/GreetingsGrpc.java b/src/main/java/ex/grpc/GreetingsGrpc.java new file mode 100644 index 0000000000..97c2f00a1e --- /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/GreetingsImpl.java b/src/main/java/ex/grpc/GreetingsImpl.java new file mode 100644 index 0000000000..005489acaa --- /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 0000000000..834ae985a4 --- /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(); + } +} diff --git a/src/main/java/ex/grpc/Helloworld.java b/src/main/java/ex/grpc/Helloworld.java new file mode 100644 index 0000000000..f72040fa2b --- /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) +} diff --git a/src/main/proto/helloworld.proto b/src/main/proto/helloworld.proto new file mode 100644 index 0000000000..da5c3a1d85 --- /dev/null +++ b/src/main/proto/helloworld.proto @@ -0,0 +1,22 @@ +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) { + } +} From e342471965a3147df478fa48008cd5d681ba77a1 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 17:22:46 -0800 Subject: [PATCH 02/38] Updates generated code to reflect the proto changes in #19 --- .../{GreetingsGrpc.java => GreeterGrpc.java} | 126 +++++++++--------- .../{GreetingsImpl.java => GreeterImpl.java} | 4 +- src/main/java/ex/grpc/GreetingsClient.java | 6 +- src/main/java/ex/grpc/GreetingsServer.java | 2 +- src/main/java/ex/grpc/Helloworld.java | 12 +- 5 files changed, 75 insertions(+), 75 deletions(-) rename src/main/java/ex/grpc/{GreetingsGrpc.java => GreeterGrpc.java} (51%) rename src/main/java/ex/grpc/{GreetingsImpl.java => GreeterImpl.java} (75%) diff --git a/src/main/java/ex/grpc/GreetingsGrpc.java b/src/main/java/ex/grpc/GreeterGrpc.java similarity index 51% rename from src/main/java/ex/grpc/GreetingsGrpc.java rename to src/main/java/ex/grpc/GreeterGrpc.java index 97c2f00a1e..080c3dfc43 100644 --- a/src/main/java/ex/grpc/GreetingsGrpc.java +++ b/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/src/main/java/ex/grpc/GreetingsImpl.java b/src/main/java/ex/grpc/GreeterImpl.java similarity index 75% rename from src/main/java/ex/grpc/GreetingsImpl.java rename to src/main/java/ex/grpc/GreeterImpl.java index 005489acaa..825ba8631e 100644 --- a/src/main/java/ex/grpc/GreetingsImpl.java +++ b/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/src/main/java/ex/grpc/GreetingsClient.java b/src/main/java/ex/grpc/GreetingsClient.java index 4ae2e7076b..141ad1e20a 100644 --- a/src/main/java/ex/grpc/GreetingsClient.java +++ b/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/src/main/java/ex/grpc/GreetingsServer.java b/src/main/java/ex/grpc/GreetingsServer.java index 834ae985a4..237309d13c 100644 --- a/src/main/java/ex/grpc/GreetingsServer.java +++ b/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/src/main/java/ex/grpc/Helloworld.java b/src/main/java/ex/grpc/Helloworld.java index f72040fa2b..b25a63fca3 100644 --- a/src/main/java/ex/grpc/Helloworld.java +++ b/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 56947163434834d408398201d9eaa2ed6ae276bb Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Wed, 18 Feb 2015 17:43:41 -0800 Subject: [PATCH 03/38] Complete the change s/Greetings/Greeter --- run_greetings_client.sh => run_greeter_client.sh | 4 ++-- run_greetings_server.sh => run_greeter_server.sh | 4 ++-- .../ex/grpc/{GreetingsClient.java => GreeterClient.java} | 8 ++++---- .../ex/grpc/{GreetingsServer.java => GreeterServer.java} | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) rename run_greetings_client.sh => run_greeter_client.sh (80%) rename run_greetings_server.sh => run_greeter_server.sh (78%) rename src/main/java/ex/grpc/{GreetingsClient.java => GreeterClient.java} (89%) rename src/main/java/ex/grpc/{GreetingsServer.java => GreeterServer.java} (88%) diff --git a/run_greetings_client.sh b/run_greeter_client.sh similarity index 80% rename from run_greetings_client.sh rename to run_greeter_client.sh index 8155589adf..e86ab4ae89 100755 --- a/run_greetings_client.sh +++ b/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/run_greetings_server.sh b/run_greeter_server.sh similarity index 78% rename from run_greetings_server.sh rename to run_greeter_server.sh index 248229e129..836abc7f48 100755 --- a/run_greetings_server.sh +++ b/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/src/main/java/ex/grpc/GreetingsClient.java b/src/main/java/ex/grpc/GreeterClient.java similarity index 89% rename from src/main/java/ex/grpc/GreetingsClient.java rename to src/main/java/ex/grpc/GreeterClient.java index 141ad1e20a..9a4615132d 100644 --- a/src/main/java/ex/grpc/GreetingsClient.java +++ b/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/src/main/java/ex/grpc/GreetingsServer.java b/src/main/java/ex/grpc/GreeterServer.java similarity index 88% rename from src/main/java/ex/grpc/GreetingsServer.java rename to src/main/java/ex/grpc/GreeterServer.java index 237309d13c..bb05680b0a 100644 --- a/src/main/java/ex/grpc/GreetingsServer.java +++ b/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 5c1b10a4f17839c9d083b1db4a50541b6b96aa2b Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Thu, 19 Feb 2015 07:30:43 -0800 Subject: [PATCH 04/38] Removes the unused protos, updates the README to reflect the protos in use --- src/main/proto/helloworld.proto | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 src/main/proto/helloworld.proto diff --git a/src/main/proto/helloworld.proto b/src/main/proto/helloworld.proto deleted file mode 100644 index da5c3a1d85..0000000000 --- a/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) { - } -} From 1cd1209c7161c19f4bde823b9dc4907ffb8c1bc9 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Mon, 23 Feb 2015 19:15:09 -0800 Subject: [PATCH 05/38] Adds a quickstart README for java with working instructions --- README.md | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000000..8cd0e59896 --- /dev/null +++ b/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 3b7d09bd341e23074e766d4ab1c4d95ec909829e Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 03:58:40 -0800 Subject: [PATCH 06/38] Fixed Maven version --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8cd0e59896..35c9db3192 100644 --- a/README.md +++ b/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 f3b5e7ab20f326523a4baa5f4fd78f3a63972a22 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 15:56:44 -0800 Subject: [PATCH 07/38] Update the Maven link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35c9db3192..4410f830f6 100644 --- a/README.md +++ b/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 7f6bb722e56f53b23d2951050cf5f85faefdabec Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Tue, 24 Feb 2015 15:57:30 -0800 Subject: [PATCH 08/38] Remove superfluous link to protobuf install --- README.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/README.md b/README.md index 4410f830f6..89724904d4 100644 --- a/README.md +++ b/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 d60ef19609f9b9e0f8a55bb0d502a4cd6d79b1fc Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Wed, 25 Feb 2015 18:46:17 +0000 Subject: [PATCH 09/38] New shiny Java tutorial --- javatutorial.md | 351 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 351 insertions(+) create mode 100644 javatutorial.md diff --git a/javatutorial.md b/javatutorial.md new file mode 100644 index 0000000000..4c419cf345 --- /dev/null +++ b/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 c716badd5648d87aba05a44c2c47839fdcd74b29 Mon Sep 17 00:00:00 2001 From: Lisa Carey Date: Wed, 25 Feb 2015 18:48:22 +0000 Subject: [PATCH 10/38] Fixed typo --- javatutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javatutorial.md b/javatutorial.md index 4c419cf345..e74573e0b4 100644 --- a/javatutorial.md +++ b/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 e82a0008354736d04a67c0cf54e67b2570be5cdb Mon Sep 17 00:00:00 2001 From: nmittler Date: Wed, 25 Feb 2015 11:02:03 -0800 Subject: [PATCH 11/38] Removing java examples from grpc-common --- pom.xml | 105 --- run_greeter_client.sh | 10 - run_greeter_server.sh | 9 - src/main/java/ex/grpc/GreeterClient.java | 55 -- src/main/java/ex/grpc/GreeterGrpc.java | 172 ---- src/main/java/ex/grpc/GreeterImpl.java | 16 - src/main/java/ex/grpc/GreeterServer.java | 51 -- src/main/java/ex/grpc/Helloworld.java | 951 ----------------------- 8 files changed, 1369 deletions(-) delete mode 100644 pom.xml delete mode 100755 run_greeter_client.sh delete mode 100755 run_greeter_server.sh delete mode 100644 src/main/java/ex/grpc/GreeterClient.java delete mode 100644 src/main/java/ex/grpc/GreeterGrpc.java delete mode 100644 src/main/java/ex/grpc/GreeterImpl.java delete mode 100644 src/main/java/ex/grpc/GreeterServer.java delete mode 100644 src/main/java/ex/grpc/Helloworld.java diff --git a/pom.xml b/pom.xml deleted file mode 100644 index da0ee205f7..0000000000 --- a/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/run_greeter_client.sh b/run_greeter_client.sh deleted file mode 100755 index e86ab4ae89..0000000000 --- a/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/run_greeter_server.sh b/run_greeter_server.sh deleted file mode 100755 index 836abc7f48..0000000000 --- a/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/src/main/java/ex/grpc/GreeterClient.java b/src/main/java/ex/grpc/GreeterClient.java deleted file mode 100644 index 9a4615132d..0000000000 --- a/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/src/main/java/ex/grpc/GreeterGrpc.java b/src/main/java/ex/grpc/GreeterGrpc.java deleted file mode 100644 index 080c3dfc43..0000000000 --- a/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/src/main/java/ex/grpc/GreeterImpl.java b/src/main/java/ex/grpc/GreeterImpl.java deleted file mode 100644 index 825ba8631e..0000000000 --- a/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/src/main/java/ex/grpc/GreeterServer.java b/src/main/java/ex/grpc/GreeterServer.java deleted file mode 100644 index bb05680b0a..0000000000 --- a/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/src/main/java/ex/grpc/Helloworld.java b/src/main/java/ex/grpc/Helloworld.java deleted file mode 100644 index b25a63fca3..0000000000 --- a/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 fa27c1a4d16e97e651f78279b5cc22e8d5b2ef17 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:20:20 +0000 Subject: [PATCH 12/38] Update javatutorial.md Updated with @nmittler's edits. --- javatutorial.md | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/javatutorial.md b/javatutorial.md index e74573e0b4..7465a8ab0e 100644 --- a/javatutorial.md +++ b/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 e691ffb8d43e38630fff8a043a39381b19af64d7 Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:25:47 +0000 Subject: [PATCH 13/38] Added note about using most recent compiler --- javatutorial.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javatutorial.md b/javatutorial.md index 7465a8ab0e..0b4fac0e69 100644 --- a/javatutorial.md +++ b/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 66206399a6d7023ea80e9314dc163d237c7aa4d9 Mon Sep 17 00:00:00 2001 From: Dan Ciruli Date: Wed, 25 Feb 2015 14:29:11 -0800 Subject: [PATCH 14/38] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 89724904d4..4c5e4c5902 100644 --- a/README.md +++ b/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 13177db5457fbc23e7aa4669e37fbbb43e0a4f6e Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:30:00 +0000 Subject: [PATCH 15/38] made last added comment a bit simpler! --- javatutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javatutorial.md b/javatutorial.md index 0b4fac0e69..05c122b8fc 100644 --- a/javatutorial.md +++ b/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 c6deececa7b6d2568bd5f3224fad704de9f83e8e Mon Sep 17 00:00:00 2001 From: LisaFC Date: Wed, 25 Feb 2015 22:34:56 +0000 Subject: [PATCH 16/38] changed gradle command to ./gradlew --- javatutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javatutorial.md b/javatutorial.md index 05c122b8fc..d4f3216d46 100644 --- a/javatutorial.md +++ b/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 78caf512970182cf85024b0f7070d002e3fd8c1c Mon Sep 17 00:00:00 2001 From: Xiao Hang Date: Wed, 25 Feb 2015 19:27:06 -0800 Subject: [PATCH 17/38] Update Android Helloworld example --- android/GreeterGrpc.java | 184 ++++++++++++++++++++++++++++++++ android/Helloworld.java | 175 ++++++++++++++++++++++++++++++ android/HelloworldActivity.java | 93 ++++++++++++++++ android/README.md | 71 ++++++++++++ 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 0000000000..eaef3679d2 --- /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 0000000000..35dd534512 --- /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 0000000000..a64d3f4d6a --- /dev/null +++ b/android/HelloworldActivity.java @@ -0,0 +1,93 @@ +package io.grpc.helloworldexample; + +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) { + Thread.currentThread().interrupt(); + } + mResultText.setText(result); + mSendButton.setEnabled(true); + } + } +} diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000000..6e6818a5df --- /dev/null +++ b/android/README.md @@ -0,0 +1,71 @@ +gRPC Hello World Tutorial (Android 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 +------------- +- [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 +$ 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 your_app_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 your_app_dir/app/libs/: + - grpc-java/core/build/libs/*.jar + - grpc-java/stub/build/libs/*.jar + - grpc-java/nano/build/libs/*.jar + - grpc-java/okhttp/build/libs/*.jar +- Copy or download other dependencies to your_app_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) + - protobuf nano: +```sh +$ cp ~/.m2/repository/com/google/protobuf/nano/protobuf-javanano/2.6.2-pre/protobuf-javanano-2.6.2-pre.jar your_app_dir/app/libs/ +``` +- Make sure your_app_dir/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 0000000000..41411d11aa --- /dev/null +++ b/android/activity_helloworld.xml @@ -0,0 +1,54 @@ + + + + + + + + + + +