Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package server;
- import java.util.HashMap;
- import java.util.Map;
- import io.grpc.Status;
- import io.grpc.stub.StreamObserver;
- import proto.UserOuterClass.CreateUserRequest;
- import proto.UserOuterClass.CreateUserResponse;
- import proto.UserOuterClass.DeleteUserRequest;
- import proto.UserOuterClass.DeleteUserResponse;
- import proto.UserOuterClass.GetUserRequest;
- import proto.UserOuterClass.GetUserResponse;
- import proto.UserOuterClass.ListUserRequest;
- import proto.UserOuterClass.ListUserResponse;
- import proto.UserOuterClass.User;
- import proto.UserServiceGrpc;
- public class Service extends UserServiceGrpc.UserServiceImplBase {
- private Map<Integer, User> userMap = new HashMap<Integer, User>();
- private int i = 1;
- @Override
- public void createUser(CreateUserRequest request, StreamObserver<CreateUserResponse> responseObserver) {
- System.out.println("Creating User");
- User user = request.getUser();
- user = user.toBuilder().setId(i).setName(request.getUser().getName()).setEmail(request.getUser().getEmail())
- .build();
- CreateUserResponse response = CreateUserResponse.newBuilder().setUser(user).build();
- responseObserver.onNext(response);
- responseObserver.onCompleted();
- userMap.put(i, user);
- i++;
- }
- @Override
- public void deleteUser(DeleteUserRequest request, StreamObserver<DeleteUserResponse> responseObserver) {
- if (userMap.containsKey(request.getUserId())) {
- userMap.remove(request.getUserId());
- System.out.println("User was deleted");
- responseObserver.onNext(DeleteUserResponse.newBuilder().setUserId(request.getUserId()).build());
- responseObserver.onCompleted();
- } else {
- System.out.println("User not found");
- responseObserver.onError(Status.NOT_FOUND.asRuntimeException());
- }
- }
- @Override
- public void getUser(GetUserRequest request, StreamObserver<GetUserResponse> responseObserver) {
- System.out.println("Get user");
- if (userMap.containsKey(request.getUserId())) {
- User user = userMap.get(request.getUserId());
- GetUserResponse response = GetUserResponse.newBuilder().setUser(user).build();
- responseObserver.onNext(response);
- responseObserver.onCompleted();
- } else {
- System.out.println("User not found");
- responseObserver.onError(Status.NOT_FOUND.asRuntimeException());
- }
- }
- @Override
- public void listUser(ListUserRequest request, StreamObserver<ListUserResponse> responseObserver) {
- System.out.println("List users");
- ListUserResponse response = ListUserResponse.newBuilder().addAllUser(userMap.values()).build();
- responseObserver.onNext(response);
- responseObserver.onCompleted();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement