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

[DO NOT REVIEW][Merged In #573][CloseSoon]Use resource name class to construct String Default value #577

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 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 @@ -60,8 +60,8 @@ public static List<GapicClass> generateServiceClasses(
@Nonnull Map<String, ResourceName> resourceNames,
@Nonnull Map<String, Message> messageTypes) {
List<GapicClass> clazzes = new ArrayList<>();
clazzes.addAll(generateStubClasses(service, serviceConfig, messageTypes));
clazzes.addAll(generateClientSettingsClasses(service, messageTypes));
clazzes.addAll(generateStubClasses(service, serviceConfig, messageTypes, resourceNames));
clazzes.addAll(generateClientSettingsClasses(service, messageTypes, resourceNames));
clazzes.addAll(generateMocksAndTestClasses(service, resourceNames, messageTypes));
// TODO(miraleung): Generate test classes.
return clazzes;
Expand All @@ -76,7 +76,10 @@ public static List<GapicClass> generateResourceNameHelperClasses(
}

public static List<GapicClass> generateStubClasses(
Service service, GapicServiceConfig serviceConfig, Map<String, Message> messageTypes) {
Service service,
GapicServiceConfig serviceConfig,
Map<String, Message> messageTypes,
Map<String, ResourceName> resourceNames) {
List<GapicClass> clazzes = new ArrayList<>();
clazzes.add(ServiceStubClassComposer.instance().generate(service, messageTypes));
clazzes.add(
Expand All @@ -87,9 +90,10 @@ public static List<GapicClass> generateStubClasses(
}

public static List<GapicClass> generateClientSettingsClasses(
Service service, Map<String, Message> messageTypes) {
Service service, Map<String, Message> messageTypes, Map<String, ResourceName> resourceNames) {
List<GapicClass> clazzes = new ArrayList<>();
clazzes.add(ServiceClientClassComposer.instance().generate(service, messageTypes));
clazzes.add(
ServiceClientClassComposer.instance().generate(service, messageTypes, resourceNames));
clazzes.add(ServiceSettingsClassComposer.instance().generate(service, messageTypes));
return clazzes;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public class DefaultValueComposer {
TypeNode.withReference(ConcreteReference.withClazz(ByteString.class));

static Expr createDefaultValue(
MethodArgument methodArg, Map<String, ResourceName> resourceNames) {
MethodArgument methodArg, Map<String, ResourceName> resourceNames, boolean useSampleCode) {
if (methodArg.isResourceNameHelper()) {
Preconditions.checkState(
methodArg.field().hasResourceReference(),
Expand All @@ -71,18 +71,29 @@ static Expr createDefaultValue(
}

if (methodArg.type().equals(methodArg.field().type())) {
return createDefaultValue(methodArg.field());
return createDefaultValue(methodArg.field(), resourceNames, useSampleCode);
}

return createDefaultValue(
Field.builder().setName(methodArg.name()).setType(methodArg.type()).build());
Field.builder().setName(methodArg.name()).setType(methodArg.type()).build(),
resourceNames,
useSampleCode);
}

static Expr createDefaultValue(
Field f, Map<String, ResourceName> resourceNames, Boolean useSampleCode) {
Copy link
Contributor

Choose a reason for hiding this comment

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

What was the motivation for using the boxed type?

return createDefaultValue(f, resourceNames, false, useSampleCode);
}

static Expr createDefaultValue(Field f) {
return createDefaultValue(f, false);
return createDefaultValue(f, new HashMap<>(), false, false);
}

static Expr createDefaultValue(Field f, boolean useExplicitInitTypeInGenerics) {
static Expr createDefaultValue(
Field f,
Map<String, ResourceName> resourceNames,
boolean useExplicitInitTypeInGenerics,
boolean useSampleCode) {
if (f.isRepeated()) {
ConcreteReference.Builder refBuilder =
ConcreteReference.builder().setClazz(f.isMap() ? HashMap.class : ArrayList.class);
Expand Down Expand Up @@ -123,6 +134,13 @@ static Expr createDefaultValue(Field f, boolean useExplicitInitTypeInGenerics) {
}

if (f.type().equals(TypeNode.STRING)) {
if (useSampleCode
Copy link
Contributor

Choose a reason for hiding this comment

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

Why not pass in the ResourceName-typed field instead if the field is a String? Then we don't need to change DefaultValueComposer at all.

&& f.hasResourceReference()
&& resourceNames.containsKey(f.resourceReference().resourceTypeString())) {
ResourceName resourceName = resourceNames.get(f.resourceReference().resourceTypeString());
return createDefaultValue(
resourceName, resourceNames.values().stream().collect(Collectors.toList()), f.name());
}
return ValueExpr.withValue(
StringObjectValue.withValue(String.format("%s%s", f.name(), f.name().hashCode())));
}
Expand Down Expand Up @@ -255,7 +273,7 @@ static Expr createSimpleMessageBuilderExpr(
.setReturnType(TypeNode.STRING)
.build();
} else {
defaultExpr = createDefaultValue(field, true);
defaultExpr = createDefaultValue(field, resourceNames, true, false);
}
builderExpr =
MethodInvocationExpr.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.generator.gapic.composer;

import com.google.api.generator.engine.ast.AssignmentExpr;
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.MethodInvocationExpr;
import com.google.api.generator.engine.ast.TryCatchStatement;
import com.google.api.generator.engine.ast.TypeNode;
import com.google.api.generator.engine.ast.Variable;
import com.google.api.generator.engine.ast.VariableExpr;
import com.google.api.generator.gapic.model.Method;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MethodSampleCodeHelperComposer {
private static String RESPONSE = "response";

public static TryCatchStatement composeUnaryRpcMethodSampleCode(
Method method,
List<MethodArgument> arguments,
TypeNode clientType,
Map<String, ResourceName> resourceNames) {
VariableExpr clientVarExpr = createVariableExpr(getClientName(clientType), clientType);
// Assign each method arguments with its default value.
Map<String, VariableExpr> methodArgVarExprMap = createMethodArgumentsVariableExprs(arguments);
List<Expr> methodArgumentsAssignmentExpr =
assignMethodArgumentsWithDefaultValues(arguments, methodArgVarExprMap, resourceNames);
List<Expr> methodVarExprs =
createMethodArgVarExprs(arguments, methodArgVarExprMap, resourceNames);
Copy link
Contributor

Choose a reason for hiding this comment

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

PTAL at my comments on splitting out the VarExprs in #573.

// Invoke current method based on return type.
// e.g. if return void, echoClient.echo(..); or,
// e.g. if return other type, EchoResponse response = echoClient.echo(...);
boolean returnsVoid = isProtoEmptyType(method.outputType());
Expr responseExpr = null;
if (returnsVoid) {
responseExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(clientVarExpr)
.setMethodName(JavaStyle.toLowerCamelCase(method.name()))
.setArguments(methodVarExprs)
.setReturnType(clientType)
.build();
} else {
responseExpr =
createAssignExprForVariableWithClientMethod(
createVariableExpr(RESPONSE, method.outputType()),
clientVarExpr,
JavaStyle.toLowerCamelCase(method.name()),
methodVarExprs);
}

List<Expr> bodyExpr = new ArrayList<>();
bodyExpr.addAll(methodArgumentsAssignmentExpr);
bodyExpr.add(responseExpr);

return TryCatchStatement.builder()
.setTryResourceExpr(assignClientVariableWithCreateMethodExpr(clientVarExpr))
.setTryBody(
bodyExpr.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()))
.setIsSampleCode(true)
.build();
}

// ==================================Helpers===================================================//

// Assign client variable expr with create client.
// e.g EchoClient echoClient = EchoClient.create()
private static AssignmentExpr assignClientVariableWithCreateMethodExpr(
VariableExpr clientVarExpr) {
return AssignmentExpr.builder()
.setVariableExpr(clientVarExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(
MethodInvocationExpr.builder()
.setStaticReferenceType(clientVarExpr.variable().type())
.setReturnType(clientVarExpr.variable().type())
.setMethodName("create")
.build())
.build();
}

// Create a Map where key is method's argument name, and value is its VariableExpr.
private static Map<String, VariableExpr> createMethodArgumentsVariableExprs(
List<MethodArgument> arguments) {
return arguments.stream()
.collect(
Collectors.toMap(
methodArg -> methodArg.name(),
methodArg ->
createVariableExpr(
JavaStyle.toLowerCamelCase(methodArg.name()), methodArg.type())));
}

// Return a list of AssignmentExpr for method argument with its default value.
private static List<Expr> assignMethodArgumentsWithDefaultValues(
List<MethodArgument> arguments,
Map<String, VariableExpr> argVarExprs,
Map<String, ResourceName> resourceNames) {
return arguments.stream()
.map(
arg -> {
Expr defaultValueExpr =
DefaultValueComposer.createDefaultValue(arg, resourceNames, true);
Copy link
Contributor

Choose a reason for hiding this comment

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

Here: If arg is String-typed and it has a matching resource name, pass that arg in instead.

VariableExpr argVarExpr =
(arg.field().hasResourceReference() && !arg.isResourceNameHelper())
? getMethodArgumentResourceReferenceVariableExpr(arg, defaultValueExpr)
: argVarExprs.get(arg.name());
return createAssignmentExpr(argVarExpr, defaultValueExpr);
})
.collect(Collectors.toList());
}

private static VariableExpr getMethodArgumentResourceReferenceVariableExpr(
MethodArgument methodArg, Expr defaultValueExpr) {
TypeNode resourceReferenceType =
methodArg.field().resourceReference().isChildType()
? TypeNode.withReference(
ConcreteReference.withClazz(com.google.api.resourcenames.ResourceName.class))
: defaultValueExpr.type();
return createVariableExpr(JavaStyle.toLowerCamelCase(methodArg.name()), resourceReferenceType);
}

private static List<Expr> createMethodArgVarExprs(
List<MethodArgument> arguments,
Map<String, VariableExpr> methodArgVarExprMap,
Map<String, ResourceName> resourceNames) {
return arguments.stream()
.map(
arg -> {
if (!arg.isResourceNameHelper()
&& arg.field().hasResourceReference()
&& resourceNames.containsKey(
arg.field().resourceReference().resourceTypeString())) {
return MethodInvocationExpr.builder()
.setExprReferenceExpr(methodArgVarExprMap.get(arg.name()))
.setMethodName("toString")
.build();
}
return methodArgVarExprMap.get(arg.name());
})
.collect(Collectors.toList());
}

private static Expr createAssignExprForVariableWithClientMethod(
VariableExpr variableExpr,
VariableExpr clientVarExpr,
String methodName,
List<Expr> argumentsVarExprs) {
MethodInvocationExpr clientMethodInvocationExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(clientVarExpr)
.setMethodName(JavaStyle.toLowerCamelCase(methodName))
.setArguments(argumentsVarExprs)
.setReturnType(variableExpr.variable().type())
.build();
return AssignmentExpr.builder()
.setVariableExpr(variableExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(clientMethodInvocationExpr)
.build();
}

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

private static boolean isProtoEmptyType(TypeNode type) {
return type.reference().pakkage().equals("com.google.protobuf")
&& type.reference().name().equals("Empty");
}

private static AssignmentExpr createAssignmentExpr(VariableExpr variableExpr, Expr valueExpr) {
return AssignmentExpr.builder()
.setVariableExpr(variableExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(valueExpr)
.build();
}

private static VariableExpr createVariableExpr(String variableName, TypeNode type) {
return VariableExpr.builder()
.setVariable(Variable.builder().setName(variableName).setType(type).build())
.build();
}
}
Loading