Search in sources :

Example 26 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project ballerina by ballerina-lang.

the class ErrorResponse method execute.

@Override
public void execute(Context context) {
    BStruct connectionStruct = (BStruct) context.getRefArgument(0);
    BValue responseValue = context.getRefArgument(1);
    if (responseValue instanceof BStruct) {
        BStruct responseStruct = (BStruct) responseValue;
        int statusCode = Integer.parseInt(String.valueOf(responseStruct.getIntField(0)));
        String errorMsg = responseStruct.getStringField(0);
        StreamObserver requestSender = (StreamObserver) connectionStruct.getNativeData(REQUEST_SENDER);
        if (requestSender == null) {
            context.setError(MessageUtils.getConnectorError(context, new StatusRuntimeException(Status.fromCode(Status.INTERNAL.getCode()).withDescription("Error while sending the error. Response" + " observer not found."))));
        } else {
            requestSender.onError(new StatusRuntimeException(Status.fromCodeValue(statusCode).withDescription(errorMsg)));
        }
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) BStruct(org.ballerinalang.model.values.BStruct) BValue(org.ballerinalang.model.values.BValue) StatusRuntimeException(io.grpc.StatusRuntimeException)

Example 27 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project ballerina by ballerina-lang.

the class ClientStreamingListener method invoke.

@Override
public StreamObserver<Message> invoke(StreamObserver<Message> responseObserver) {
    Resource onOpen = resourceMap.get(MessageConstants.ON_OPEN_RESOURCE);
    List<ParamDetail> paramDetails = onOpen.getParamDetails();
    BValue[] signatureParams = new BValue[paramDetails.size()];
    signatureParams[0] = getConnectionParameter(onOpen, responseObserver);
    CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, Boolean.FALSE);
    Executor.submit(onOpen, callback, null, null, signatureParams);
    return new StreamObserver<Message>() {

        @Override
        public void onNext(Message value) {
            Resource onMessage = resourceMap.get(MessageConstants.ON_MESSAGE_RESOURCE);
            List<ParamDetail> paramDetails = onMessage.getParamDetails();
            BValue[] signatureParams = new BValue[paramDetails.size()];
            signatureParams[0] = getConnectionParameter(onMessage, responseObserver);
            BValue requestParam = getRequestParameter(onMessage, value);
            if (requestParam != null) {
                signatureParams[1] = requestParam;
            }
            CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, Boolean.FALSE);
            Executor.submit(onMessage, callback, null, null, signatureParams);
        }

        @Override
        public void onError(Throwable t) {
            Resource onError = resourceMap.get(MessageConstants.ON_ERROR_RESOURCE);
            if (onError == null) {
                String message = "Error in listener service definition. onError resource does not exists";
                LOG.error(message);
                throw new RuntimeException(message);
            }
            List<ParamDetail> paramDetails = onError.getParamDetails();
            BValue[] signatureParams = new BValue[paramDetails.size()];
            signatureParams[0] = getConnectionParameter(onError, responseObserver);
            if (paramDetails.size() != 2) {
                String message = "Error in onError resource definition. It must have two input params, but have " + paramDetails.size();
                LOG.error(message);
                throw new RuntimeException(message);
            }
            BType errorType = paramDetails.get(1).getVarType();
            BStruct errorStruct = MessageUtils.getConnectorError((BStructType) errorType, t);
            signatureParams[1] = errorStruct;
            CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, Boolean.FALSE);
            Executor.submit(onError, callback, null, null, signatureParams);
        }

        @Override
        public void onCompleted() {
            Resource onCompleted = resourceMap.get(MessageConstants.ON_COMPLETE_RESOURCE);
            if (onCompleted == null) {
                String message = "Error in listener service definition. onError resource does not exists";
                LOG.error(message);
                throw new RuntimeException(message);
            }
            List<ParamDetail> paramDetails = onCompleted.getParamDetails();
            BValue[] signatureParams = new BValue[paramDetails.size()];
            signatureParams[0] = getConnectionParameter(onCompleted, responseObserver);
            CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, isEmptyResponse());
            Executor.submit(onCompleted, callback, null, null, signatureParams);
        }
    };
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) GrpcCallableUnitCallBack(org.ballerinalang.net.grpc.GrpcCallableUnitCallBack) BStruct(org.ballerinalang.model.values.BStruct) Message(org.ballerinalang.net.grpc.Message) BValue(org.ballerinalang.model.values.BValue) Resource(org.ballerinalang.connector.api.Resource) ParamDetail(org.ballerinalang.connector.api.ParamDetail) BType(org.ballerinalang.model.types.BType) CallableUnitCallback(org.ballerinalang.bre.bvm.CallableUnitCallback)

Example 28 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project motan by weibocom.

the class MotanServerCallHandler method streamCall.

@SuppressWarnings("unchecked")
private <ReqT, RespT> Listener<ReqT> streamCall(final ServerCall<ReqT, RespT> call, Metadata headers) {
    final ServerCallStreamObserverImpl<ReqT, RespT> responseObserver = new ServerCallStreamObserverImpl<ReqT, RespT>(call);
    DefaultRequest request = getBaseMotanRequest(headers);
    request.setArguments(new Object[] { responseObserver });
    Response response = provider.call(request);
    final StreamObserver<ReqT> requestObserver = (StreamObserver<ReqT>) response.getValue();
    responseObserver.freeze();
    if (responseObserver.autoFlowControlEnabled) {
        call.request(1);
    }
    return new ServerCall.Listener<ReqT>() {

        boolean halfClosed = false;

        @Override
        public void onMessage(ReqT request) {
            requestObserver.onNext(request);
            if (responseObserver.autoFlowControlEnabled) {
                call.request(1);
            }
        }

        @Override
        public void onHalfClose() {
            halfClosed = true;
            requestObserver.onCompleted();
        }

        @Override
        public void onCancel() {
            responseObserver.cancelled = true;
            if (responseObserver.onCancelHandler != null) {
                responseObserver.onCancelHandler.run();
            }
            if (!halfClosed) {
                requestObserver.onError(Status.CANCELLED.asException());
            }
        }

        @Override
        public void onReady() {
            if (responseObserver.onReadyHandler != null) {
                responseObserver.onReadyHandler.run();
            }
        }
    };
}
Also used : Response(com.weibo.api.motan.rpc.Response) StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Listener(io.grpc.ServerCall.Listener) DefaultRequest(com.weibo.api.motan.rpc.DefaultRequest)

Example 29 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project motan by weibocom.

the class GrpcServerDemo method routeChat.

/**
 * Receives a stream of message/location pairs, and responds with a stream of all previous
 * messages at each of those locations.
 *
 * @param responseObserver an observer to receive the stream of previous messages.
 * @return an observer to handle requested message/location pairs.
 */
public StreamObserver<RouteNote> routeChat(final StreamObserver<RouteNote> responseObserver) {
    return new StreamObserver<RouteNote>() {

        public void onNext(RouteNote note) {
            List<RouteNote> notes = getOrCreateNotes(note.getLocation());
            // Respond with all previous notes at this location.
            for (RouteNote prevNote : notes.toArray(new RouteNote[0])) {
                responseObserver.onNext(prevNote);
            }
            // Now add the new note to the list
            notes.add(note);
        }

        public void onError(Throwable t) {
        }

        public void onCompleted() {
            responseObserver.onCompleted();
        }
    };
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) RouteNote(io.grpc.examples.routeguide.RouteNote)

Example 30 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project motan by weibocom.

the class GrpcClientDemo method main.

public static void main(String[] args) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "classpath:motan_demo_client_grpc.xml" });
    GrpcService service = (GrpcService) ctx.getBean("motanDemoReferer");
    // unary
    for (int i = 0; i < 2; i++) {
        Point request = Point.newBuilder().setLatitude(100 + i).setLongitude(150 + i).build();
        System.out.println(service.getFeature(request));
        Thread.sleep(1000);
    }
    // server streaming
    Rectangle request = Rectangle.newBuilder().setLo(Point.newBuilder().setLatitude(400000000).setLongitude(-750000000).build()).setHi(Point.newBuilder().setLatitude(420000000).setLongitude(-730000000).build()).build();
    StreamObserver<Feature> responseObserver = new StreamObserver<Feature>() {

        @Override
        public void onNext(Feature value) {
            System.out.println(value);
        }

        @Override
        public void onError(Throwable t) {
        // TODO Auto-generated method stub
        }

        @Override
        public void onCompleted() {
            System.out.println("response complete!");
        }
    };
    service.listFeatures(request, responseObserver);
    Thread.sleep(2000);
    // client streaming
    StreamObserver<RouteSummary> routeSummaryObserver = new StreamObserver<RouteSummary>() {

        @Override
        public void onNext(RouteSummary value) {
            System.out.println(value);
        }

        @Override
        public void onError(Throwable t) {
        // TODO Auto-generated method stub
        }

        @Override
        public void onCompleted() {
            System.out.println("response complete!");
        }
    };
    StreamObserver<Point> requestObserver = service.recordRoute(routeSummaryObserver);
    Random random = new Random();
    for (int i = 0; i < 5; i++) {
        Point point = Point.newBuilder().setLatitude(random.nextInt()).setLongitude(random.nextInt()).build();
        requestObserver.onNext(point);
        Thread.sleep(200);
    }
    requestObserver.onCompleted();
    Thread.sleep(2000);
    // biderict-streaming
    StreamObserver<RouteNote> biRequestObserver = service.routeChat(new StreamObserver<RouteNote>() {

        public void onNext(RouteNote value) {
            System.out.println(value);
        }

        public void onError(Throwable t) {
            t.printStackTrace();
        }

        public void onCompleted() {
            System.out.println("routenote complete");
        }
    });
    try {
        RouteNote[] requests = { newNote("First message", 0, 0), newNote("Second message", 0, 1), newNote("Third message", 1, 0), newNote("Fourth message", 1, 1) };
        for (RouteNote note : requests) {
            biRequestObserver.onNext(note);
        }
    } catch (RuntimeException e) {
        biRequestObserver.onError(e);
        throw e;
    }
    biRequestObserver.onCompleted();
    Thread.sleep(2000);
    System.out.println("motan demo is finish.");
    System.exit(0);
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) RouteSummary(io.grpc.examples.routeguide.RouteSummary) Rectangle(io.grpc.examples.routeguide.Rectangle) Point(io.grpc.examples.routeguide.Point) Feature(io.grpc.examples.routeguide.Feature) Point(io.grpc.examples.routeguide.Point) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) GrpcService(com.weibo.motan.demo.service.GrpcService) Random(java.util.Random) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) RouteNote(io.grpc.examples.routeguide.RouteNote)

Aggregations

StreamObserver (io.grpc.stub.StreamObserver)130 Test (org.junit.Test)93 CountDownLatch (java.util.concurrent.CountDownLatch)50 ArrayList (java.util.ArrayList)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)38 StreamObserver (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver)27 StatusRuntimeException (io.grpc.StatusRuntimeException)26 Status (io.grpc.Status)20 List (java.util.List)18 BeamFnApi (org.apache.beam.model.fnexecution.v1.BeamFnApi)18 ManagedChannel (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel)18 CompletableFuture (java.util.concurrent.CompletableFuture)17 ExecutorService (java.util.concurrent.ExecutorService)16 SegmentId (io.pravega.controller.stream.api.grpc.v1.Controller.SegmentId)14 ServerRequest (io.pravega.controller.stream.api.grpc.v1.Controller.ServerRequest)14 VisibleForTesting (com.google.common.annotations.VisibleForTesting)12 Strings (com.google.common.base.Strings)12 Throwables (com.google.common.base.Throwables)12 ImmutableMap (com.google.common.collect.ImmutableMap)12 AuthHandler (io.pravega.auth.AuthHandler)12