1 /* 2 * Copyright 2020 The gRPC Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package io.grpc.examples.hostname; 18 19 import io.grpc.examples.helloworld.GreeterGrpc; 20 import io.grpc.examples.helloworld.HelloReply; 21 import io.grpc.examples.helloworld.HelloRequest; 22 import io.grpc.stub.StreamObserver; 23 import java.io.IOException; 24 import java.net.InetAddress; 25 import java.util.Random; 26 import java.util.logging.Level; 27 import java.util.logging.Logger; 28 29 /** Greeter implementation which replies identifying itself with its hostname. */ 30 public final class HostnameGreeter extends GreeterGrpc.GreeterImplBase { 31 private static final Logger logger = Logger.getLogger(HostnameGreeter.class.getName()); 32 33 private final String serverName; 34 HostnameGreeter(String serverName)35 public HostnameGreeter(String serverName) { 36 if (serverName == null) { 37 serverName = determineHostname(); 38 } 39 this.serverName = serverName; 40 } 41 42 @Override sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver)43 public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { 44 HelloReply reply = HelloReply.newBuilder() 45 .setMessage("Hello " + req.getName() + ", from " + serverName) 46 .build(); 47 responseObserver.onNext(reply); 48 responseObserver.onCompleted(); 49 } 50 determineHostname()51 private static String determineHostname() { 52 try { 53 return InetAddress.getLocalHost().getHostName(); 54 } catch (IOException ex) { 55 logger.log(Level.INFO, "Failed to determine hostname. Will generate one", ex); 56 } 57 // Strange. Well, let's make an identifier for ourselves. 58 return "generated-" + new Random().nextInt(); 59 } 60 } 61