Search in sources :

Example 6 with Resource

use of org.ballerinalang.connector.api.Resource in project ballerina by ballerina-lang.

the class GrpcServicesBuilder method getServiceDefinition.

private static ServerServiceDefinition getServiceDefinition(Service service, Descriptors.ServiceDescriptor serviceDescriptor) throws GrpcServerException {
    // Generate full service name for the service definition. <package>.<service>
    final String serviceName;
    if (ServiceProtoConstants.CLASSPATH_SYMBOL.equals(service.getPackage())) {
        serviceName = service.getName();
    } else {
        serviceName = service.getPackage() + ServiceProtoConstants.CLASSPATH_SYMBOL + service.getName();
    }
    // Server Definition Builder for the service.
    Builder serviceDefBuilder = ServerServiceDefinition.builder(serviceName);
    for (Descriptors.MethodDescriptor methodDescriptor : serviceDescriptor.getMethods()) {
        final String methodName = serviceName + FILE_SEPARATOR + methodDescriptor.getName();
        Descriptors.Descriptor requestDescriptor = serviceDescriptor.findMethodByName(methodDescriptor.getName()).getInputType();
        Descriptors.Descriptor responseDescriptor = serviceDescriptor.findMethodByName(methodDescriptor.getName()).getOutputType();
        MessageRegistry.getInstance().addMessageDescriptor(requestDescriptor.getName(), requestDescriptor);
        MessageRegistry.getInstance().addMessageDescriptor(responseDescriptor.getName(), responseDescriptor);
        MethodDescriptor.Marshaller<Message> reqMarshaller = ProtoUtils.marshaller(Message.newBuilder(requestDescriptor.getName()).build());
        MethodDescriptor.Marshaller<Message> resMarshaller = ProtoUtils.marshaller(Message.newBuilder(responseDescriptor.getName()).build());
        MethodDescriptor.MethodType methodType;
        ServerCallHandler<Message, Message> serverCallHandler;
        Map<String, Resource> resourceMap = new HashMap<>();
        Resource mappedResource = null;
        for (Resource resource : service.getResources()) {
            if (methodDescriptor.getName().equals(resource.getName())) {
                mappedResource = resource;
            }
            resourceMap.put(resource.getName(), resource);
        }
        if (methodDescriptor.toProto().getServerStreaming() && methodDescriptor.toProto().getClientStreaming()) {
            methodType = MethodDescriptor.MethodType.BIDI_STREAMING;
            serverCallHandler = ServerCalls.asyncBidiStreamingCall(new BidirectionalStreamingListener(methodDescriptor, resourceMap));
        } else if (methodDescriptor.toProto().getClientStreaming()) {
            methodType = MethodDescriptor.MethodType.CLIENT_STREAMING;
            serverCallHandler = ServerCalls.asyncClientStreamingCall(new ClientStreamingListener(methodDescriptor, resourceMap));
        } else if (methodDescriptor.toProto().getServerStreaming()) {
            methodType = MethodDescriptor.MethodType.SERVER_STREAMING;
            serverCallHandler = ServerCalls.asyncServerStreamingCall(new ServerStreamingListener(methodDescriptor, mappedResource));
        } else {
            methodType = MethodDescriptor.MethodType.UNARY;
            serverCallHandler = ServerCalls.asyncUnaryCall(new UnaryMethodListener(methodDescriptor, mappedResource));
        }
        MethodDescriptor.Builder<Message, Message> methodBuilder = MethodDescriptor.newBuilder();
        MethodDescriptor<Message, Message> grpcMethodDescriptor = methodBuilder.setType(methodType).setFullMethodName(methodName).setRequestMarshaller(reqMarshaller).setResponseMarshaller(resMarshaller).setSchemaDescriptor(methodDescriptor).build();
        serviceDefBuilder.addMethod(grpcMethodDescriptor, serverCallHandler);
    }
    return serviceDefBuilder.build();
}
Also used : HashMap(java.util.HashMap) UnaryMethodListener(org.ballerinalang.net.grpc.listener.UnaryMethodListener) NettyServerBuilder(io.grpc.netty.NettyServerBuilder) Builder(io.grpc.ServerServiceDefinition.Builder) Resource(org.ballerinalang.connector.api.Resource) MethodDescriptor(io.grpc.MethodDescriptor) ServerStreamingListener(org.ballerinalang.net.grpc.listener.ServerStreamingListener) ClientStreamingListener(org.ballerinalang.net.grpc.listener.ClientStreamingListener) Descriptors(com.google.protobuf.Descriptors) BidirectionalStreamingListener(org.ballerinalang.net.grpc.listener.BidirectionalStreamingListener)

Example 7 with Resource

use of org.ballerinalang.connector.api.Resource in project ballerina by ballerina-lang.

the class HttpService method buildHttpService.

public static HttpService buildHttpService(Service service) {
    HttpService httpService = new HttpService(service);
    Annotation serviceConfigAnnotation = getHttpServiceConfigAnnotation(service);
    if (serviceConfigAnnotation == null) {
        log.debug("serviceConfig not specified in the Service instance, using default base path");
        // service name cannot start with / hence concat
        httpService.setBasePath(HttpConstants.DEFAULT_BASE_PATH.concat(httpService.getName()));
    } else {
        Struct serviceConfig = serviceConfigAnnotation.getValue();
        httpService.setBasePath(serviceConfig.getStringField(BASE_PATH_FIELD));
        httpService.setCompression(serviceConfig.getEnumField(COMPRESSION_FIELD));
        httpService.setCorsHeaders(CorsHeaders.buildCorsHeaders(serviceConfig.getStructField(CORS_FIELD)));
        httpService.setWebSocketUpgradeConfig(serviceConfig.getStructField(WEBSOCKET_UPGRADE_FIELD));
    }
    List<HttpResource> resources = new ArrayList<>();
    for (Resource resource : httpService.getBallerinaService().getResources()) {
        HttpResource httpResource = HttpResource.buildHttpResource(resource, httpService);
        try {
            httpService.getUriTemplate().parse(httpResource.getPath(), httpResource, new HttpResourceElementFactory());
        } catch (URITemplateException | UnsupportedEncodingException e) {
            throw new BallerinaConnectorException(e.getMessage());
        }
        resources.add(httpResource);
    }
    httpService.setResources(resources);
    httpService.setAllAllowedMethods(DispatcherUtil.getAllResourceMethods(httpService));
    return httpService;
}
Also used : URITemplateException(org.ballerinalang.net.uri.URITemplateException) BallerinaConnectorException(org.ballerinalang.connector.api.BallerinaConnectorException) ArrayList(java.util.ArrayList) Resource(org.ballerinalang.connector.api.Resource) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Annotation(org.ballerinalang.connector.api.Annotation) Struct(org.ballerinalang.connector.api.Struct)

Example 8 with Resource

use of org.ballerinalang.connector.api.Resource 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 9 with Resource

use of org.ballerinalang.connector.api.Resource in project ballerina by ballerina-lang.

the class WebSubHttpService method buildWebSubSubscriberHttpService.

/**
 * Builds the HTTP service representation of the service.
 *
 * @param service   the service for which the HTTP representation is built
 * @return  the built HttpService representation
 */
static HttpService buildWebSubSubscriberHttpService(Service service) {
    WebSubHttpService httpService = new WebSubHttpService(service);
    Annotation serviceConfigAnnotation = getWebSubSubscriberServiceConfigAnnotation(service);
    if (serviceConfigAnnotation == null) {
        logger.debug("ServiceConfig not specified in the Service instance, using default base path");
        // service name cannot start with / hence concat
        httpService.setBasePath(HttpConstants.DEFAULT_BASE_PATH.concat(httpService.getName()));
        return httpService;
    }
    Struct serviceConfig = serviceConfigAnnotation.getValue();
    httpService.setBasePath(serviceConfig.getStringField(BASE_PATH_FIELD));
    List<HttpResource> resources = new ArrayList<>();
    for (Resource resource : httpService.getBallerinaService().getResources()) {
        HttpResource httpResource = WebSubHttpResource.buildWebSubHttpResource(resource, httpService);
        resources.add(httpResource);
    }
    httpService.setResources(resources);
    httpService.setAllAllowedMethods(DispatcherUtil.getAllResourceMethods(httpService));
    return httpService;
}
Also used : HttpResource(org.ballerinalang.net.http.HttpResource) ArrayList(java.util.ArrayList) HttpResource(org.ballerinalang.net.http.HttpResource) Resource(org.ballerinalang.connector.api.Resource) Annotation(org.ballerinalang.connector.api.Annotation) Struct(org.ballerinalang.connector.api.Struct)

Example 10 with Resource

use of org.ballerinalang.connector.api.Resource in project ballerina by ballerina-lang.

the class WebSocketUtil method handleHandshake.

public static void handleHandshake(WebSocketService wsService, HttpHeaders headers, BStruct wsConnection) {
    String[] subProtocols = wsService.getNegotiableSubProtocols();
    WebSocketInitMessage initMessage = (WebSocketInitMessage) wsConnection.getNativeData(WebSocketConstants.WEBSOCKET_MESSAGE);
    int idleTimeoutInSeconds = wsService.getIdleTimeoutInSeconds();
    HandshakeFuture future = initMessage.handshake(subProtocols, true, idleTimeoutInSeconds * 1000, headers);
    future.setHandshakeListener(new HandshakeListener() {

        @Override
        public void onSuccess(Session session) {
            BStruct serviceEndpoint = (BStruct) wsConnection.getNativeData(WebSocketConstants.WEBSOCKET_ENDPOINT);
            populateEndpoint(session, serviceEndpoint);
            wsConnection.addNativeData(WebSocketConstants.NATIVE_DATA_WEBSOCKET_SESSION, session);
            WebSocketOpenConnectionInfo connectionInfo = new WebSocketOpenConnectionInfo(wsService, serviceEndpoint);
            WebSocketConnectionManager.getInstance().addConnection(session.getId(), connectionInfo);
            Resource onOpenResource = wsService.getResourceByName(WebSocketConstants.RESOURCE_NAME_ON_OPEN);
            if (onOpenResource == null) {
                return;
            }
            List<ParamDetail> paramDetails = onOpenResource.getParamDetails();
            BValue[] bValues = new BValue[paramDetails.size()];
            bValues[0] = serviceEndpoint;
            // TODO handle BallerinaConnectorException
            Executor.submit(onOpenResource, new WebSocketEmptyCallableUnitCallback(), null, null, bValues);
        }

        @Override
        public void onError(Throwable throwable) {
            ErrorHandlerUtils.printError(throwable);
        }
    });
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) HandshakeFuture(org.wso2.transport.http.netty.contract.websocket.HandshakeFuture) HandshakeListener(org.wso2.transport.http.netty.contract.websocket.HandshakeListener) Resource(org.ballerinalang.connector.api.Resource) WebSocketInitMessage(org.wso2.transport.http.netty.contract.websocket.WebSocketInitMessage) List(java.util.List) Session(javax.websocket.Session)

Aggregations

Resource (org.ballerinalang.connector.api.Resource)16 ParamDetail (org.ballerinalang.connector.api.ParamDetail)12 BValue (org.ballerinalang.model.values.BValue)12 BStruct (org.ballerinalang.model.values.BStruct)10 CallableUnitCallback (org.ballerinalang.bre.bvm.CallableUnitCallback)6 GrpcCallableUnitCallBack (org.ballerinalang.net.grpc.GrpcCallableUnitCallBack)5 BString (org.ballerinalang.model.values.BString)4 BType (org.ballerinalang.model.types.BType)3 StreamObserver (io.grpc.stub.StreamObserver)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Annotation (org.ballerinalang.connector.api.Annotation)2 BallerinaConnectorException (org.ballerinalang.connector.api.BallerinaConnectorException)2 Struct (org.ballerinalang.connector.api.Struct)2 Message (org.ballerinalang.net.grpc.Message)2 Descriptors (com.google.protobuf.Descriptors)1 MethodDescriptor (io.grpc.MethodDescriptor)1 Builder (io.grpc.ServerServiceDefinition.Builder)1 NettyServerBuilder (io.grpc.netty.NettyServerBuilder)1