Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[composer][5/5]Implement default unary rpc method's sample code #515

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@

import com.google.api.generator.engine.ast.AssignmentExpr;
import com.google.api.generator.engine.ast.CommentStatement;
import com.google.api.generator.engine.ast.ConcreteReference;
import com.google.api.generator.engine.ast.Expr;
import com.google.api.generator.engine.ast.ExprStatement;
import com.google.api.generator.engine.ast.ForStatement;
import com.google.api.generator.engine.ast.LineComment;
import com.google.api.generator.engine.ast.MethodInvocationExpr;
import com.google.api.generator.engine.ast.Statement;
Expand All @@ -30,14 +30,16 @@
import com.google.api.generator.gapic.model.MethodArgument;
import com.google.api.generator.gapic.model.ResourceName;
import com.google.api.generator.gapic.utils.JavaStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public final class SampleCodeHelperComposer {
private static String RESPONSE_VAR_NAME = "response";
private static String REQUEST_VAR_NAME = "request";
private static String ASYNC_NAME_PATTERN = "%sAsync";

public static TryCatchStatement composeRpcMethodSampleCode(
Method method,
Expand All @@ -46,15 +48,15 @@ public static TryCatchStatement composeRpcMethodSampleCode(
Map<String, ResourceName> resourceNames) {
// Default Unary RPC method.
if (arguments.isEmpty()) {
return composeUnaryRpcDefaultMethodSampleCode(method, clientType);
return composeUnaryRpcDefaultMethodSampleCode(method, clientType, resourceNames);
}
// Paged Unary RPC method.
if (method.isPaged()) {
return composePagedUnaryRpcMethodSampleCode(method, arguments, clientType);
return composePagedUnaryRpcMethodSampleCode(method, arguments, clientType, resourceNames);
}
// Long run operation Unary RPC method.
if (method.hasLro()) {
return composeLroUnaryRpcMethodSampleCode(method, arguments, clientType);
return composeLroUnaryRpcMethodSampleCode(method, arguments, clientType, resourceNames);
}
// Pure Unary RPC method.
return composeUnaryRpcMethodSampleCode(method, arguments, clientType, resourceNames);
Expand Down Expand Up @@ -101,46 +103,150 @@ private static TryCatchStatement composeUnaryRpcMethodSampleCode(
}

private static TryCatchStatement composeLroUnaryRpcMethodSampleCode(
Method method, List<MethodArgument> arguments, TypeNode clientType) {
Method method,
List<MethodArgument> arguments,
TypeNode clientType,
Map<String, ResourceName> resourceNames) {
// TODO(summerji): compose sample code for unary lro rpc method.
// TODO(summerji): Add unit tests.
// Assign each method arguments with default value.
List<Statement> bodyStatements =
arguments.stream()
.map(
methodArg ->
ExprStatement.withExpr(
assignMethodArgumentWithDefaultValue(methodArg, resourceNames)))
.collect(Collectors.toList());
// Assign response variable with get method.
// e.g EchoResponse response = echoClient.waitAsync().get();
Expr getResponseMethodExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(
MethodInvocationExpr.builder()
.setExprReferenceExpr(createVariableExpr(getClientName(clientType), clientType))
.setMethodName(getLroMethodName(method.name()))
.setArguments(mapMethodArgumentsToVariableExprs(arguments))
.build())
.setMethodName("get")
.setReturnType(method.outputType())
.build();
bodyStatements.add(
ExprStatement.withExpr(
AssignmentExpr.builder()
.setVariableExpr(createVariableDeclExpr(RESPONSE_VAR_NAME, method.outputType()))
.setValueExpr(getResponseMethodExpr)
.build()));
return TryCatchStatement.builder()
.setTryResourceExpr(assignClientVariableWithCreateMethodExpr(clientType))
.setTryBody(
Arrays.asList(
createLineCommentStatement(
"Note: Not Implement yet, placeholder for lro Unary rpc method sample code.")))
.setTryBody(bodyStatements)
.setIsSampleCode(true)
.build();
}

private static TryCatchStatement composePagedUnaryRpcMethodSampleCode(
Method method, List<MethodArgument> arguments, TypeNode clientType) {
// TODO(summerji): compose sample code for unary paged rpc method.
// TODO(summerji): Add unit tests.
Method method,
List<MethodArgument> arguments,
TypeNode clientType,
Map<String, ResourceName> resourceNames) {
// TODO(summerji): Add unit test.
// Assign each method arguments with default value.
List<Statement> bodyStatements =
arguments.stream()
.map(
methodArg ->
ExprStatement.withExpr(
assignMethodArgumentWithDefaultValue(methodArg, resourceNames)))
.collect(Collectors.toList());
// For loop client on iterateAll method.
// e.g. for (LoggingServiceV2Client loggingServiceV2Client :
// loggingServiceV2Client.ListLogs(parent).iterateAll()) {
// //doThingsWith(element);}
bodyStatements.add(
ForStatement.builder()
.setLocalVariableExpr(createVariableDeclExpr(getClientName(clientType), clientType))
.setCollectionExpr(createIteratorAllMethodExpr(method, clientType, arguments))
.setBody(Arrays.asList(createLineCommentStatement("doThingsWith(element);")))
.build());
return TryCatchStatement.builder()
.setTryResourceExpr(assignClientVariableWithCreateMethodExpr(clientType))
.setTryBody(
Arrays.asList(
createLineCommentStatement(
"Note: Not Implement yet, placeholder for paged unary rpc method sample code.")))
.setTryBody(bodyStatements)
.setIsSampleCode(true)
.build();
}

private static TryCatchStatement composeUnaryRpcDefaultMethodSampleCode(
Method method, TypeNode clientType) {
Method method, TypeNode clientType, Map<String, ResourceName> resourceNames) {
// TODO(summerji): compose sample code for unary default rpc method.
// TODO(summerji): Add unit tests.
String content =
String.format(
"Note: Not Implement yet, placeholder for unary %s rpc method sample code.",
(!method.hasLro() && !method.isPaged()
? "default"
: (method.hasLro() ? "lro default" : "paged default")));
// If variant method signatures exists, use the first one.
List<MethodArgument> arguments =
!method.methodSignatures().isEmpty()
? method.methodSignatures().get(0)
: Collections.emptyList();
// Assign each method arguments with default value.
List<Statement> bodyStatements =
arguments.stream()
.map(
methodArg ->
ExprStatement.withExpr(
assignMethodArgumentWithDefaultValue(methodArg, resourceNames)))
.collect(Collectors.toList());
// Assign request variables with set argument attributes.
// e.g EchoRequest
bodyStatements.add(
ExprStatement.withExpr(createRequestBuilderExpr(method.inputType(), arguments)));

if (method.isPaged()) {
// For loop on invoke client method's iterator with comment.
// e.g. for (EchoClient echoClient : echoClient.PagedExpand(request).iterateAll()) {//..}
bodyStatements.add(
ForStatement.builder()
.setLocalVariableExpr(createVariableDeclExpr(getClientName(clientType), clientType))
.setCollectionExpr(createIteratorAllMethodExpr(method, clientType, arguments))
.setBody(Arrays.asList(createLineCommentStatement("doThingsWith(element);")))
.build());
} else if (method.hasLro()) {
// Create response variable by invoke client's async method.
// e.g Operation response = EchoClient.waitAsync(request).get();
Expr getResponseMethodExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(
MethodInvocationExpr.builder()
.setStaticReferenceType(clientType)
.setMethodName(getLroMethodName(method.name()))
.setArguments(
Arrays.asList(createVariableExpr(REQUEST_VAR_NAME, method.inputType())))
.build())
.setMethodName("get")
.setReturnType(method.outputType())
.build();
bodyStatements.add(
ExprStatement.withExpr(
AssignmentExpr.builder()
.setVariableExpr(createVariableDeclExpr(RESPONSE_VAR_NAME, method.outputType()))
.setValueExpr(getResponseMethodExpr)
.build()));
} else {
// Create response variable by invoke client's method by passing request.
// e.g. EchoResponse response = echoClient.Echo(request);
Expr invokeMethodExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(createVariableExpr(getClientName(clientType), clientType))
.setMethodName(method.name())
.setArguments(createVariableExpr("request", method.inputType()))
.setReturnType(method.outputType())
.build();
bodyStatements.add(
ExprStatement.withExpr(
AssignmentExpr.builder()
.setVariableExpr(createVariableDeclExpr(RESPONSE_VAR_NAME, method.outputType()))
.setValueExpr(invokeMethodExpr)
.build()));
}

return TryCatchStatement.builder()
.setTryResourceExpr(assignClientVariableWithCreateMethodExpr(clientType))
.setTryBody(Arrays.asList(createLineCommentStatement(content)))
.setTryBody(bodyStatements)
.setIsSampleCode(true)
.build();
}
Expand All @@ -161,6 +267,37 @@ private static AssignmentExpr assignClientVariableWithCreateMethodExpr(TypeNode
.build();
}

// Create request variable by set attributes.
// e.g. EchoRequest request = EchoRequest.newBuilder().setParent(parent).build();
private static Expr createRequestBuilderExpr(
TypeNode requestType, List<MethodArgument> arguments) {
MethodInvocationExpr newBuilderExpr =
MethodInvocationExpr.builder()
.setStaticReferenceType(requestType)
.setMethodName("newBuilder")
.build();
for (MethodArgument arg : arguments) {
newBuilderExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(newBuilderExpr)
.setMethodName(String.format("set%s", JavaStyle.toUpperCamelCase(arg.name())))
.setArguments(
VariableExpr.withVariable(
Variable.builder().setName(arg.name()).setType(arg.type()).build()))
.build();
}
MethodInvocationExpr requestBuildExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(newBuilderExpr)
.setMethodName("build")
.setReturnType(requestType)
.build();
return AssignmentExpr.builder()
.setVariableExpr(createVariableDeclExpr("request", requestType))
.setValueExpr(requestBuildExpr)
.build();
}

private static Expr assignMethodArgumentWithDefaultValue(
MethodArgument argument, Map<String, ResourceName> resourceNames) {
return AssignmentExpr.builder()
Expand Down Expand Up @@ -190,14 +327,37 @@ private static Expr createAssignExprForVariableWithClientMethod(
}

private static List<Expr> mapMethodArgumentsToVariableExprs(List<MethodArgument> arguments) {
return arguments.stream().map(arg -> createVariableExpr(arg.name(), arg.type())).collect(
Collectors.toList());
return arguments.stream()
.map(arg -> createVariableExpr(arg.name(), arg.type()))
.collect(Collectors.toList());
}

private static Expr createIteratorAllMethodExpr(
Method method, TypeNode clientType, List<MethodArgument> arguments) {
// e.g echoClient.echo(name).iterateAll()
return MethodInvocationExpr.builder()
.setExprReferenceExpr(
MethodInvocationExpr.builder()
.setExprReferenceExpr(createVariableExpr(getClientName(clientType), clientType))
.setMethodName(method.name())
.setArguments(
!arguments.isEmpty()
? mapMethodArgumentsToVariableExprs(arguments)
: Arrays.asList(createVariableExpr("request", method.inputType())))
.build())
.setMethodName("iterateAll")
.setReturnType(clientType)
.build();
}

private static String getClientName(TypeNode clientType) {
return JavaStyle.toLowerCamelCase(clientType.reference().name());
}

private static String getLroMethodName(String methodName) {
return JavaStyle.toLowerCamelCase(String.format(ASYNC_NAME_PATTERN, methodName));
}

private static CommentStatement createLineCommentStatement(String content) {
return CommentStatement.withComment(LineComment.withComment(content));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

public class ServiceClientSampleCodeComposer {
// TODO(summerji): Add unit tests for ServiceClientSampleCodeComposer.
// TODO(summerji): Refactor signatures as sample code context.

public static String composeClassHeaderCredentialsSampleCode(
TypeNode clientType, TypeNode settingsType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,9 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not Implement yet, placeholder for unary default rpc method sample code.
* ResourceName parent = FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]");
* EchoRequest request = EchoRequest.newBuilder().setParent(parent).build();
* EchoResponse response = echoClient.Echo(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -334,7 +336,10 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not Implement yet, placeholder for unary paged default rpc method sample code.
* PagedExpandRequest request = PagedExpandRequest.newBuilder().build();
* for (EchoClient echoClient : echoClient.PagedExpand(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
Expand Down Expand Up @@ -364,7 +369,8 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not Implement yet, placeholder for lro Unary rpc method sample code.
* Duration ttl = Duration.newBuilder().build();
* Operation response = echoClient.waitAsync(ttl).get();
* }
* }</pre>
*
Expand All @@ -382,7 +388,8 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not Implement yet, placeholder for lro Unary rpc method sample code.
* Timestamp end_time = Timestamp.newBuilder().build();
* Operation response = echoClient.waitAsync(end_time).get();
* }
* }</pre>
*
Expand All @@ -400,7 +407,9 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not Implement yet, placeholder for unary lro default rpc method sample code.
* Duration ttl = Duration.newBuilder().build();
* WaitRequest request = WaitRequest.newBuilder().setTtl(ttl).build();
* Operation response = EchoClient.waitAsync(request).get();
* }
* }</pre>
*
Expand Down Expand Up @@ -429,7 +438,8 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not Implement yet, placeholder for unary default rpc method sample code.
* BlockRequest request = BlockRequest.newBuilder().build();
* BlockResponse response = echoClient.Block(request);
* }
* }</pre>
*
Expand Down
Loading