use of com.google.api.generator.gapic.model.Message in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composePagedCallableMethod.
// Compose sample code for the method where it is CallableMethodKind.PAGED.
public static Sample composePagedCallableMethod(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<Expr> bodyExprs = new ArrayList<>();
bodyExprs.add(requestAssignmentExpr);
// Find the repeated field.
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found on message %s for method %s", methodOutputMessage.name(), method.name()));
TypeNode repeatedResponseType = repeatedPagedResultsField.type();
// Create ApiFuture Variable Expression with assign value by invoking client paged callable
// method.
// e.g. ApiFuture<ListExclusionsPagedResponse> future =
// configServiceV2Client.listExclusionsPagedCallable().futureCall(request);
TypeNode apiFutureType = TypeNode.withReference(ConcreteReference.builder().setClazz(ApiFuture.class).setGenerics(repeatedResponseType.reference()).build());
VariableExpr apiFutureVarExpr = VariableExpr.withVariable(Variable.builder().setName("future").setType(apiFutureType).build());
MethodInvocationExpr pagedCallableFutureMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(String.format("%sPagedCallable", JavaStyle.toLowerCamelCase(method.name()))).build();
pagedCallableFutureMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(pagedCallableFutureMethodExpr).setMethodName("futureCall").setArguments(requestVarExpr).setReturnType(apiFutureType).build();
AssignmentExpr apiFutureAssignmentExpr = AssignmentExpr.builder().setVariableExpr(apiFutureVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(pagedCallableFutureMethodExpr).build();
bodyExprs.add(apiFutureAssignmentExpr);
List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
bodyExprs.clear();
// Add line comment
bodyStatements.add(CommentStatement.withComment(LineComment.withComment("Do something.")));
// For-loop on repeated response element
// e.g. for (ListExclusionsResponse element : future.get().iterateAll()) {
// // doThingsWith(element);
// }
VariableExpr repeatedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setName("element").setType(repeatedResponseType).build());
MethodInvocationExpr futureGetIterateAllMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(apiFutureVarExpr).setMethodName("get").build();
futureGetIterateAllMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(futureGetIterateAllMethodExpr).setMethodName("iterateAll").setReturnType(repeatedResponseType).build();
CommentStatement lineCommentStatement = CommentStatement.withComment(LineComment.withComment("doThingsWith(element);"));
ForStatement repeatedResponseForStatement = ForStatement.builder().setLocalVariableExpr(repeatedResponseVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(futureGetIterateAllMethodExpr).setBody(Arrays.asList(lineCommentStatement)).build();
bodyStatements.add(repeatedResponseForStatement);
List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
RegionTag regionTag = RegionTag.builder().setServiceName(clientType.reference().name()).setRpcName(method.name()).setIsAsynchronous(true).build();
return Sample.builder().setBody(body).setRegionTag(regionTag).build();
}
use of com.google.api.generator.gapic.model.Message in project gapic-generator-java by googleapis.
the class HttpJsonServiceStubClassComposer method setOperationSnapshotFactoryExpr.
private List<Expr> setOperationSnapshotFactoryExpr(Method protoMethod, Map<String, Message> messageTypes) {
// Generate input variables for create()
VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(protoMethod.inputType()).setName("request").build());
VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setType(protoMethod.outputType()).setName("response").build());
MethodInvocationExpr buildExpr;
List<Statement> createBody = new ArrayList<>(4);
TypeNode httpJsonOperationSnapshotType = FIXED_REST_TYPESTORE.get(HttpJsonOperationSnapshot.class.getSimpleName());
TypeNode operationSnapshotType = FIXED_TYPESTORE.get(OperationSnapshot.class.getSimpleName());
Message inputOperationMessage = messageTypes.get(protoMethod.inputType().reference().fullName());
Message outputOperationMessage = messageTypes.get(protoMethod.outputType().reference().fullName());
OperationResponse operationResponse = outputOperationMessage.operationResponse();
if (operationResponse == null) {
// AIP-151 LRO
// HttpJsonOperationSnapshot.create(response)
buildExpr = MethodInvocationExpr.builder().setStaticReferenceType(httpJsonOperationSnapshotType).setMethodName("create").setArguments(responseVarExpr).setReturnType(operationSnapshotType).build();
} else {
BiFunction<String, List<Expr>, Function<MethodInvocationExpr, MethodInvocationExpr>> methodMaker = getMethodMaker();
// Generate opName
TypeNode stringBuilderType = TypeNode.withReference(ConcreteReference.withClazz(StringBuilder.class));
VariableExpr opNameVarExpr = VariableExpr.withVariable(Variable.builder().setType(stringBuilderType).setName("opName").build());
MethodInvocationExpr getId = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.nameFieldName())).build();
Expr opNameObjectExpr = NewObjectExpr.builder().setType(stringBuilderType).setArguments(getId).build();
AssignmentExpr opNameAssignExpr = AssignmentExpr.builder().setVariableExpr(opNameVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(opNameObjectExpr).build();
createBody.add(ExprStatement.withExpr(opNameAssignExpr));
// Generate compound operation name
if (!protoMethod.isOperationPollingMethod()) {
// TODO: Change to ordered map
Map<String, String> requestFields = inputOperationMessage.operationRequestFields();
List<String> fieldAnnotationNames = new ArrayList<>(requestFields.keySet());
Collections.sort(fieldAnnotationNames);
for (String fieldName : fieldAnnotationNames) {
createBody.add(appendField(opNameVarExpr, requestVarExpr, requestFields.get(fieldName)));
}
}
// Generate check for status == done
MethodInvocationExpr getStatusExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.statusFieldName())).build();
String statusTypeName = operationResponse.statusFieldTypeName();
String statusClassName = statusTypeName.substring(statusTypeName.lastIndexOf('.') + 1);
TypeNode opType = protoMethod.hasLro() ? protoMethod.lro().responseType() : protoMethod.outputType();
TypeNode statusType = TypeNode.withReference(VaporReference.builder().setName(statusClassName).setPakkage(opType.reference().fullName()).setIsStaticImport(false).build());
VariableExpr statusDoneExpr = VariableExpr.builder().setVariable(Variable.builder().setName("DONE").setType(TypeNode.INT).build()).setStaticReferenceType(statusType).build();
MethodInvocationExpr statusEqualsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(statusDoneExpr).setMethodName("equals").setArguments(getStatusExpr).build();
// Generate return statement
// Generate getter methods from annotations
MethodInvocationExpr opNameToStringExpr = MethodInvocationExpr.builder().setExprReferenceExpr(opNameVarExpr).setMethodName("toString").build();
MethodInvocationExpr getHttpErrorStatusCodeExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.errorCodeFieldName())).build();
MethodInvocationExpr getHttpErrorMessageExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.errorMessageFieldName())).build();
MethodInvocationExpr newBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(httpJsonOperationSnapshotType).setMethodName("newBuilder").build();
newBuilderExpr = methodMaker.apply("setName", Collections.singletonList(opNameToStringExpr)).apply(newBuilderExpr);
newBuilderExpr = methodMaker.apply("setMetadata", Collections.singletonList(responseVarExpr)).apply(newBuilderExpr);
newBuilderExpr = methodMaker.apply("setDone", Collections.singletonList(statusEqualsExpr)).apply(newBuilderExpr);
newBuilderExpr = methodMaker.apply("setResponse", Collections.singletonList(responseVarExpr)).apply(newBuilderExpr);
newBuilderExpr = methodMaker.apply("setError", Arrays.asList(getHttpErrorStatusCodeExpr, getHttpErrorMessageExpr)).apply(newBuilderExpr);
buildExpr = MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(operationSnapshotType).build();
}
// Generate lambda anonymous class
return Collections.singletonList(LambdaExpr.builder().setArguments(requestVarExpr.toBuilder().setIsDecl(true).build(), responseVarExpr.toBuilder().setIsDecl(true).build()).setBody(createBody).setReturnExpr(buildExpr).build());
}
use of com.google.api.generator.gapic.model.Message in project gapic-generator-java by googleapis.
the class ServiceClientTestClassComposer method createStreamingRpcTestMethod.
@Override
protected MethodDefinition createStreamingRpcTestMethod(Service service, Method method, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
TypeNode methodOutputType = method.hasLro() ? method.lro().responseType() : method.outputType();
List<Expr> methodExprs = new ArrayList<>();
VariableExpr expectedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(methodOutputType).setName("expectedResponse").build());
Expr expectedResponseValExpr = null;
if (messageTypes.containsKey(methodOutputType.reference().fullName())) {
expectedResponseValExpr = DefaultValueComposer.createSimpleMessageBuilderValue(messageTypes.get(methodOutputType.reference().fullName()), resourceNames, messageTypes);
} else {
// Wrap this in a field so we don't have to split the helper into lots of different methods,
// or duplicate it for VariableExpr.
expectedResponseValExpr = DefaultValueComposer.createValue(Field.builder().setType(methodOutputType).setIsMessage(true).setName("expectedResponse").build());
}
methodExprs.add(AssignmentExpr.builder().setVariableExpr(expectedResponseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(expectedResponseValExpr).build());
String mockServiceVarName = getMockServiceVarName(service);
if (method.hasLro()) {
VariableExpr resultOperationVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_GRPC_TYPESTORE.get("Operation")).setName("resultOperation").build());
methodExprs.add(AssignmentExpr.builder().setVariableExpr(resultOperationVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(DefaultValueComposer.createSimpleOperationBuilderValue(String.format("%sTest", JavaStyle.toLowerCamelCase(method.name())), expectedResponseVarExpr)).build());
methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(resultOperationVarExpr).build());
} else {
methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(expectedResponseVarExpr).build());
}
// Construct the request or method arguments.
VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
Preconditions.checkNotNull(requestMessage);
Expr valExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes);
methodExprs.add(AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
List<Statement> methodStatements = new ArrayList<>();
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
// Construct the mock stream observer.
VariableExpr responseObserverVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(FIXED_GRPC_TYPESTORE.get("MockStreamObserver").reference().copyAndSetGenerics(Arrays.asList(method.outputType().reference())))).setName("responseObserver").build());
methodStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(responseObserverVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_GRPC_TYPESTORE.get("MockStreamObserver")).setIsGeneric(true).build()).build()));
methodStatements.add(EMPTY_LINE_STATEMENT);
// Build the callable variable and assign it.
VariableExpr callableVarExpr = VariableExpr.withVariable(Variable.builder().setType(getCallableType(method)).setName("callable").build());
Expr streamingCallExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("client")).setMethodName(String.format("%sCallable", JavaStyle.toLowerCamelCase(method.name()))).setReturnType(callableVarExpr.type()).build();
methodExprs.add(AssignmentExpr.builder().setVariableExpr(callableVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(streamingCallExpr).build());
// Call the streaming-variant callable method.
if (method.stream().equals(Method.Stream.SERVER)) {
methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(callableVarExpr).setMethodName("serverStreamingCall").setArguments(requestVarExpr, responseObserverVarExpr).build());
} else {
VariableExpr requestObserverVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(FIXED_TYPESTORE.get("ApiStreamObserver").reference().copyAndSetGenerics(Arrays.asList(method.inputType().reference())))).setName("requestObserver").build());
List<Expr> callableMethodArgs = new ArrayList<>();
if (!method.stream().equals(Method.Stream.BIDI) && !method.stream().equals(Method.Stream.CLIENT)) {
callableMethodArgs.add(requestVarExpr);
}
callableMethodArgs.add(responseObserverVarExpr);
methodExprs.add(AssignmentExpr.builder().setVariableExpr(requestObserverVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(callableVarExpr).setMethodName(getCallableMethodName(method)).setArguments(callableMethodArgs).setReturnType(requestObserverVarExpr.type()).build()).build());
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(requestObserverVarExpr).setMethodName("onNext").setArguments(requestVarExpr).build());
methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(requestObserverVarExpr).setMethodName("onCompleted").build());
}
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
// Check the actual responses.
VariableExpr actualResponsesVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(method.outputType().reference())).build())).setName("actualResponses").build());
Expr getFutureResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseObserverVarExpr).setMethodName("future").build();
getFutureResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(getFutureResponseExpr).setMethodName("get").setReturnType(actualResponsesVarExpr.type()).build();
methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualResponsesVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getFutureResponseExpr).build());
// Assert the size is equivalent.
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("1").build()), MethodInvocationExpr.builder().setExprReferenceExpr(actualResponsesVarExpr).setMethodName("size").setReturnType(TypeNode.INT).build()).build());
// Assert the responses are equivalent.
Expr zeroExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build());
Expr actualResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualResponsesVarExpr).setMethodName("get").setArguments(zeroExpr).build();
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedResponseVarExpr, actualResponseExpr).build());
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
String testMethodName = String.format("%sTest", JavaStyle.toLowerCamelCase(method.name()));
return MethodDefinition.builder().setAnnotations(Arrays.asList(TEST_ANNOTATION)).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName(testMethodName).setThrowsExceptions(Arrays.asList(TypeNode.withExceptionClazz(Exception.class))).setBody(methodStatements).build();
}
use of com.google.api.generator.gapic.model.Message in project gapic-generator-java by googleapis.
the class HttpRuleParser method validateAndConstructHttpBindings.
private static Set<HttpBinding> validateAndConstructHttpBindings(Set<String> paramNames, Message inputMessage, Map<String, Message> messageTypes, Map<String, String> patternSampleValues) {
ImmutableSortedSet.Builder<HttpBinding> httpBindings = ImmutableSortedSet.naturalOrder();
for (String paramName : paramNames) {
// Handle foo.bar cases by descending into the subfields.
String patternSampleValue = patternSampleValues != null ? patternSampleValues.get(paramName) : null;
String[] subFields = paramName.split("\\.");
if (inputMessage == null) {
httpBindings.add(HttpBinding.create(paramName, false, patternSampleValue));
continue;
}
Message nestedMessage = inputMessage;
for (int i = 0; i < subFields.length; i++) {
String subFieldName = subFields[i];
if (i < subFields.length - 1) {
Field field = nestedMessage.fieldMap().get(subFieldName);
nestedMessage = messageTypes.get(field.type().reference().fullName());
Preconditions.checkNotNull(nestedMessage, String.format("No containing message found for field %s with type %s", field.name(), field.type().reference().simpleName()));
} else {
if (patternSampleValues != null) {
checkHttpFieldIsValid(subFieldName, nestedMessage, false);
patternSampleValue = patternSampleValues.get(paramName);
}
Field field = nestedMessage.fieldMap().get(subFieldName);
httpBindings.add(HttpBinding.create(paramName, field.isProto3Optional(), patternSampleValue));
}
}
}
return httpBindings.build();
}
use of com.google.api.generator.gapic.model.Message in project gapic-generator-java by googleapis.
the class HttpRuleParser method parseHttpRuleHelper.
private static HttpBindings parseHttpRuleHelper(HttpRule httpRule, Optional<Message> inputMessageOpt, Map<String, Message> messageTypes) {
// Get pattern.
String pattern = getHttpVerbPattern(httpRule);
ImmutableSet.Builder<String> bindingsBuilder = ImmutableSet.builder();
bindingsBuilder.addAll(PatternParser.getPattenBindings(pattern));
if (httpRule.getAdditionalBindingsCount() > 0) {
for (HttpRule additionalRule : httpRule.getAdditionalBindingsList()) {
// TODO: save additional bindings path in HttpRuleBindings
bindingsBuilder.addAll(PatternParser.getPattenBindings(getHttpVerbPattern(additionalRule)));
}
}
Set<String> pathParamNames = bindingsBuilder.build();
Map<String, String> patternSampleValues = constructPathValuePatterns(pattern);
// TODO: support nested message fields bindings
String body = httpRule.getBody();
Set<String> bodyParamNames;
Set<String> queryParamNames;
if (!inputMessageOpt.isPresent()) {
// Must be a mixin, do not support full HttpRuleBindings for now
bodyParamNames = ImmutableSet.of();
queryParamNames = ImmutableSet.of();
} else if (Strings.isNullOrEmpty(body)) {
bodyParamNames = ImmutableSet.of();
queryParamNames = Sets.difference(inputMessageOpt.get().fieldMap().keySet(), pathParamNames);
} else if (body.equals(ASTERISK)) {
bodyParamNames = Sets.difference(inputMessageOpt.get().fieldMap().keySet(), pathParamNames);
queryParamNames = ImmutableSet.of();
} else {
bodyParamNames = ImmutableSet.of(body);
Set<String> bodyBinidngsUnion = Sets.union(bodyParamNames, pathParamNames);
queryParamNames = Sets.difference(inputMessageOpt.get().fieldMap().keySet(), bodyBinidngsUnion);
}
Message message = inputMessageOpt.orElse(null);
return HttpBindings.builder().setHttpVerb(HttpBindings.HttpVerb.valueOf(httpRule.getPatternCase().toString())).setPattern(pattern).setPathParameters(validateAndConstructHttpBindings(pathParamNames, message, messageTypes, patternSampleValues)).setQueryParameters(validateAndConstructHttpBindings(queryParamNames, message, messageTypes, null)).setBodyParameters(validateAndConstructHttpBindings(bodyParamNames, message, messageTypes, null)).setIsAsteriskBody(body.equals(ASTERISK)).build();
}
Aggregations