use of com.google.api.generator.engine.ast.IfStatement in project gapic-generator-java by googleapis.
the class AbstractServiceStubSettingsClassComposer method createCreateStubMethod.
private MethodDefinition createCreateStubMethod(Service service, TypeStore typeStore) {
// Set up the if-statement.
List<Statement> bodyStatements = new ArrayList<>();
Expr getTransportNameExpr = MethodInvocationExpr.builder().setMethodName("getTransportChannelProvider").build();
getTransportNameExpr = MethodInvocationExpr.builder().setExprReferenceExpr(getTransportNameExpr).setMethodName("getTransportName").build();
Iterator<TypeNode> channelTypesIt = getTransportContext().transportChannelTypes().iterator();
Iterator<String> getterNameIt = getTransportContext().transportGetterNames().iterator();
Iterator<String> serivceStubClassNameIt = getTransportContext().classNames().getTransportServiceStubClassNames(service).iterator();
while (channelTypesIt.hasNext() && getterNameIt.hasNext()) {
TypeNode channelType = channelTypesIt.next();
String getterName = getterNameIt.next();
String serivceStubClassName = serivceStubClassNameIt.next();
Expr tRansportNameExpr = MethodInvocationExpr.builder().setStaticReferenceType(channelType).setMethodName(getterName).build();
Expr ifConditionExpr = MethodInvocationExpr.builder().setExprReferenceExpr(getTransportNameExpr).setMethodName("equals").setArguments(tRansportNameExpr).setReturnType(TypeNode.BOOLEAN).build();
Expr createExpr = MethodInvocationExpr.builder().setStaticReferenceType(typeStore.get(serivceStubClassName)).setMethodName("create").setArguments(ValueExpr.withValue(ThisObjectValue.withType(typeStore.get(ClassNames.getServiceStubSettingsClassName(service))))).build();
IfStatement ifStatement = IfStatement.builder().setConditionExpr(ifConditionExpr).setBody(Arrays.asList(ExprStatement.withExpr(ReturnExpr.withExpr(createExpr)))).build();
bodyStatements.add(ifStatement);
}
// Set up exception throwing.
Expr errorMessageExpr = MethodInvocationExpr.builder().setStaticReferenceType(TypeNode.STRING).setMethodName("format").setArguments(ValueExpr.withValue(StringObjectValue.withValue("Transport not supported: %s")), getTransportNameExpr).setReturnType(TypeNode.STRING).build();
TypeNode exceptionType = TypeNode.withExceptionClazz(UnsupportedOperationException.class);
Statement throwStatement = ExprStatement.withExpr(ThrowExpr.builder().setType(exceptionType).setMessageExpr(errorMessageExpr).build());
bodyStatements.add(throwStatement);
// Put the method together.
TypeNode returnType = typeStore.get(ClassNames.getServiceStubClassName(service));
AnnotationNode annotation = AnnotationNode.builder().setType(FIXED_TYPESTORE.get("BetaApi")).setDescription("A restructuring of stub classes is planned, so this may break in the future").build();
return MethodDefinition.builder().setAnnotations(Arrays.asList(annotation)).setScope(ScopeNode.PUBLIC).setReturnType(returnType).setName("createStub").setThrowsExceptions(Arrays.asList(TypeNode.withExceptionClazz(IOException.class))).setBody(bodyStatements).build();
}
use of com.google.api.generator.engine.ast.IfStatement in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createToStringListMethod.
private static MethodDefinition createToStringListMethod(TypeNode thisClassType) {
TypeNode listClassType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(thisClassType.reference())).build());
VariableExpr valuesVarExpr = VariableExpr.withVariable(Variable.builder().setName("values").setType(listClassType).build());
TypeNode listStringType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(ConcreteReference.withClazz(String.class))).build());
VariableExpr listVarExpr = VariableExpr.withVariable(Variable.builder().setName("list").setType(listStringType).build());
AssignmentExpr listAssignExpr = AssignmentExpr.builder().setVariableExpr(listVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(ArrayList.class))).setIsGeneric(true).setArguments(Arrays.asList(MethodInvocationExpr.builder().setExprReferenceExpr(valuesVarExpr).setMethodName("size").build())).build()).build();
VariableExpr valueVarExpr = VariableExpr.withVariable(Variable.builder().setName("value").setType(thisClassType).build());
// We use an equality check instead of Objects.isNull() for Java 7 compatibility.
Expr isNullCheck = RelationalOperationExpr.equalToWithExprs(valueVarExpr, ValueExpr.createNullExpr());
Statement listAddEmptyStringStatement = ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(listVarExpr).setMethodName("add").setArguments(Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue("")))).build());
Statement listAddValueStatement = ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(listVarExpr).setMethodName("add").setArguments(Arrays.asList(MethodInvocationExpr.builder().setExprReferenceExpr(valueVarExpr).setMethodName("toString").build())).build());
IfStatement ifStatement = IfStatement.builder().setConditionExpr(isNullCheck).setBody(Arrays.asList(listAddEmptyStringStatement)).setElseBody(Arrays.asList(listAddValueStatement)).build();
ForStatement forStatement = ForStatement.builder().setLocalVariableExpr(valueVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(valuesVarExpr).setBody(Arrays.asList(ifStatement)).build();
return MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(listStringType).setName("toStringList").setArguments(Arrays.asList(valuesVarExpr.toBuilder().setIsDecl(true).build())).setBody(Arrays.asList(ExprStatement.withExpr(listAssignExpr), forStatement)).setReturnExpr(listVarExpr).build();
}
use of com.google.api.generator.engine.ast.IfStatement in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createGetFieldValuesMapMethod.
private static MethodDefinition createGetFieldValuesMapMethod(ResourceName resourceName, TypeNode thisClassType, Map<String, VariableExpr> patternTokenVarExprs, List<List<String>> tokenHierarchies) {
Reference strRef = TypeNode.STRING.reference();
TypeNode mapBuilderType = TypeNode.withReference(ConcreteReference.builder().setClazz(ImmutableMap.Builder.class).setGenerics(Arrays.asList(strRef, strRef)).build());
VariableExpr fieldMapBuilderVarExpr = VariableExpr.withVariable(Variable.builder().setName("fieldMapBuilder").setType(mapBuilderType).build());
AssignmentExpr builderAssignExpr = AssignmentExpr.builder().setVariableExpr(fieldMapBuilderVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("builder").setReturnType(mapBuilderType).build()).build();
// Special-cased PubSub handling.
List<List<String>> processedTokenHierarchies = tokenHierarchies.stream().filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)).collect(Collectors.toList());
// Innermost if-blocks.
List<Statement> tokenIfStatements = new ArrayList<>();
for (String token : getTokenSet(processedTokenHierarchies)) {
VariableExpr tokenVarExpr = patternTokenVarExprs.get(token);
Preconditions.checkNotNull(tokenVarExpr, String.format("No variable found for %s among %s", token, patternTokenVarExprs.keySet()));
StringObjectValue tokenStrVal = StringObjectValue.withValue(token);
MethodInvocationExpr putExpr = MethodInvocationExpr.builder().setExprReferenceExpr(fieldMapBuilderVarExpr).setMethodName("put").setArguments(ValueExpr.withValue(tokenStrVal), tokenVarExpr).build();
Expr notNullCheckExpr = RelationalOperationExpr.notEqualToWithExprs(tokenVarExpr, ValueExpr.createNullExpr());
tokenIfStatements.add(IfStatement.builder().setConditionExpr(notNullCheckExpr).setBody(Arrays.asList(ExprStatement.withExpr(putExpr))).build());
}
// Put the innermost if-statements and assignment expressions together.
VariableExpr fieldValuesMapVarExpr = FIXED_CLASS_VARS.get("fieldValuesMap");
AssignmentExpr fieldValuesMapAssignExpr = AssignmentExpr.builder().setVariableExpr(fieldValuesMapVarExpr).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(fieldMapBuilderVarExpr).setMethodName("build").setReturnType(fieldValuesMapVarExpr.type()).build()).build();
List<Statement> middleIfBlockStatements = new ArrayList<>();
middleIfBlockStatements.add(ExprStatement.withExpr(builderAssignExpr));
middleIfBlockStatements.addAll(tokenIfStatements);
middleIfBlockStatements.add(ExprStatement.withExpr(fieldValuesMapAssignExpr));
// Middle if-block, i.e. `if (fieldValuesMap == null)`.
Expr fieldValuesMapNullCheckExpr = RelationalOperationExpr.equalToWithExprs(fieldValuesMapVarExpr, ValueExpr.createNullExpr());
IfStatement fieldValuesMapIfStatement = IfStatement.builder().setConditionExpr(fieldValuesMapNullCheckExpr).setBody(middleIfBlockStatements).build();
// Outer if-block.
IfStatement outerIfStatement = IfStatement.builder().setConditionExpr(fieldValuesMapNullCheckExpr).setBody(Arrays.asList(SynchronizedStatement.builder().setLock(ThisObjectValue.withType(thisClassType)).setBody(Arrays.asList(fieldValuesMapIfStatement)).build())).build();
// Put the method together.
TypeNode mapStringType = fieldValuesMapVarExpr.type();
return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(mapStringType).setName("getFieldValuesMap").setBody(Arrays.asList(outerIfStatement)).setReturnExpr(fieldValuesMapVarExpr).build();
}
use of com.google.api.generator.engine.ast.IfStatement in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createEqualsMethod.
private static MethodDefinition createEqualsMethod(ResourceName resourceName, List<List<String>> tokenHierarchies, TypeStore typeStore) {
// Create method definition variables.
Variable oVariable = Variable.builder().setType(TypeNode.withReference(javaObjectReference)).setName("o").build();
VariableExpr argVarExpr = VariableExpr.builder().setIsDecl(false).setVariable(oVariable).build();
TypeNode thisClassType = typeStore.get(getThisClassName(resourceName));
ValueExpr thisValueExpr = ValueExpr.withValue(ThisObjectValue.withType(thisClassType));
ValueExpr trueValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.BOOLEAN).setValue("true").build());
// Create first if statement's return expression
ReturnExpr returnTrueExpr = ReturnExpr.withExpr(trueValueExpr);
// Create second if statement's condition expression
RelationalOperationExpr oEqualsThisExpr = RelationalOperationExpr.equalToWithExprs(argVarExpr, thisValueExpr);
RelationalOperationExpr oNotEqualsNullExpr = RelationalOperationExpr.notEqualToWithExprs(argVarExpr, ValueExpr.createNullExpr());
MethodInvocationExpr getClassMethodInvocationExpr = MethodInvocationExpr.builder().setMethodName("getClass").build();
RelationalOperationExpr getClassEqualsExpr = RelationalOperationExpr.equalToWithExprs(getClassMethodInvocationExpr, getClassMethodInvocationExpr.toBuilder().setExprReferenceExpr(argVarExpr).build());
LogicalOperationExpr orLogicalExpr = LogicalOperationExpr.logicalOrWithExprs(oNotEqualsNullExpr, getClassEqualsExpr);
// Create second if statement's body assignment expression.
Variable thatVariable = Variable.builder().setName("that").setType(thisClassType).build();
VariableExpr thatVariableExpr = VariableExpr.builder().setIsDecl(false).setVariable(thatVariable).build();
CastExpr oCastExpr = CastExpr.builder().setExpr(argVarExpr).setType(thisClassType).build();
AssignmentExpr thatAssignmentExpr = AssignmentExpr.builder().setVariableExpr(thatVariableExpr.toBuilder().setIsDecl(true).build()).setValueExpr(oCastExpr).build();
// PubSub special-case handling - exclude _deleted-topic_.
List<List<String>> processedTokenHierarchies = tokenHierarchies.stream().filter(ts -> !ts.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)).collect(Collectors.toList());
// Create return expression in the second if statement's body.
Set<String> tokenSet = getTokenSet(processedTokenHierarchies);
Iterator<String> itToken = tokenSet.iterator();
Expr curTokenExpr = createObjectsEqualsForTokenMethodExpr(thisValueExpr, thatVariableExpr, Variable.builder().setType(TypeNode.STRING).setName(JavaStyle.toLowerCamelCase(itToken.next())).build());
while (itToken.hasNext()) {
Expr nextTokenExpr = createObjectsEqualsForTokenMethodExpr(thisValueExpr, thatVariableExpr, Variable.builder().setType(TypeNode.STRING).setName(JavaStyle.toLowerCamelCase(itToken.next())).build());
curTokenExpr = LogicalOperationExpr.logicalAndWithExprs(curTokenExpr, nextTokenExpr);
}
ReturnExpr secondIfReturnExpr = ReturnExpr.withExpr(curTokenExpr);
// Code: if (o == this) { return true;}
IfStatement firstIfStatement = IfStatement.builder().setConditionExpr(oEqualsThisExpr).setBody(Arrays.asList(ExprStatement.withExpr(returnTrueExpr))).build();
// Code: if (o != null || getClass() == o.getClass()) { FoobarName that = ((FoobarName) o);
// return ..}
IfStatement secondIfStatement = IfStatement.builder().setConditionExpr(orLogicalExpr).setBody(Arrays.asList(ExprStatement.withExpr(thatAssignmentExpr), ExprStatement.withExpr(secondIfReturnExpr))).build();
// Create method's return expression.
ValueExpr falseValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.BOOLEAN).setValue("false").build());
return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setArguments(argVarExpr.toBuilder().setIsDecl(true).build()).setReturnType(TypeNode.BOOLEAN).setName("equals").setReturnExpr(falseValueExpr).setBody(Arrays.asList(firstIfStatement, secondIfStatement)).build();
}
use of com.google.api.generator.engine.ast.IfStatement 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();
}
Aggregations