Skip to content

Commit

Permalink
separate base files from example code
Browse files Browse the repository at this point in the history
  • Loading branch information
vnorigoog committed Jun 22, 2020
1 parent 8c96b8c commit c470eaa
Show file tree
Hide file tree
Showing 26 changed files with 656 additions and 160 deletions.
113 changes: 113 additions & 0 deletions net/grpc/gateway/examples/grpc-web-java/greeter-service/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>grpc.testing.main</groupId>
<artifactId>grpcweb-java-examples-greeter</artifactId>
<version>0.1</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<grpc-port>7080</grpc-port>
<grpc-web-port>8080</grpc-web-port>
</properties>

<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.11.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>com.google.grpcweb</groupId>
<artifactId>grpcweb-java</artifactId>
<version>0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.12</version>
</dependency>
</dependencies>

<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.4.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.7.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>


Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2020 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package grpcweb.examples.greeter;

import grpcweb.examples.greeter.GreeterOuterClass.HelloRequest;
import java.io.IOException;
import org.apache.http.HttpVersion;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;

/**
* A simple client that requests a greeting from the {@link GreeterService}.
*/
public class GreeterClient {
static byte[] sendGrpcWebReqAndReceiveResponse() throws IOException {
// create a HelloRequest obj
HelloRequest reqObj = HelloRequest.newBuilder().setName("foo").build();
byte[] packagedBytes = Util.packageReqObjIntoGrpcwebProtocol(reqObj);

// send request to the grpc-web server
ContentType contentType = ContentType.create("application/grpc-web");
int grpcWebPort = Util.getGrpcwebServicePortNum();
return Request.Post("http://localhost:" + grpcWebPort +
"/grpcweb.examples.greeter.Greeter/SayHello")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyByteArray(packagedBytes, contentType)
.execute().returnContent().asBytes();
}

public static void main(String[] args) throws Exception {
System.out.println("Response to Hello Request is: " +
new String(sendGrpcWebReqAndReceiveResponse()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2020 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package grpcweb.examples.greeter;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.google.protobuf.InvalidProtocolBufferException;
import grpcweb.examples.greeter.GreeterOuterClass.HelloReply;
import java.lang.invoke.MethodHandles;
import java.nio.ByteBuffer;
import java.util.logging.Logger;

/**
* A simple client that requests a greeting from the {@link GreeterService}.
*/
public class GreeterClientTest {
private static final Logger LOG =
Logger.getLogger(MethodHandles.lookup().lookupClass().getName());

private static void validateResponse(byte[] response) throws InvalidProtocolBufferException {
LOG.info("Response length = " + response.length);
LOG.info("Response is: " + new String(response));

// validate the 1st byte
assertEquals((byte)0x00, response[0]);

int len = ByteBuffer.wrap(response, 1, 4).getInt();
assertEquals(11, len);

// copy len bytes into a byte array, which can be xlated into HelloResponse
byte[] protoBytes = new byte[len];
System.arraycopy(response, 5, protoBytes, 0, len);
HelloReply reply = HelloReply.parseFrom(protoBytes);
assertEquals("Hello foo", reply.getMessage());

// if there is more data in the response, it should be a trailer.
int offset = len + 5;
int trailerBlockLen = response.length - offset;
if (trailerBlockLen == 0) {
// don't have any more bytes. we are done
return;
}
assertEquals((byte)0x80, response[offset]);
offset++;
int trailerLen = ByteBuffer.wrap(response, offset, 4).getInt();
assertTrue(trailerLen > 0);

byte[] trailer = new byte[trailerLen];
System.arraycopy(response, offset+4, trailer, 0, trailerLen);
String trailerStr = new String(trailer);
LOG.info("received trailer: " + trailerStr);
assertTrue(trailerStr.startsWith("grpc-status:0"));
}

public static void main(String[] args) throws Exception {
new StartServiceAndGrpcwebProxy().start();
byte[] response = GreeterClient.sendGrpcWebReqAndReceiveResponse();
validateResponse(response);
System.exit(0);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright 2020 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package grpcweb.examples.greeter;

import grpcweb.examples.greeter.GreeterOuterClass.HelloReply;
import grpcweb.examples.greeter.GreeterOuterClass.HelloRequest;
import io.grpc.stub.StreamObserver;

public class GreeterService extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
System.out.println("Greeter Service responding in sayhello() method");
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package grpcweb.examples.greeter;

import com.google.grpcweb.GrpcPortNumRelay;
import com.google.grpcweb.JettyWebserverForGrpcwebTraffic;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;

/**
* This class starts the service on a port (property: grpc-port)
* and starts the grpc-web proxy on a different port (property: grpc-web-port).
*/
class StartServiceAndGrpcwebProxy {
private void startGrpcService(int port) throws Exception {
Server grpcServer = ServerBuilder.forPort(port)
.addService((BindableService) new GreeterService())
.build();
grpcServer.start();
System.out.println("**** started gRPC Service on port# " + port);
}

void start() throws Exception {
int grpcPort = Util.getGrpcServicePortNum();
int grpcWebPort = Util.getGrpcwebServicePortNum();

// Start the Grpc service on grpc-port
startGrpcService(grpcPort);

// Start the grpc-web proxy on grpc-web-port.
(new JettyWebserverForGrpcwebTraffic(grpcWebPort)).start();

// grpc-web proxy needs to know the grpc-port# so it could connect to the grpc service.
GrpcPortNumRelay.setGrpcPortNum(grpcPort);
}

public static void main(String[] args) throws Exception {
new StartServiceAndGrpcwebProxy().start();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package grpcweb.examples.greeter;

import grpcweb.examples.greeter.GreeterOuterClass.HelloRequest;
import java.io.IOException;
import java.util.Properties;

class Util {
static byte[] packageReqObjIntoGrpcwebProtocol(HelloRequest req) {
byte[] reqObjBytes = req.toByteArray();
int len = reqObjBytes.length;
byte[] packagedBytes = new byte[5 + len];
packagedBytes[0] = (byte) 0x00;
packagedBytes[1] = (byte) ((len >> 24) & 0xff);
packagedBytes[2] = (byte) ((len >> 16) & 0xff);
packagedBytes[3] = (byte) ((len >> 8) & 0xff);
packagedBytes[4] = (byte) ((len >> 0) & 0xff);
System.arraycopy(reqObjBytes, 0, packagedBytes, 5, len);
return packagedBytes;
}

private static int getIntPropertyValue(String s) throws IOException {
java.io.InputStream inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
java.util.Properties properties = new Properties();
properties.load(inputStream);
return Integer.parseInt(properties.getProperty(s));
}

static int getGrpcServicePortNum() throws IOException {
return getIntPropertyValue("grpc-port");
}

static int getGrpcwebServicePortNum() throws IOException {
return getIntPropertyValue("grpc-web-port");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2020 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";

option java_package = "grpcweb.examples.greeter";

package grpcweb.examples.greeter;

// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
string name = 1;
}

// The response message containing the greetings
message HelloReply {
string message = 1;
}
Loading

0 comments on commit c470eaa

Please sign in to comment.