Task 2 - errors handler

This commit is contained in:
Rémi Heredero 2023-11-08 09:56:05 +01:00
parent 0e1947feef
commit 5fb6c3d0cc

View File

@ -2,24 +2,42 @@ import ch.sdi.calc.CalculatorGrpc;
import ch.sdi.calc.CalculatorOuterClass;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CalculatorClient {
private ManagedChannel channel;
private final CalculatorGrpc.CalculatorBlockingStub blockingStub;
private CalculatorGrpc.CalculatorBlockingStub blockingStub = null;
private static final Logger logger = Logger.getLogger(CalculatorClient.class.getName());
public CalculatorClient(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port).usePlaintext());
}
private CalculatorClient(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.build();
try {
channel = channelBuilder.build();
} catch (Exception e) {
logger.log(Level.WARNING, "Could not connect to server: {0}", e.getMessage());
return;
}
blockingStub = CalculatorGrpc.newBlockingStub(channel);
}
public double calculate(String expression) {
logger.info("Trying to do: " + expression + " ..." );
CalculatorOuterClass.CalculatorRequest request = CalculatorOuterClass.CalculatorRequest.newBuilder().setExpression(expression).build();
CalculatorOuterClass.CalculatorResponse response;
response = blockingStub.calculate(request);
CalculatorOuterClass.CalculatorResponse response = null;
try {
response = blockingStub.calculate(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return 0;
}
logger.info("Answer: " + response.getResult());
return response.getResult();
}
@ -32,5 +50,10 @@ public class CalculatorClient {
double answer = client.calculate(expression);
System.out.println("Answer: " + answer);
}
String expression = "1-a";
System.out.println("Expression: " + expression);
double answer = client.calculate(expression);
System.out.println("Answer: " + answer);
}
}