use of com.google.api.gax.rpc.BidiStream in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composeStreamBidiSample.
private static Sample composeStreamBidiSample(Method method, VariableExpr clientVarExpr, AssignmentExpr requestAssignmentExpr) {
List<Expr> bodyExprs = new ArrayList<>();
// Create bidi stream variable expression and assign it with invoking client's bidi stream
// method.
// e.g. BidiStream<EchoRequest, EchoResponse> bidiStream = echoClient.chatCallable().call();
TypeNode bidiStreamType = TypeNode.withReference(ConcreteReference.builder().setClazz(BidiStream.class).setGenerics(method.inputType().reference(), method.outputType().reference()).build());
VariableExpr bidiStreamVarExpr = VariableExpr.withVariable(Variable.builder().setName("bidiStream").setType(bidiStreamType).build());
MethodInvocationExpr clientBidiStreamCallMethodInvoationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(String.format("%sCallable", method.name()))).build();
clientBidiStreamCallMethodInvoationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientBidiStreamCallMethodInvoationExpr).setMethodName("call").setReturnType(bidiStreamType).build();
AssignmentExpr bidiStreamAssignmentExpr = AssignmentExpr.builder().setVariableExpr(bidiStreamVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(clientBidiStreamCallMethodInvoationExpr).build();
bodyExprs.add(bidiStreamAssignmentExpr);
// Add request with default value expression.
bodyExprs.add(requestAssignmentExpr);
// Invoke send method with argument request.
// e.g. bidiStream.send(request);
MethodInvocationExpr sendMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(bidiStreamVarExpr).setArguments(requestAssignmentExpr.variableExpr().toBuilder().setIsDecl(false).build()).setMethodName("send").build();
bodyExprs.add(sendMethodInvocationExpr);
List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
// For-loop on bidi stream variable.
// e.g. for (EchoResponse response : bidiStream) {
// // Do something when reveive a response.
// }
ForStatement forStatement = ForStatement.builder().setLocalVariableExpr(VariableExpr.builder().setVariable(Variable.builder().setType(method.outputType()).setName("response").build()).setIsDecl(true).build()).setCollectionExpr(bidiStreamVarExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("Do something when a response is received.")))).build();
bodyStatements.add(forStatement);
RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setIsAsynchronous(true).build();
return Sample.builder().setBody(bodyStatements).setRegionTag(regionTag).build();
}
Aggregations