use of com.google.api.generator.util.TriFunction in project gapic-generator-java by googleapis.
the class AbstractServiceClientClassComposer method createRequestBuilderExpr.
@VisibleForTesting
static Expr createRequestBuilderExpr(Method method, List<MethodArgument> signature, TypeStore typeStore) {
TypeNode methodInputType = method.inputType();
Expr newBuilderExpr = MethodInvocationExpr.builder().setMethodName("newBuilder").setStaticReferenceType(methodInputType).build();
// Maintain the args' order of appearance for better determinism.
List<Field> rootFields = new ArrayList<>();
Map<Field, Trie<Field>> rootFieldToTrie = new HashMap<>();
for (MethodArgument arg : signature) {
Field rootField = arg.nestedFields().isEmpty() ? arg.field() : arg.nestedFields().get(0);
if (!rootFields.contains(rootField)) {
rootFields.add(rootField);
}
Trie<Field> updatedTrie = rootFieldToTrie.containsKey(rootField) ? rootFieldToTrie.get(rootField) : new Trie<>();
List<Field> nestedFieldsWithChild = new ArrayList<>(arg.nestedFields());
nestedFieldsWithChild.add(arg.field());
updatedTrie.insert(nestedFieldsWithChild);
rootFieldToTrie.put(rootField, updatedTrie);
}
Function<Field, Expr> parentPreprocFn = field -> (Expr) MethodInvocationExpr.builder().setStaticReferenceType(field.type()).setMethodName("newBuilder").build();
TriFunction<Field, Expr, Expr, Expr> parentPostprocFn = (field, baseRefExpr, leafProcessedExpr) -> {
boolean isRootNode = field == null;
return isRootNode ? leafProcessedExpr : MethodInvocationExpr.builder().setExprReferenceExpr(baseRefExpr).setMethodName(String.format("set%s", JavaStyle.toUpperCamelCase(field.name()))).setArguments(MethodInvocationExpr.builder().setExprReferenceExpr(leafProcessedExpr).setMethodName("build").build()).build();
};
final Map<Field, MethodArgument> fieldToMethodArg = signature.stream().collect(Collectors.toMap(a -> a.field(), a -> a));
BiFunction<Field, Expr, Expr> leafProcFn = (field, parentBaseRefExpr) -> (Expr) buildNestedSetterInvocationExpr(fieldToMethodArg.get(field), parentBaseRefExpr);
for (Field rootField : rootFields) {
newBuilderExpr = rootFieldToTrie.get(rootField).dfsTraverseAndReduce(parentPreprocFn, parentPostprocFn, leafProcFn, newBuilderExpr);
}
return MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(methodInputType).build();
}
Aggregations