use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.
the class AbstractServiceClientClassComposer method createNestedPagingClasses.
private static List<ClassDefinition> createNestedPagingClasses(Service service, Map<String, Message> messageTypes, TypeStore typeStore) {
List<ClassDefinition> nestedClasses = new ArrayList<>();
for (Method method : service.methods()) {
if (!method.isPaged()) {
continue;
}
// 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();
nestedClasses.add(createNestedRpcPagedResponseClass(method, repeatedResponseType, messageTypes, typeStore));
nestedClasses.add(createNestedRpcPageClass(method, repeatedResponseType, messageTypes, typeStore));
nestedClasses.add(createNestedRpcFixedSizeCollectionClass(method, repeatedResponseType, messageTypes, typeStore));
}
return nestedClasses;
}
use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.
the class DefaultValueComposer method createSimpleMessageBuilderValue.
public static Expr createSimpleMessageBuilderValue(Message message, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes, Map<String, String> valuePatterns) {
MethodInvocationExpr builderExpr = MethodInvocationExpr.builder().setStaticReferenceType(message.type()).setMethodName("newBuilder").build();
for (Field field : message.fields()) {
if (// Avoid colliding fields.
field.isContainedInOneof() || ((field.isMessage() || (field.isEnum() && // Avoid importing unparsed messages.
message.operationResponse() == null)) && !field.isRepeated() && !messageTypes.containsKey(field.type().reference().fullName()))) {
continue;
}
String setterMethodNamePattern = "set%s";
if (field.isRepeated()) {
setterMethodNamePattern = field.isMap() ? "putAll%s" : "addAll%s";
}
Expr defaultExpr = null;
if (field.hasResourceReference() && resourceNames.get(field.resourceReference().resourceTypeString()) != null) {
defaultExpr = createResourceHelperValue(resourceNames.get(field.resourceReference().resourceTypeString()), field.resourceReference().isChildType(), resourceNames.values().stream().collect(Collectors.toList()), message.name(), /* allowAnonResourceNameClass = */
false);
defaultExpr = MethodInvocationExpr.builder().setExprReferenceExpr(defaultExpr).setMethodName("toString").setReturnType(TypeNode.STRING).build();
} else {
if (message.operationResponse() != null) {
if (field.name().equals(message.operationResponse().statusFieldName())) {
String statusTypeName = message.operationResponse().statusFieldTypeName();
String statusClassName = statusTypeName.substring(statusTypeName.lastIndexOf('.') + 1);
TypeNode statusType = TypeNode.withReference(VaporReference.builder().setName(statusClassName).setPakkage(message.type().reference().fullName()).setIsStaticImport(false).build());
defaultExpr = VariableExpr.builder().setVariable(Variable.builder().setName("DONE").setType(statusType).build()).setStaticReferenceType(statusType).build();
} else if (field.name().equals(message.operationResponse().errorCodeFieldName())) {
defaultExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(field.type()).setValue("0").build());
}
}
if (defaultExpr == null) {
defaultExpr = createValue(field, true, resourceNames, messageTypes, valuePatterns);
}
}
builderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(builderExpr).setMethodName(String.format(setterMethodNamePattern, JavaStyle.toUpperCamelCase(field.name()))).setArguments(defaultExpr).build();
}
return MethodInvocationExpr.builder().setExprReferenceExpr(builderExpr).setMethodName("build").setReturnType(message.type()).build();
}
use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.
the class ServiceClientTestClassComposer method constructRpcTestCheckerLogic.
@Override
protected List<Statement> constructRpcTestCheckerLogic(Method method, Service service, boolean isRequestArg, Map<String, VariableExpr> classMemberVarExprs, VariableExpr requestVarExpr, Message requestMessage, List<VariableExpr> argExprs) {
List<Expr> methodExprs = new ArrayList<>();
List<Statement> methodStatements = new ArrayList<>();
// Construct the request checker logic.
VariableExpr actualRequestsVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(ConcreteReference.withClazz(AbstractMessage.class))).build())).setName("actualRequests").build());
methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualRequestsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(getMockServiceVarName(service))).setMethodName("getRequests").setReturnType(actualRequestsVarExpr.type()).build()).build());
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(actualRequestsVarExpr).setMethodName("size").build()).build());
VariableExpr actualRequestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("actualRequest").build());
Expr getFirstRequestExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualRequestsVarExpr).setMethodName("get").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build())).setReturnType(FIXED_TYPESTORE.get("AbstractMessage")).build();
getFirstRequestExpr = CastExpr.builder().setType(method.inputType()).setExpr(getFirstRequestExpr).build();
methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualRequestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getFirstRequestExpr).build());
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
// Assert field equality.
if (isRequestArg) {
// TODO(miraleung): Replace these with a simple request object equals?
Preconditions.checkNotNull(requestVarExpr);
Preconditions.checkNotNull(requestMessage);
for (Field field : requestMessage.fields()) {
String fieldGetterMethodNamePatternTemp = "get%s";
if (field.isRepeated()) {
fieldGetterMethodNamePatternTemp = field.isMap() ? "get%sMap" : "get%sList";
}
final String fieldGetterMethodNamePattern = fieldGetterMethodNamePatternTemp;
Function<VariableExpr, Expr> checkExprFn = v -> MethodInvocationExpr.builder().setExprReferenceExpr(v).setMethodName(String.format(fieldGetterMethodNamePattern, JavaStyle.toUpperCamelCase(field.name()))).build();
Expr expectedFieldExpr = checkExprFn.apply(requestVarExpr);
Expr actualFieldExpr = checkExprFn.apply(actualRequestVarExpr);
List<Expr> assertEqualsArguments = new ArrayList<>();
assertEqualsArguments.add(expectedFieldExpr);
assertEqualsArguments.add(actualFieldExpr);
if (TypeNode.isFloatingPointType(field.type())) {
boolean isFloat = field.type().equals(TypeNode.FLOAT);
assertEqualsArguments.add(ValueExpr.withValue(PrimitiveValue.builder().setType(isFloat ? TypeNode.FLOAT : TypeNode.DOUBLE).setValue(String.format("0.0001%s", isFloat ? "f" : "")).build()));
}
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(assertEqualsArguments).build());
}
} else {
for (VariableExpr argVarExpr : argExprs) {
Variable variable = argVarExpr.variable();
String fieldGetterMethodNamePattern = "get%s";
if (LIST_TYPE.isSupertypeOrEquals(variable.type())) {
fieldGetterMethodNamePattern = "get%sList";
} else if (MAP_TYPE.isSupertypeOrEquals(variable.type())) {
fieldGetterMethodNamePattern = "get%sMap";
}
Expr actualFieldExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualRequestVarExpr).setMethodName(String.format(fieldGetterMethodNamePattern, JavaStyle.toUpperCamelCase(variable.identifier().name()))).build();
Expr expectedFieldExpr = argVarExpr;
if (RESOURCE_NAME_TYPE.isSupertypeOrEquals(argVarExpr.type())) {
expectedFieldExpr = MethodInvocationExpr.builder().setExprReferenceExpr(argVarExpr).setMethodName("toString").build();
}
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedFieldExpr, actualFieldExpr).build());
}
}
// Assert header equality.
Expr headerKeyExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ApiClientHeaderProvider")).setMethodName("getDefaultApiClientHeaderKey").build();
Expr headerPatternExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_GRPC_TYPESTORE.get("GaxGrpcProperties")).setMethodName("getDefaultApiClientHeaderPattern").build();
Expr headerSentExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("channelProvider")).setMethodName("isHeaderSent").setArguments(headerKeyExpr, headerPatternExpr).build();
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertTrue").setArguments(headerSentExpr).build());
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
return methodStatements;
}
use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composePagedCallableSample.
private static Sample composePagedCallableSample(Method method, VariableExpr clientVarExpr, VariableExpr requestVarExpr, Map<String, Message> messageTypes) {
// 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();
// Assign future variable by invoking paged callable method.
// e.g. ApiFuture<PagedExpandPagedResponse> future =
// echoClient.pagedExpandCallable().futureCall(request);
VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setName("response").setType(method.outputType()).build());
MethodInvocationExpr pagedCallableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(String.format("%sCallable", method.name()))).build();
pagedCallableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(pagedCallableMethodInvocationExpr).setMethodName("call").setArguments(requestVarExpr).setReturnType(method.outputType()).build();
AssignmentExpr responseAssignmentExpr = AssignmentExpr.builder().setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(pagedCallableMethodInvocationExpr).build();
List<Statement> whileBodyStatements = new ArrayList<>();
whileBodyStatements.add(ExprStatement.withExpr(responseAssignmentExpr));
// For-loop on repeated response elements.
// e.g. for (EchoResponse element : response.getResponsesList()) {
// // doThingsWith(element);
// }
VariableExpr repeatedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setName("element").setType(repeatedResponseType).build());
MethodInvocationExpr getResponseListMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName("getResponsesList").build();
ForStatement responseForStatements = ForStatement.builder().setLocalVariableExpr(repeatedResponseVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(getResponseListMethodInvocationExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("doThingsWith(element);")))).build();
whileBodyStatements.add(responseForStatements);
// Create nextPageToken variable expression and assign it with a value by invoking
// getNextPageToken method.
// e.g. String nextPageToken = response.getNextPageToken();
VariableExpr nextPageTokenVarExpr = VariableExpr.withVariable(Variable.builder().setName("nextPageToken").setType(TypeNode.STRING).build());
MethodInvocationExpr getNextPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName("getNextPageToken").setReturnType(TypeNode.STRING).build();
AssignmentExpr nextPageTokenAssignmentExpr = AssignmentExpr.builder().setVariableExpr(nextPageTokenVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getNextPageTokenMethodInvocationExpr).build();
whileBodyStatements.add(ExprStatement.withExpr(nextPageTokenAssignmentExpr));
// If nextPageToken variable expression is not null or empty, assign request variable with a
// value by invoking setPageToken method.
// if (!Strings.isNullOrEmpty(nextPageToken)) {
// request = request.toBuilder().setPageToken(nextPageToken).build();
// } else {
// break;
// }
Expr conditionExpr = UnaryOperationExpr.logicalNotWithExpr(MethodInvocationExpr.builder().setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Strings.class))).setMethodName("isNullOrEmpty").setArguments(nextPageTokenVarExpr).setReturnType(TypeNode.BOOLEAN).build());
MethodInvocationExpr setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr).setMethodName("toBuilder").build();
setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(setPageTokenMethodInvocationExpr).setMethodName("setPageToken").setArguments(nextPageTokenVarExpr).build();
setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(setPageTokenMethodInvocationExpr).setMethodName("build").setReturnType(method.inputType()).build();
AssignmentExpr requestReAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr).setValueExpr(setPageTokenMethodInvocationExpr).build();
IfStatement nextPageTokenIfStatement = IfStatement.builder().setConditionExpr(conditionExpr).setBody(Arrays.asList(ExprStatement.withExpr(requestReAssignmentExpr))).setElseBody(Arrays.asList(BreakStatement.create())).build();
whileBodyStatements.add(nextPageTokenIfStatement);
WhileStatement pagedWhileStatement = WhileStatement.builder().setConditionExpr(ValueExpr.withValue(PrimitiveValue.builder().setValue("true").setType(TypeNode.BOOLEAN).build())).setBody(whileBodyStatements).build();
RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setOverloadDisambiguation("Paged").setIsAsynchronous(true).build();
return Sample.builder().setBody(Arrays.asList(pagedWhileStatement)).setRegionTag(regionTag).build();
}
use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.
the class ServiceClientMethodSampleComposer method composePagedSample.
static Sample composePagedSample(Method method, VariableExpr clientVarExpr, List<VariableExpr> rpcMethodArgVarExprs, List<Expr> bodyExprs, Map<String, Message> messageTypes) {
// Find the repeated field.
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Preconditions.checkNotNull(methodOutputMessage, "Output message %s not found, keys: ", method.outputType().reference().fullName(), messageTypes.keySet().toString());
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();
// For loop paged response item on iterateAll method.
// e.g. for (LogEntry element : loggingServiceV2Client.ListLogs(parent).iterateAll()) {
// //doThingsWith(element);
// }
MethodInvocationExpr clientMethodIterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(method.name())).setArguments(rpcMethodArgVarExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).build();
clientMethodIterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientMethodIterateAllExpr).setMethodName("iterateAll").setReturnType(repeatedResponseType).build();
ForStatement loopIteratorStatement = ForStatement.builder().setLocalVariableExpr(VariableExpr.builder().setVariable(Variable.builder().setName("element").setType(repeatedResponseType).build()).setIsDecl(true).build()).setCollectionExpr(clientMethodIterateAllExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("doThingsWith(element);")))).build();
List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
bodyExprs.clear();
bodyStatements.add(loopIteratorStatement);
RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setOverloadDisambiguation(SampleComposerUtil.createOverloadDisambiguation(rpcMethodArgVarExprs)).build();
return Sample.builder().setBody(bodyStatements).setRegionTag(regionTag).build();
}
Aggregations