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]Refactor settings sample code and add unit test #646

Merged
merged 3 commits into from
Jan 26, 2021
Merged
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 @@ -139,7 +139,8 @@ private static List<CommentStatement> createClassHeaderComments(
Optional<String> methodNameOpt =
methodOpt.isPresent() ? Optional.of(methodOpt.get().name()) : Optional.empty();
Optional<String> sampleCodeOpt =
SettingsSampleCodeComposer.composeSampleCode(methodOpt, classType);
SettingsSampleCodeComposer.composeSampleCode(
methodNameOpt, ClassNames.getServiceSettingsClassName(service), classType);
return SettingsCommentComposer.createClassHeaderComments(
ClassNames.getServiceClientClassName(service),
service.defaultHost(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,8 @@ private static List<CommentStatement> createClassHeaderComments(
Optional<String> methodNameOpt =
methodOpt.isPresent() ? Optional.of(methodOpt.get().name()) : Optional.empty();
Optional<String> sampleCodeOpt =
SettingsSampleCodeComposer.composeSampleCode(methodOpt, classType);
SettingsSampleCodeComposer.composeSampleCode(
methodNameOpt, ClassNames.getServiceSettingsClassName(service), classType);

return SettingsCommentComposer.createClassHeaderComments(
ClassNames.getServiceStubClassName(service),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

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.PrimitiveValue;
Expand All @@ -26,8 +25,6 @@
import com.google.api.generator.engine.ast.VaporReference;
import com.google.api.generator.engine.ast.Variable;
import com.google.api.generator.engine.ast.VariableExpr;
import com.google.api.generator.engine.writer.JavaWriterVisitor;
import com.google.api.generator.gapic.model.Method;
import com.google.api.generator.gapic.utils.JavaStyle;
import java.time.Duration;
import java.util.Arrays;
Expand All @@ -36,56 +33,60 @@
import java.util.stream.Collectors;

public final class SettingsSampleCodeComposer {
// TODO(summerji): Add unit tests

private static final String BUILDER_NAME_PATTERN = "%sBuilder";
private static final String STUB = "Stub";
private static final String EMPTY_STRING = "";

public static Optional<String> composeSampleCode(Optional<Method> methodOpt, TypeNode classType) {
if (!methodOpt.isPresent()) {
public static Optional<String> composeSampleCode(
Optional<String> methodNameOpt, String settingsClassName, TypeNode classType) {
if (!methodNameOpt.isPresent()) {
return Optional.empty();
}

Method method = methodOpt.get();
// Initialize services settingsBuilder with newBuilder()
// e.g. FoobarSettings.Builder foobarSettingsBuilder = FoobarSettings.newBuilder();
String className = classType.reference().name();
TypeNode builderType =
TypeNode.withReference(
VaporReference.builder()
.setEnclosingClassNames(classType.reference().name())
.setName("Builder")
.setPakkage(classType.reference().pakkage())
.build());
Variable builderVar =
Variable.builder()
.setName(getClassSettingsBuilderName(className))
.setType(builderType)
.build();
VariableExpr localSettingsVarExpr = VariableExpr.withVariable(builderVar);
Expr settingsBuilderExpr =
VariableExpr localSettingsVarExpr =
VariableExpr.withVariable(
Variable.builder()
.setName(JavaStyle.toLowerCamelCase(String.format("%sBuilder", settingsClassName)))
.setType(builderType)
.build());
MethodInvocationExpr settingsBuilderMethodInvocationExpr =
MethodInvocationExpr.builder()
.setStaticReferenceType(classType)
.setMethodName("newBuilder")
.setReturnType(builderType)
.build();
Expr initLocalSettingsExpr =
AssignmentExpr initLocalSettingsExpr =
AssignmentExpr.builder()
.setVariableExpr(localSettingsVarExpr.toBuilder().setIsDecl(true).build())
.setValueExpr(settingsBuilderExpr)
.setValueExpr(settingsBuilderMethodInvocationExpr)
.build();

// Builder with set value method
// e.g foobarSettingBuilder.fooSetting().setRetrySettings(
// echoSettingsBuilder.echoSettings().getRetrySettings().toBuilder().setTotalTimeout(Duration.ofSeconds(30)).build());
MethodInvocationExpr retrySettingsMethodExpr =
MethodInvocationExpr settingBuilderMethodInvocationExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(localSettingsVarExpr)
.setMethodName(JavaStyle.toLowerCamelCase(String.format("%sSettings", method.name())))
.setReturnType(method.outputType())
.setMethodName(
JavaStyle.toLowerCamelCase(String.format("%sSettings", methodNameOpt.get())))
.build();
MethodInvocationExpr retrySettingsArgExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(settingBuilderMethodInvocationExpr)
.setMethodName("getRetrySettings")
.build();
retrySettingsArgExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(retrySettingsArgExpr)
.setMethodName("toBuilder")
.build();
MethodInvocationExpr timeoutArExpr =
MethodInvocationExpr ofSecondMethodInvocationExpr =
MethodInvocationExpr.builder()
.setStaticReferenceType(
TypeNode.withReference(ConcreteReference.withClazz(Duration.class)))
Expand All @@ -94,30 +95,22 @@ public static Optional<String> composeSampleCode(Optional<Method> methodOpt, Typ
ValueExpr.withValue(
PrimitiveValue.builder().setType(TypeNode.INT).setValue("30").build()))
.build();
MethodInvocationExpr timeoutBuilderMethodExpr =
retrySettingsArgExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(
MethodInvocationExpr.builder()
.setExprReferenceExpr(
MethodInvocationExpr.builder()
.setExprReferenceExpr(retrySettingsMethodExpr)
.setMethodName("getRetrySettings")
.build())
.setMethodName("toBuilder")
.build())
.setExprReferenceExpr(retrySettingsArgExpr)
.setMethodName("setTotalTimeout")
.setArguments(Arrays.asList(timeoutArExpr))
.setArguments(ofSecondMethodInvocationExpr)
.build();
MethodInvocationExpr retrySettingsArgExpr =
retrySettingsArgExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(timeoutBuilderMethodExpr)
.setExprReferenceExpr(retrySettingsArgExpr)
.setMethodName("build")
.build();
MethodInvocationExpr settingBuilderMethodExpr =
settingBuilderMethodInvocationExpr =
MethodInvocationExpr.builder()
.setExprReferenceExpr(retrySettingsMethodExpr)
.setExprReferenceExpr(settingBuilderMethodInvocationExpr)
.setMethodName("setRetrySettings")
.setArguments(Arrays.asList(retrySettingsArgExpr))
.setArguments(retrySettingsArgExpr)
.build();

// Initialize clientSetting with builder() method.
Expand All @@ -126,7 +119,7 @@ public static Optional<String> composeSampleCode(Optional<Method> methodOpt, Typ
VariableExpr.withVariable(
Variable.builder()
.setType(classType)
.setName(JavaStyle.toLowerCamelCase(className).replace("Stub", ""))
.setName(JavaStyle.toLowerCamelCase(settingsClassName))
.build());
AssignmentExpr settingBuildAssignmentExpr =
AssignmentExpr.builder()
Expand All @@ -140,25 +133,13 @@ public static Optional<String> composeSampleCode(Optional<Method> methodOpt, Typ
.build();

List<Statement> statements =
Arrays.asList(initLocalSettingsExpr, settingBuilderMethodExpr, settingBuildAssignmentExpr)
Arrays.asList(
initLocalSettingsExpr,
settingBuilderMethodInvocationExpr,
settingBuildAssignmentExpr)
.stream()
.map(e -> ExprStatement.withExpr(e))
.collect(Collectors.toList());
return Optional.of(SampleCodeJavaFormatter.format(writeStatements(statements)));
}

private static String getClassSettingsBuilderName(String className) {
return JavaStyle.toLowerCamelCase(
String.format(BUILDER_NAME_PATTERN, JavaStyle.toLowerCamelCase(className)))
.replace(STUB, EMPTY_STRING);
}

// TODO(summerji): Refactor to use writeSampleCode method after PR#499 merged.
private static String writeStatements(List<Statement> statements) {
JavaWriterVisitor visitor = new JavaWriterVisitor();
for (Statement statement : statements) {
statement.accept(visitor);
}
return visitor.write();
return Optional.of(SampleCodeWriter.write(statements));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ TESTS = [
"SampleCodeJavaFormatterTest",
"SampleCodeWriterTest",
"ServiceClientSampleCodeComposerTest",
"SettingsSampleCodeComposerTest",
]

filegroup(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// 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.samplecode;

import static junit.framework.Assert.assertEquals;

import com.google.api.generator.engine.ast.TypeNode;
import com.google.api.generator.engine.ast.VaporReference;
import com.google.api.generator.testutils.LineFormatter;
import java.util.Optional;
import org.junit.Test;

public class SettingsSampleCodeComposerTest {
@Test
public void composeSettingsSampleCode_noMethods() {
TypeNode classType = TypeNode.withReference(VaporReference.builder()
.setName("EchoSettings")
.setPakkage("com.google.showcase.v1beta1")
.build());
Optional<String> results = SettingsSampleCodeComposer.composeSampleCode(Optional.empty(), "EchoSettings", classType);
assertEquals(results, Optional.empty());
}

@Test
public void composeSettingsSampleCode_serviceSettingsClass() {
TypeNode classType = TypeNode.withReference(VaporReference.builder()
.setName("EchoSettings")
.setPakkage("com.google.showcase.v1beta1")
.build());
Optional<String> results = SettingsSampleCodeComposer.composeSampleCode(Optional.of("Echo"), "EchoSettings", classType);
String expected = LineFormatter.lines(
"EchoSettings.Builder echoSettingsBuilder = EchoSettings.newBuilder();\n",
"echoSettingsBuilder\n",
" .echoSettings()\n",
" .setRetrySettings(\n",
" echoSettingsBuilder\n",
" .echoSettings()\n",
" .getRetrySettings()\n",
" .toBuilder()\n",
" .setTotalTimeout(Duration.ofSeconds(30))\n",
" .build());\n",
"EchoSettings echoSettings = echoSettingsBuilder.build();");
assertEquals(results.get(), expected);
}

@Test
public void composeSettingsSampleCode_serviceStubClass() {
TypeNode classType = TypeNode.withReference(VaporReference.builder()
.setName("EchoStubSettings")
.setPakkage("com.google.showcase.v1beta1")
.build());
Optional<String> results = SettingsSampleCodeComposer.composeSampleCode(Optional.of("Echo"), "EchoSettings", classType);
String expected = LineFormatter.lines(
"EchoStubSettings.Builder echoSettingsBuilder = EchoStubSettings.newBuilder();\n",
"echoSettingsBuilder\n",
" .echoSettings()\n",
" .setRetrySettings(\n",
" echoSettingsBuilder\n",
" .echoSettings()\n",
" .getRetrySettings()\n",
" .toBuilder()\n",
" .setTotalTimeout(Duration.ofSeconds(30))\n",
" .build());\n",
"EchoStubSettings echoSettings = echoSettingsBuilder.build();");
assertEquals(results.get(), expected);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,18 @@
* <p>For example, to set the total timeout of getBucket to 30 seconds:
*
* <pre>{@code
* ConfigServiceV2StubSettings.Builder configServiceV2SettingsBuilder =
* ConfigServiceV2StubSettings.Builder configSettingsBuilder =
* ConfigServiceV2StubSettings.newBuilder();
* configServiceV2SettingsBuilder
* configSettingsBuilder
* .getBucketSettings()
* .setRetrySettings(
* configServiceV2SettingsBuilder
* configSettingsBuilder
* .getBucketSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* ConfigServiceV2StubSettings configServiceV2Settings = configServiceV2SettingsBuilder.build();
* ConfigServiceV2StubSettings configSettings = configSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,18 @@
* <p>For example, to set the total timeout of deleteLog to 30 seconds:
*
* <pre>{@code
* LoggingServiceV2StubSettings.Builder loggingServiceV2SettingsBuilder =
* LoggingServiceV2StubSettings.Builder loggingSettingsBuilder =
* LoggingServiceV2StubSettings.newBuilder();
* loggingServiceV2SettingsBuilder
* loggingSettingsBuilder
* .deleteLogSettings()
* .setRetrySettings(
* loggingServiceV2SettingsBuilder
* loggingSettingsBuilder
* .deleteLogSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* LoggingServiceV2StubSettings loggingServiceV2Settings = loggingServiceV2SettingsBuilder.build();
* LoggingServiceV2StubSettings loggingSettings = loggingSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,18 @@
* <p>For example, to set the total timeout of getLogMetric to 30 seconds:
*
* <pre>{@code
* MetricsServiceV2StubSettings.Builder metricsServiceV2SettingsBuilder =
* MetricsServiceV2StubSettings.Builder metricsSettingsBuilder =
* MetricsServiceV2StubSettings.newBuilder();
* metricsServiceV2SettingsBuilder
* metricsSettingsBuilder
* .getLogMetricSettings()
* .setRetrySettings(
* metricsServiceV2SettingsBuilder
* metricsSettingsBuilder
* .getLogMetricSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* MetricsServiceV2StubSettings metricsServiceV2Settings = metricsServiceV2SettingsBuilder.build();
* MetricsServiceV2StubSettings metricsSettings = metricsSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
Expand Down