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

[draft][5/5]Implement default unary rpc method's sample code #517

Closed
wants to merge 12 commits into from
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

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;
Expand All @@ -31,6 +32,7 @@
import com.google.api.generator.gapic.model.ResourceName;
import com.google.api.generator.gapic.utils.JavaStyle;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
Expand All @@ -47,7 +49,7 @@ 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()) {
Expand Down Expand Up @@ -170,19 +172,81 @@ private static TryCatchStatement composePagedUnaryRpcMethodSampleCode(
}

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.
VariableExpr clientVarExpr = createVariableExpr(getClientName(clientType), clientType);
String content =
String.format(
"Note: Not implemented yet, placeholder for unary %s rpc method sample code.",
(!method.hasLro() && !method.isPaged()
? "default"
: (method.hasLro() ? "lro default" : "paged default")));
VariableExpr requestVarExpr = createVariableExpr(REQUEST_VAR_NAME, method.inputType());
VariableExpr responseVarExpr = createVariableExpr(RESPONSE_VAR_NAME, method.outputType());
// 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<Expr> bodyExprs =
arguments.stream()
.map(methodArg -> assignMethodArgumentWithDefaultValue(methodArg, resourceNames))
.collect(Collectors.toList());
// Assign request variables with set argument attributes.
bodyExprs.add(createRequestBuilderExpr(requestVarExpr, arguments));

List<Statement> bodyStatements =
bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
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(clientVarExpr.toBuilder().setIsDecl(true).build())
.setCollectionExpr(createIteratorAllMethodExpr(method, clientVarExpr, 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()
.setExprReferenceExpr(clientVarExpr)
.setMethodName(getLroMethodName(method.name()))
.setArguments(Arrays.asList(requestVarExpr))
.build())
.setMethodName("get")
.setReturnType(method.outputType())
.build();
if (!method.outputType().equals(TypeNode.VOID)) {
getResponseMethodExpr =
AssignmentExpr.builder()
.setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(getResponseMethodExpr)
.build();
}
bodyStatements.add(ExprStatement.withExpr(getResponseMethodExpr));
} else {
// Create response variable by invoke client's method by passing request.
// e.g. EchoResponse response = echoClient.Echo(request);
Expr invokeMethodExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(clientVarExpr)
.setMethodName(JavaStyle.toLowerCamelCase(method.name()))
.setArguments(requestVarExpr)
.setReturnType(method.outputType())
.build();
if (!method.outputType().equals(TypeNode.VOID)) {
invokeMethodExpr =
AssignmentExpr.builder()
.setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(invokeMethodExpr)
.build();
}
bodyStatements.add(ExprStatement.withExpr(invokeMethodExpr));
}

return TryCatchStatement.builder()
.setTryResourceExpr(assignClientVariableWithCreateMethodExpr(clientVarExpr))
.setTryBody(Arrays.asList(createLineCommentStatement(content)))
.setTryBody(bodyStatements)
.setIsSampleCode(true)
.build();
}
Expand All @@ -204,6 +268,47 @@ private static AssignmentExpr assignClientVariableWithCreateMethodExpr(
.build();
}

// Create request variable by set attributes.
// e.g. EchoRequest request = EchoRequest.newBuilder().setParent(parent).build();
private static Expr createRequestBuilderExpr(
VariableExpr requestVarExpr, List<MethodArgument> arguments) {
MethodInvocationExpr newBuilderExpr =
MethodInvocationExpr.builder()
.setStaticReferenceType(requestVarExpr.variable().type())
.setMethodName("newBuilder")
.build();
for (MethodArgument arg : arguments) {
// if method argument is ResourceName, return method invocation expr <arg>.toString().
TypeNode resourceNameType =
TypeNode.withReference(
ConcreteReference.withClazz(com.google.api.resourcenames.ResourceName.class));
Expr argumentExpr = createVariableExpr(arg.name(), arg.type());
if (resourceNameType.isSupertypeOrEquals(arg.type())) {
argumentExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(argumentExpr)
.setMethodName("toString")
.build();
}
newBuilderExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(newBuilderExpr)
.setMethodName(String.format("set%s", JavaStyle.toUpperCamelCase(arg.name())))
.setArguments(argumentExpr)
.build();
}
MethodInvocationExpr requestBuildExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(newBuilderExpr)
.setMethodName("build")
.setReturnType(requestVarExpr.variable().type())
.build();
return AssignmentExpr.builder()
.setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(requestBuildExpr)
.build();
}

private static Expr assignMethodArgumentWithDefaultValue(
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we refactor this so that we use the variable expr throughout (like one would do with Java programming) instead of recreating it several times?

MethodArgument argument, Map<String, ResourceName> resourceNames) {
return AssignmentExpr.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,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 implemented yet, placeholder for unary default rpc method sample code.
* ResourceName parent = FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]");
* EchoRequest request = EchoRequest.newBuilder().setParent(parent.toString()).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 implemented 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 @@ -402,7 +407,9 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not implemented 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 @@ -431,7 +438,8 @@ public class EchoClient implements BackgroundResource {
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* BlockRequest request = BlockRequest.newBuilder().build();
* BlockResponse response = echoClient.block(request);
* }
* }</pre>
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,16 @@ public class IdentityClient implements BackgroundResource {
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* String parent = "parent-995424086";
* String display_name = "display_name1615086568";
* String email = "email96619420";
* CreateUserRequest request =
* CreateUserRequest.newBuilder()
* .setParent(parent)
* .setDisplayName(display_name)
* .setEmail(email)
* .build();
* User response = identityClient.createUser(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -266,7 +275,9 @@ public class IdentityClient implements BackgroundResource {
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* UserName name = UserName.of("[USER]");
* GetUserRequest request = GetUserRequest.newBuilder().setName(name.toString()).build();
* User response = identityClient.getUser(request);
* }
* }</pre>
*
Expand All @@ -289,7 +300,8 @@ public class IdentityClient implements BackgroundResource {
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* UpdateUserRequest request = UpdateUserRequest.newBuilder().build();
* User response = identityClient.updateUser(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -353,7 +365,9 @@ public class IdentityClient implements BackgroundResource {
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* UserName name = UserName.of("[USER]");
* DeleteUserRequest request = DeleteUserRequest.newBuilder().setName(name.toString()).build();
* Empty response = identityClient.deleteUser(request);
* }
* }</pre>
*
Expand All @@ -376,7 +390,10 @@ public class IdentityClient implements BackgroundResource {
*
* <pre>{@code
* try (IdentityClient identityClient = IdentityClient.create()) {
* // Note: Not implemented yet, placeholder for unary paged default rpc method sample code.
* ListUsersRequest request = ListUsersRequest.newBuilder().build();
* for (IdentityClient identityClient : identityClient.ListUsers(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
Expand Down
49 changes: 40 additions & 9 deletions test/integration/goldens/asset/AssetServiceClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,8 @@ public final OperationsClient getOperationsClient() {
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary lro default rpc method sample code.
* ExportAssetsRequest request = ExportAssetsRequest.newBuilder().build();
* Operation response = assetServiceClient.exportAssetsAsync(request).get();
* }
* }</pre>
*
Expand Down Expand Up @@ -229,7 +230,8 @@ public final UnaryCallable<ExportAssetsRequest, Operation> exportAssetsCallable(
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* BatchGetAssetsHistoryRequest request = BatchGetAssetsHistoryRequest.newBuilder().build();
* BatchGetAssetsHistoryResponse response = assetServiceClient.batchGetAssetsHistory(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -288,7 +290,9 @@ public final Feed createFeed(String parent) {
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* String parent = "parent-995424086";
* CreateFeedRequest request = CreateFeedRequest.newBuilder().setParent(parent).build();
* Feed response = assetServiceClient.createFeed(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -364,7 +368,9 @@ public final Feed getFeed(String name) {
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* FeedName name = FeedName.ofProjectFeedName("[PROJECT]", "[FEED]");
* GetFeedRequest request = GetFeedRequest.newBuilder().setName(name.toString()).build();
* Feed response = assetServiceClient.getFeed(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -416,7 +422,9 @@ public final ListFeedsResponse listFeeds(String parent) {
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* String parent = "parent-995424086";
* ListFeedsRequest request = ListFeedsRequest.newBuilder().setParent(parent).build();
* ListFeedsResponse response = assetServiceClient.listFeeds(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -468,7 +476,9 @@ public final Feed updateFeed(Feed feed) {
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* Feed feed = Feed.newBuilder().build();
* UpdateFeedRequest request = UpdateFeedRequest.newBuilder().setFeed(feed).build();
* Feed response = assetServiceClient.updateFeed(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -546,7 +556,9 @@ public final Empty deleteFeed(String name) {
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary default rpc method sample code.
* FeedName name = FeedName.ofProjectFeedName("[PROJECT]", "[FEED]");
* DeleteFeedRequest request = DeleteFeedRequest.newBuilder().setName(name.toString()).build();
* Empty response = assetServiceClient.deleteFeed(request);
* }
* }</pre>
*
Expand Down Expand Up @@ -657,7 +669,19 @@ public final SearchAllResourcesPagedResponse searchAllResources(
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary paged default rpc method sample code.
* String scope = "scope109264468";
* String query = "query107944136";
* List<String> asset_types = new ArrayList<>();
* SearchAllResourcesRequest request =
* SearchAllResourcesRequest.newBuilder()
* .setScope(scope)
* .setQuery(query)
* .setAssetTypes(asset_types)
* .build();
* for (AssetServiceClient assetServiceClient :
* assetServiceClient.SearchAllResources(scope, query, asset_types).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
Expand Down Expand Up @@ -768,7 +792,14 @@ public final SearchAllIamPoliciesPagedResponse searchAllIamPolicies(String scope
*
* <pre>{@code
* try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
* // Note: Not implemented yet, placeholder for unary paged default rpc method sample code.
* String scope = "scope109264468";
* String query = "query107944136";
* SearchAllIamPoliciesRequest request =
* SearchAllIamPoliciesRequest.newBuilder().setScope(scope).setQuery(query).build();
* for (AssetServiceClient assetServiceClient :
* assetServiceClient.SearchAllIamPolicies(scope, query).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
Expand Down
Loading