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

[samplecode] Implement rpc default method sample code #594

Merged
merged 5 commits into from
Dec 17, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -479,13 +479,14 @@ private static List<MethodDefinition> createServiceMethods(
Map<String, Message> messageTypes,
Map<String, TypeNode> types,
Map<String, ResourceName> resourceNames) {
String clientName = getClientClassName(service);
List<MethodDefinition> javaMethods = new ArrayList<>();
for (Method method : service.methods()) {
if (method.stream().equals(Stream.NONE)) {
javaMethods.addAll(
createMethodVariants(
method, getClientClassName(service), messageTypes, types, resourceNames));
javaMethods.add(createMethodDefaultMethod(method, types));
createMethodVariants(method, clientName, messageTypes, types, resourceNames));
javaMethods.add(
createMethodDefaultMethod(method, clientName, messageTypes, types, resourceNames));
}
if (method.hasLro()) {
javaMethods.add(createLroCallableMethod(service, method, types));
Expand Down Expand Up @@ -594,7 +595,11 @@ private static List<MethodDefinition> createMethodVariants(
}

private static MethodDefinition createMethodDefaultMethod(
Method method, Map<String, TypeNode> types) {
Method method,
String clientName,
Map<String, Message> messageTypes,
Map<String, TypeNode> types,
Map<String, ResourceName> resourceNames) {
String methodName = JavaStyle.toLowerCamelCase(method.name());
TypeNode methodInputType = method.inputType();
TypeNode methodOutputType =
Expand Down Expand Up @@ -627,6 +632,11 @@ private static MethodDefinition createMethodDefaultMethod(
callableMethodName = String.format(OPERATION_CALLABLE_NAME_PATTERN, methodName);
}

Optional<String> defaultMethodSampleCode =
Optional.of(
ServiceClientSampleCodeComposer.composeRpcDefaultMethodHeaderSampleCode(
method, types.get(clientName), resourceNames, messageTypes));

MethodInvocationExpr callableMethodExpr =
MethodInvocationExpr.builder().setMethodName(callableMethodName).build();
callableMethodExpr =
Expand All @@ -639,7 +649,8 @@ private static MethodDefinition createMethodDefaultMethod(
MethodDefinition.Builder methodBuilder =
MethodDefinition.builder()
.setHeaderCommentStatements(
ServiceClientCommentComposer.createRpcMethodHeaderComment(method))
ServiceClientCommentComposer.createRpcMethodHeaderComment(
method, defaultMethodSampleCode))
.setScope(ScopeNode.PUBLIC)
.setIsFinal(true)
.setName(String.format(method.hasLro() ? "%sAsync" : "%s", methodName))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,9 @@ static List<CommentStatement> createRpcMethodHeaderComment(
return comments;
}

static List<CommentStatement> createRpcMethodHeaderComment(Method method) {
// TODO(summerji): Refactor this method when implement default method sample code.
return createRpcMethodHeaderComment(method, Collections.emptyList(), Optional.empty());
static List<CommentStatement> createRpcMethodHeaderComment(
Method method, Optional<String> sampleCode) {
return createRpcMethodHeaderComment(method, Collections.emptyList(), sampleCode);
}

static CommentStatement createMethodNoArgComment(String serviceName) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import com.google.api.generator.gapic.utils.JavaStyle;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -194,7 +195,6 @@ public static String composeRpcMethodHeaderSampleCode(
List<MethodArgument> arguments,
Map<String, ResourceName> resourceNames,
Map<String, Message> messageTypes) {
// TODO(summerji): Add other types RPC methods' sample code.
if (method.isPaged()) {
// Find the repeated field.
Message methodOutputMessage = messageTypes.get(method.outputType().reference().simpleName());
Expand All @@ -218,6 +218,120 @@ public static String composeRpcMethodHeaderSampleCode(
composeUnaryRpcMethodSampleCode(method, clientType, arguments, resourceNames));
}

public static String composeRpcDefaultMethodHeaderSampleCode(
Method method,
TypeNode clientType,
Map<String, ResourceName> resourceNames,
Map<String, Message> messageTypes) {
VariableExpr clientVarExpr =
VariableExpr.withVariable(
Variable.builder()
.setName(JavaStyle.toLowerCamelCase(clientType.reference().name()))
.setType(clientType)
.build());
// Assign method's request variable with the default value.
VariableExpr requestVarExpr =
VariableExpr.withVariable(
Variable.builder().setName("request").setType(method.inputType()).build());
Message requestMessage = messageTypes.get(method.inputType().reference().simpleName());
Preconditions.checkNotNull(requestMessage);
Expr requestBuilderExpr =
DefaultValueComposer.createSimpleMessageBuilderExpr(
requestMessage, resourceNames, messageTypes);
summer-ji-eng marked this conversation as resolved.
Show resolved Hide resolved
List<Expr> bodyExprs = new ArrayList<>();
summer-ji-eng marked this conversation as resolved.
Show resolved Hide resolved
bodyExprs.add(
AssignmentExpr.builder()
.setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(requestBuilderExpr)
.build());
List<Statement> bodyStatements = new ArrayList<>();
if (method.isPaged()) {
summer-ji-eng marked this conversation as resolved.
Show resolved Hide resolved
bodyStatements.addAll(
bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
bodyExprs.clear();
Message methodOutputMessage = messageTypes.get(method.outputType().reference().simpleName());
Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapFirstRepeatedField();
Preconditions.checkNotNull(
repeatedPagedResultsField,
String.format(
"Expected paged RPC %s to have a repeated field in the response %s but found none",
method.name(), methodOutputMessage.name()));
TypeNode repeatedResponseType = repeatedPagedResultsField.type();
MethodInvocationExpr clientMethodExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(clientVarExpr)
.setMethodName(JavaStyle.toLowerCamelCase(method.name()))
.setArguments(requestVarExpr)
.build();
Expr clientMethodIteratorAllExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(clientMethodExpr)
.setMethodName("iterateAll")
.setReturnType(repeatedResponseType)
.build();
ForStatement loopIteratorStatement =
ForStatement.builder()
.setLocalVariableExpr(
VariableExpr.builder()
.setVariable(
Variable.builder()
.setName("element")
.setType(repeatedResponseType)
.build())
.setIsDecl(true)
.build())
.setCollectionExpr(clientMethodIteratorAllExpr)
.setBody(
Arrays.asList(
CommentStatement.withComment(
LineComment.withComment("doThingsWith(element);"))))
.build();
bodyStatements.add(loopIteratorStatement);
} else {
TypeNode methodOutputType =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly, this could probably reuse composeUnaryRpcMethodSampleCode and composeUnaryLroRpcMethodSampleCode.

Copy link
Contributor Author

@summer-ji-eng summer-ji-eng Dec 15, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @miraleung, thanks for the valuable suggestion.

Make composeUnaryRpcMethodSampleCode, composeUnaryPagedRpcMethodSampleCode, and composeUnaryLroRpcMethodSampleCode re-usable for default method.

Update the unit test based on the new approach.

Open to discuss a better approach to re-use the utility methods. 🙏

method.hasLro() ? method.lro().responseType() : method.outputType();
Expr invokeMethodExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(clientVarExpr)
.setMethodName(
JavaStyle.toLowerCamelCase(method.name()) + (method.hasLro() ? "Async" : ""))
.setArguments(requestVarExpr)
.setReturnType(methodOutputType)
.build();
if (method.hasLro()) {
invokeMethodExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(invokeMethodExpr)
.setMethodName("get")
.setReturnType(methodOutputType)
.build();
}
boolean returnVoid = isProtoEmptyType(methodOutputType);
if (returnVoid) {
bodyExprs.add(invokeMethodExpr);
} else {
VariableExpr responseVarExpr =
VariableExpr.withVariable(
Variable.builder().setName("response").setType(methodOutputType).build());
bodyExprs.add(
AssignmentExpr.builder()
.setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(invokeMethodExpr)
.build());
}
bodyStatements.addAll(
bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
bodyExprs.clear();
}

return SampleCodeWriter.write(
TryCatchStatement.builder()
.setTryResourceExpr(assignClientVariableWithCreateMethodExpr(clientVarExpr))
.setTryBody(bodyStatements)
.setIsSampleCode(true)
.build());
}

@VisibleForTesting
static TryCatchStatement composeUnaryRpcMethodSampleCode(
Method method,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,20 @@ public class EchoClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* EchoRequest request =
* EchoRequest.newBuilder()
* .setName(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
* .setParent(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
* .setFoobar(Foobar.newBuilder().build())
* .build();
* EchoResponse response = echoClient.echo(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand Down Expand Up @@ -339,6 +353,22 @@ public class EchoClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* PagedExpandRequest request =
* PagedExpandRequest.newBuilder()
* .setContent("content951530617")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* for (EchoResponse element : echoClient.pagedExpand(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand Down Expand Up @@ -381,6 +411,22 @@ public class EchoClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* PagedExpandRequest request =
* PagedExpandRequest.newBuilder()
* .setContent("content951530617")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* for (EchoResponse element : echoClient.simplePagedExpand(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand Down Expand Up @@ -441,6 +487,15 @@ public class EchoClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* WaitRequest request = WaitRequest.newBuilder().build();
* WaitResponse response = echoClient.waitAsync(request).get();
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand All @@ -462,6 +517,15 @@ public class EchoClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* BlockRequest request = BlockRequest.newBuilder().build();
* BlockResponse response = echoClient.block(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,19 @@ public class IdentityClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* CreateUserRequest request =
* CreateUserRequest.newBuilder()
* .setParent(UserName.of("[USER]").toString())
* .setUser(User.newBuilder().build())
* .build();
* User response = identityClient.createUser(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand Down Expand Up @@ -255,6 +268,16 @@ public class IdentityClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* GetUserRequest request =
* GetUserRequest.newBuilder().setName(UserName.of("[USER]").toString()).build();
* User response = identityClient.getUser(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand All @@ -270,6 +293,16 @@ public class IdentityClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* UpdateUserRequest request =
* UpdateUserRequest.newBuilder().setUser(User.newBuilder().build()).build();
* User response = identityClient.updateUser(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand Down Expand Up @@ -324,6 +357,16 @@ public class IdentityClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* DeleteUserRequest request =
* DeleteUserRequest.newBuilder().setName(UserName.of("[USER]").toString()).build();
* identityClient.deleteUser(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand All @@ -339,6 +382,21 @@ public class IdentityClient implements BackgroundResource {

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* ListUsersRequest request =
* ListUsersRequest.newBuilder()
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* for (User element : identityClient.listUsers(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
Expand Down
Loading