use of com.google.api.generator.gapic.model.Sample in project gapic-generator-java by googleapis.
the class ServiceClientHeaderSampleComposerTest method composeClassHeaderSample_unaryRpc.
/*Testing composeClassHeaderSample*/
@Test
public void composeClassHeaderSample_unaryRpc() {
Descriptors.FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
Set<ResourceName> outputResourceNames = new HashSet<>();
List<Service> services = Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames);
Service echoProtoService = services.get(0);
TypeNode clientType = TypeNode.withReference(VaporReference.builder().setName("EchoClient").setPakkage(SHOWCASE_PACKAGE_NAME).build());
Sample sample = ServiceClientHeaderSampleComposer.composeClassHeaderSample(echoProtoService, clientType, resourceNames, messageTypes);
String results = writeStatements(sample);
String expected = LineFormatter.lines("try (EchoClient echoClient = EchoClient.create()) {\n", " EchoResponse response = echoClient.echo();\n", "}");
Assert.assertEquals(expected, results);
}
use of com.google.api.generator.gapic.model.Sample in project gapic-generator-java by googleapis.
the class AbstractServiceClientClassComposer method createMethodDefaultMethod.
private static MethodDefinition createMethodDefaultMethod(Method method, String clientName, Map<String, Message> messageTypes, TypeStore typeStore, Map<String, ResourceName> resourceNames, List<Sample> samples) {
String methodName = JavaStyle.toLowerCamelCase(method.name());
TypeNode methodInputType = method.inputType();
TypeNode methodOutputType = method.isPaged() ? typeStore.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) : method.outputType();
List<AnnotationNode> annotations = new ArrayList<>();
if (method.hasLro()) {
LongrunningOperation lro = method.lro();
methodOutputType = TypeNode.withReference(typeStore.get("OperationFuture").reference().copyAndSetGenerics(Arrays.asList(lro.responseType().reference(), lro.metadataType().reference())));
if (method.lro().operationServiceStubType() != null) {
annotations.add(AnnotationNode.withTypeAndDescription(typeStore.get("BetaApi"), "The surface for long-running operations is not stable yet and may change in the" + " future."));
}
}
// Construct the method that accepts a request proto.
VariableExpr requestArgVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("request").setType(methodInputType).build()).setIsDecl(true).build();
String callableMethodName = method.isPaged() ? String.format(PAGED_CALLABLE_NAME_PATTERN, methodName) : String.format(CALLABLE_NAME_PATTERN, methodName);
if (method.hasLro()) {
callableMethodName = String.format(OPERATION_CALLABLE_NAME_PATTERN, methodName);
}
Optional<Sample> defaultMethodSample = Optional.of(ServiceClientMethodSampleComposer.composeCanonicalSample(method, typeStore.get(clientName), resourceNames, messageTypes));
Optional<String> defaultMethodDocSample = Optional.empty();
if (defaultMethodSample.isPresent()) {
samples.add(defaultMethodSample.get());
defaultMethodDocSample = Optional.of(SampleCodeWriter.writeInlineSample(defaultMethodSample.get().body()));
}
MethodInvocationExpr callableMethodExpr = MethodInvocationExpr.builder().setMethodName(callableMethodName).build();
callableMethodExpr = MethodInvocationExpr.builder().setMethodName(method.hasLro() ? "futureCall" : "call").setArguments(Arrays.asList(requestArgVarExpr.toBuilder().setIsDecl(false).build())).setExprReferenceExpr(callableMethodExpr).setReturnType(methodOutputType).build();
MethodDefinition.Builder methodBuilder = MethodDefinition.builder().setHeaderCommentStatements(ServiceClientCommentComposer.createRpcMethodHeaderComment(method, defaultMethodDocSample)).setScope(ScopeNode.PUBLIC).setIsFinal(true).setName(String.format(method.hasLro() ? "%sAsync" : "%s", methodName)).setArguments(Arrays.asList(requestArgVarExpr));
if (method.isDeprecated()) {
annotations.add(AnnotationNode.withType(TypeNode.DEPRECATED));
}
if (isProtoEmptyType(methodOutputType)) {
methodBuilder = methodBuilder.setBody(Arrays.asList(ExprStatement.withExpr(callableMethodExpr))).setReturnType(TypeNode.VOID);
} else {
methodBuilder = methodBuilder.setReturnExpr(callableMethodExpr).setReturnType(methodOutputType);
}
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
use of com.google.api.generator.gapic.model.Sample in project gapic-generator-java by googleapis.
the class AbstractServiceClientClassComposer method createCallableMethod.
private static MethodDefinition createCallableMethod(Service service, Method method, CallableMethodKind callableMethodKind, TypeStore typeStore, Map<String, Message> messageTypes, Map<String, ResourceName> resourceNames, List<Sample> samples) {
TypeNode rawCallableReturnType = null;
if (callableMethodKind.equals(CallableMethodKind.LRO)) {
rawCallableReturnType = typeStore.get("OperationCallable");
} else {
switch(method.stream()) {
case CLIENT:
rawCallableReturnType = typeStore.get("ClientStreamingCallable");
break;
case SERVER:
rawCallableReturnType = typeStore.get("ServerStreamingCallable");
break;
case BIDI:
rawCallableReturnType = typeStore.get("BidiStreamingCallable");
break;
case NONE:
// Fall through.
default:
rawCallableReturnType = typeStore.get("UnaryCallable");
}
}
// Set generics.
TypeNode returnType = TypeNode.withReference(rawCallableReturnType.reference().copyAndSetGenerics(getGenericsForCallable(callableMethodKind, method, typeStore)));
String rawMethodName = JavaStyle.toLowerCamelCase(method.name());
String methodName = getCallableName(callableMethodKind, rawMethodName);
TypeNode stubType = typeStore.get(ClassNames.getServiceStubClassName(service));
MethodInvocationExpr returnExpr = MethodInvocationExpr.builder().setExprReferenceExpr(VariableExpr.builder().setVariable(Variable.builder().setName("stub").setType(stubType).build()).build()).setMethodName(methodName).setReturnType(returnType).build();
Optional<Sample> sampleCode = Optional.empty();
if (callableMethodKind.equals(CallableMethodKind.LRO)) {
sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composeLroCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
} else if (callableMethodKind.equals(CallableMethodKind.PAGED)) {
sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composePagedCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
} else if (callableMethodKind.equals(CallableMethodKind.REGULAR)) {
if (method.stream().equals(Stream.NONE)) {
sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composeRegularCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
} else {
sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composeStreamCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
}
}
Optional<String> sampleDocCode = Optional.empty();
if (sampleCode.isPresent()) {
samples.add(sampleCode.get());
sampleDocCode = Optional.of(SampleCodeWriter.writeInlineSample(sampleCode.get().body()));
}
MethodDefinition.Builder methodDefBuilder = MethodDefinition.builder();
if (method.isDeprecated()) {
methodDefBuilder = methodDefBuilder.setAnnotations(Arrays.asList(AnnotationNode.withType(TypeNode.DEPRECATED)));
}
return methodDefBuilder.setHeaderCommentStatements(ServiceClientCommentComposer.createRpcCallableMethodHeaderComment(method, sampleDocCode)).setScope(ScopeNode.PUBLIC).setIsFinal(true).setName(methodName).setReturnType(returnType).setReturnExpr(returnExpr).build();
}
use of com.google.api.generator.gapic.model.Sample in project gapic-generator-java by googleapis.
the class SampleComposerUtil method handleDuplicateSamples.
public static List<Sample> handleDuplicateSamples(List<Sample> samples) {
// grab all distinct samples and group by sample name
// ie: { "echo", ["echo(request"],
// "echoString", ["echo(parent)", "echo(child)", "echo(context)"],
// "echoDelete", ["echo.delete(request)"] }
Map<String, List<Sample>> distinctSamplesGroupedByName = samples.stream().distinct().collect(Collectors.groupingBy(s -> s.name()));
// collect samples that don't have duplicates
// ie: ["echo", "echoDelete"]
List<Sample> uniqueSamples = distinctSamplesGroupedByName.entrySet().stream().filter(entry -> entry.getValue().size() < 2).map(entry -> entry.getValue().get(0)).collect(Collectors.toList());
if (uniqueSamples.size() == distinctSamplesGroupedByName.size()) {
return uniqueSamples;
}
// collect samples that do have duplicates
// ie: ["echoString"]
List<Map.Entry<String, List<Sample>>> duplicateDistinctSamples = distinctSamplesGroupedByName.entrySet().stream().filter(entry -> entry.getValue().size() > 1).collect(Collectors.toList());
// ie: ["echo", "echoDelete", "echoString", "echoString1"]
for (Map.Entry<String, List<Sample>> entry : duplicateDistinctSamples) {
int sampleNum = 0;
for (Sample sample : entry.getValue()) {
Sample uniqueSample = sample;
// first sample will be "canonical", not updating name
if (sampleNum != 0) {
uniqueSample = sample.withRegionTag(sample.regionTag().withOverloadDisambiguation(sample.regionTag().overloadDisambiguation() + sampleNum));
}
uniqueSamples.add(uniqueSample);
sampleNum++;
}
}
return uniqueSamples;
}
use of com.google.api.generator.gapic.model.Sample in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composeRegularCallableMethod.
// Compose sample code for the method where it is CallableMethodKind.REGULAR.
public static Sample composeRegularCallableMethod(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().fullName());
Preconditions.checkNotNull(requestMessage, String.format("Could not find the message type %s.", method.inputType().reference().fullName()));
Expr requestBuilderExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes);
AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(requestBuilderExpr).build();
List<Statement> bodyStatements = new ArrayList<>();
bodyStatements.add(ExprStatement.withExpr(requestAssignmentExpr));
RegionTag regionTag;
if (method.isPaged()) {
Sample pagedCallable = composePagedCallableSample(method, clientVarExpr, requestVarExpr, messageTypes);
bodyStatements.addAll(pagedCallable.body());
regionTag = pagedCallable.regionTag();
} else {
// e.g. echoClient.echoCallable().futureCall(request)
Sample unaryOrLroCallable = composeUnaryOrLroCallableSample(method, clientVarExpr, requestVarExpr);
bodyStatements.addAll(unaryOrLroCallable.body());
regionTag = unaryOrLroCallable.regionTag();
}
List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
return Sample.builder().setBody(body).setRegionTag(regionTag).build();
}
Aggregations