use of org.ballerinalang.net.grpc.ClientConnectorFactory in project ballerina by ballerina-lang.
the class InitStub method execute.
@Override
public void execute(Context context) {
BStruct serviceStub = (BStruct) context.getRefArgument(SERVICE_STUB_REF_INDEX);
BStruct clientEndpoint = (BStruct) context.getRefArgument(CLIENT_ENDPOINT_REF_INDEX);
ManagedChannel channel = (ManagedChannel) clientEndpoint.getNativeData(CHANNEL_KEY);
String stubtype = context.getStringArgument(STUB_TYPE_STRING_INDEX);
String descriptorKey = context.getStringArgument(DESCRIPTOR_KEY_STRING_INDEX);
BMap<String, BValue> descriptorMap = (BMap<String, BValue>) context.getRefArgument(DESCRIPTOR_MAP_REF_INDEX);
if (stubtype == null || descriptorKey == null || descriptorMap == null) {
context.setError(MessageUtils.getConnectorError(context, new StatusRuntimeException(Status.fromCode(Status.INTERNAL.getCode()).withDescription("Error while initializing connector. " + "message descriptor keys not exist. Please check the generated sub file"))));
return;
}
try {
// If there are more than one descriptors exist, other descriptors are considered as dependent
// descriptors. client supported only one depth descriptor dependency.
List<byte[]> depDescriptorData = new ArrayList<>();
byte[] descriptorValue = null;
for (String key : descriptorMap.keySet()) {
if (descriptorMap.get(key) == null) {
continue;
}
if (descriptorKey.equals(key)) {
descriptorValue = hexStringToByteArray(descriptorMap.get(key).stringValue());
} else {
depDescriptorData.add(hexStringToByteArray(descriptorMap.get(key).stringValue()));
}
}
if (descriptorValue == null) {
context.setError(MessageUtils.getConnectorError(context, new StatusRuntimeException(Status.fromCode(Status.INTERNAL.getCode()).withDescription("Error while establishing the connection" + ". service descriptor is null."))));
return;
}
ProtoFileDefinition protoFileDefinition = new ProtoFileDefinition(depDescriptorData);
protoFileDefinition.setRootDescriptorData(descriptorValue);
ClientConnectorFactory clientConnectorFactory = new ClientConnectorFactory(protoFileDefinition);
if (BLOCKING_TYPE.equalsIgnoreCase(stubtype)) {
GrpcBlockingStub grpcBlockingStub = clientConnectorFactory.newBlockingStub(channel);
serviceStub.addNativeData(SERVICE_STUB, grpcBlockingStub);
} else if (NON_BLOCKING_TYPE.equalsIgnoreCase(stubtype)) {
GrpcNonBlockingStub nonBlockingStub = clientConnectorFactory.newNonBlockingStub(channel);
serviceStub.addNativeData(SERVICE_STUB, nonBlockingStub);
} else {
context.setError(MessageUtils.getConnectorError(context, new StatusRuntimeException(Status.fromCode(Status.INTERNAL.getCode()).withDescription("Error while initializing connector. " + "invalid connector type"))));
return;
}
serviceStub.addNativeData(CLIENT_END_POINT, clientEndpoint);
} catch (RuntimeException | GrpcClientException e) {
context.setError(MessageUtils.getConnectorError(context, e));
}
}
Aggregations