use of com.google.api.generator.gapic.model.ResourceName 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.gapic.model.ResourceName 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.gapic.model.ResourceName in project gapic-generator-java by googleapis.
the class DefaultValueComposer method createResourceHelperValue.
@VisibleForTesting
static Expr createResourceHelperValue(ResourceName resourceName, boolean isChildType, List<ResourceName> resnames, String fieldOrMessageName, boolean allowAnonResourceNameClass) {
if (isChildType) {
resourceName = findParentResource(resourceName, resnames).orElse(resourceName);
}
if (resourceName.isOnlyWildcard()) {
List<ResourceName> unexaminedResnames = new ArrayList<>(resnames);
for (ResourceName resname : resnames) {
unexaminedResnames.remove(resname);
if (!resname.isOnlyWildcard()) {
return createResourceHelperValue(resname, false, unexaminedResnames, fieldOrMessageName);
}
}
return allowAnonResourceNameClass ? createAnonymousResourceNameClassValue(fieldOrMessageName) : ValueExpr.withValue(StringObjectValue.withValue(String.format("%s%s", fieldOrMessageName, fieldOrMessageName.hashCode())));
}
// The cost tradeoffs of new ctors versus distinct() don't really matter here, since this list
// will usually have a very small number of elements.
List<String> patterns = new ArrayList<>(new HashSet<>(resourceName.patterns()));
boolean containsOnlyDeletedTopic = patterns.size() == 1 && patterns.get(0).equals(ResourceNameConstants.DELETED_TOPIC_LITERAL);
String ofMethodName = "of";
List<String> patternPlaceholderTokens = new ArrayList<>();
if (containsOnlyDeletedTopic) {
ofMethodName = "ofDeletedTopic";
} else {
for (String pattern : resourceName.patterns()) {
if (pattern.equals(ResourceNameConstants.WILDCARD_PATTERN) || pattern.equals(ResourceNameConstants.DELETED_TOPIC_LITERAL)) {
continue;
}
patternPlaceholderTokens.addAll(ResourceNameTokenizer.parseTokenHierarchy(Arrays.asList(pattern)).get(0));
break;
}
}
boolean hasOnePattern = resourceName.patterns().size() == 1;
if (!hasOnePattern) {
ofMethodName = String.format("of%sName", String.join("", patternPlaceholderTokens.stream().map(s -> JavaStyle.toUpperCamelCase(s)).collect(Collectors.toList())));
}
TypeNode resourceNameJavaType = resourceName.type();
List<Expr> argExprs = patternPlaceholderTokens.stream().map(s -> ValueExpr.withValue(StringObjectValue.withValue(String.format("[%s]", s.toUpperCase())))).collect(Collectors.toList());
return MethodInvocationExpr.builder().setStaticReferenceType(resourceNameJavaType).setMethodName(ofMethodName).setArguments(argExprs).setReturnType(resourceNameJavaType).build();
}
use of com.google.api.generator.gapic.model.ResourceName in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createBuilderCreatorMethods.
private static List<MethodDefinition> createBuilderCreatorMethods(ResourceName resourceName, List<List<String>> tokenHierarchies, TypeStore typeStore) {
List<MethodDefinition> javaMethods = new ArrayList<>();
String newMethodNameFormat = "new%s";
AnnotationNode betaAnnotation = AnnotationNode.builder().setType(FIXED_TYPESTORE.get("BetaApi")).setDescription("The per-pattern Builders are not stable yet and may be changed in the future.").build();
List<AnnotationNode> annotations = Arrays.asList(betaAnnotation);
// Variation example: newProjectLocationAutoscalingPolicyBuilder().
for (int i = 0; i < tokenHierarchies.size(); i++) {
// PubSub special-case handling.
if (tokenHierarchies.get(i).contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) {
continue;
}
final TypeNode returnType = getBuilderType(typeStore, tokenHierarchies, i);
final Expr returnExpr = NewObjectExpr.withType(returnType);
Function<String, MethodDefinition.Builder> methodDefStarterFn = methodName -> MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(returnType).setName(methodName).setReturnExpr(returnExpr);
String variantName = getBuilderTypeName(tokenHierarchies, i);
javaMethods.add(methodDefStarterFn.apply(String.format(newMethodNameFormat, variantName)).setAnnotations(i == 0 ? Collections.emptyList() : annotations).build());
if (i == 0 && tokenHierarchies.size() > 1) {
// Create another builder creator method, but with the per-variant name.
javaMethods.add(methodDefStarterFn.apply(String.format(newMethodNameFormat, getBuilderTypeName(tokenHierarchies.get(i)))).setAnnotations(annotations).build());
}
}
// TODO(miraleung, v2): It seems weird that we currently generate a toBuilder method only for
// the default class, and none for the Builder variants.
TypeNode toBuilderReturnType = getBuilderType(typeStore, tokenHierarchies, 0);
TypeNode thisClassType = typeStore.get(getThisClassName(resourceName));
javaMethods.add(MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(toBuilderReturnType).setName("toBuilder").setReturnExpr(NewObjectExpr.builder().setType(toBuilderReturnType).setArguments(Arrays.asList(ValueExpr.withValue(ThisObjectValue.withType(thisClassType)))).build()).build());
return javaMethods;
}
use of com.google.api.generator.gapic.model.ResourceName in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composeLroCallableMethod.
// Compose sample code for the method where it is CallableMethodKind.LRO.
public static Sample composeLroCallableMethod(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);
// Create OperationFuture variable expr with invoking client's LRO callable method.
// e.g. OperationFuture<Empty, WaitMetadata> future =
// echoClient.waitOperationCallable().futureCall(request);
TypeNode operationFutureType = TypeNode.withReference(ConcreteReference.builder().setClazz(OperationFuture.class).setGenerics(method.lro().responseType().reference(), method.lro().metadataType().reference()).build());
VariableExpr operationFutureVarExpr = VariableExpr.withVariable(Variable.builder().setName("future").setType(operationFutureType).build());
MethodInvocationExpr rpcMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(String.format("%sOperationCallable", JavaStyle.toLowerCamelCase(method.name()))).build();
rpcMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcMethodInvocationExpr).setMethodName("futureCall").setArguments(requestVarExpr).setReturnType(operationFutureType).build();
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(operationFutureVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(rpcMethodInvocationExpr).build());
List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
bodyExprs.clear();
// Add a line comment
bodyStatements.add(CommentStatement.withComment(LineComment.withComment("Do something.")));
// Assign response variable with invoking client's LRO method.
// e.g. if return void, future.get(); or,
// e.g. if return other type, WaitResponse response = future.get();
MethodInvocationExpr futureGetMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(operationFutureVarExpr).setMethodName("get").setReturnType(method.lro().responseType()).build();
boolean returnsVoid = method.lro().responseType().isProtoEmptyType();
if (returnsVoid) {
bodyExprs.add(futureGetMethodExpr);
} else {
VariableExpr responseVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("response").setType(method.lro().responseType()).build()).setIsDecl(true).build();
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(responseVarExpr).setValueExpr(futureGetMethodExpr).build());
}
bodyStatements.addAll(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
bodyExprs.clear();
RegionTag regionTag = RegionTag.builder().setServiceName(clientType.reference().name()).setRpcName(method.name()).setIsAsynchronous(true).setOverloadDisambiguation("LRO").build();
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