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();
}
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;
}
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);
}
};
}
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;
}
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);
}
});
}
Aggregations