Search in sources :

Example 1 with InitCodeNode

use of com.google.api.codegen.metacode.InitCodeNode in project toolkit by googleapis.

the class TestCaseTransformer method createMockResponseAdditionalSubTrees.

private List<InitCodeNode> createMockResponseAdditionalSubTrees(MethodContext context) {
    List<InitCodeNode> additionalSubTrees = new ArrayList<>();
    if (context.getMethodConfig().isPageStreaming()) {
        // Initialize one resource element if it is page-streaming.
        PageStreamingConfig config = context.getMethodConfig().getPageStreaming();
        FieldModel field = config.getResourcesField();
        InitCodeNode initCodeNode;
        if (field.isRepeated()) {
            if (field.isMap()) {
                initCodeNode = InitCodeNode.create(field.getNameAsParameter());
            } else {
                initCodeNode = InitCodeNode.createSingletonList(config.getResourcesFieldName());
            }
        } else {
            initCodeNode = InitCodeNode.create(field.getNameAsParameter());
        }
        if (config.getResourcesField().isMap()) {
            initCodeNode = InitCodeNode.createWithChildren(config.getResourcesField().getNameAsParameter(), MapInitLine, initCodeNode);
        }
        additionalSubTrees.add(initCodeNode);
        // Set the initial value of the page token to empty, in order to indicate that no more pages
        // are available
        String responseTokenName = config.getResponseTokenField().getSimpleName();
        additionalSubTrees.add(InitCodeNode.createWithValue(responseTokenName, InitValueConfig.createWithValue(InitValue.createLiteral(""))));
    }
    if (context.getMethodConfig().isBatching()) {
        // Initialize one batching element if it is batching.
        BatchingConfig config = context.getMethodConfig().getBatching();
        if (config.getSubresponseField() != null) {
            String subResponseFieldName = config.getSubresponseField().getSimpleName();
            additionalSubTrees.add(InitCodeNode.createSingletonList(subResponseFieldName));
        }
    }
    if (context.getMethodConfig().isGrpcStreaming()) {
        GrpcStreamingConfig streamingConfig = context.getMethodConfig().getGrpcStreaming();
        if (streamingConfig.hasResourceField()) {
            String resourceFieldName = streamingConfig.getResourcesField().getSimpleName();
            additionalSubTrees.add(InitCodeNode.createSingletonList(resourceFieldName));
        }
    }
    return additionalSubTrees;
}
Also used : InitCodeNode(com.google.api.codegen.metacode.InitCodeNode) PageStreamingConfig(com.google.api.codegen.config.PageStreamingConfig) ArrayList(java.util.ArrayList) BatchingConfig(com.google.api.codegen.config.BatchingConfig) FieldModel(com.google.api.codegen.config.FieldModel) GrpcStreamingConfig(com.google.api.codegen.config.GrpcStreamingConfig)

Example 2 with InitCodeNode

use of com.google.api.codegen.metacode.InitCodeNode in project toolkit by googleapis.

the class InitCodeTransformer method getFieldSettings.

private List<FieldSettingView> getFieldSettings(MethodContext context, Iterable<InitCodeNode> childItems) {
    SurfaceNamer namer = context.getNamer();
    List<FieldSettingView> allSettings = new ArrayList<>();
    for (InitCodeNode item : childItems) {
        FieldSettingView.Builder fieldSetting = FieldSettingView.newBuilder();
        FieldConfig fieldConfig = item.getFieldConfig();
        if (context.getFeatureConfig().useResourceNameProtoAccessor(fieldConfig)) {
            fieldSetting.fieldSetFunction(namer.getResourceNameFieldSetFunctionName(fieldConfig.getMessageFieldConfig()));
        } else {
            fieldSetting.fieldSetFunction(namer.getFieldSetFunctionName(item.getType(), Name.anyLower(item.getVarName())));
        }
        fieldSetting.fieldAddFunction(namer.getFieldAddFunctionName(item.getType(), Name.anyLower(item.getVarName())));
        fieldSetting.fieldGetFunction(namer.getFieldGetFunctionName(item.getType(), Name.anyLower(item.getVarName())));
        fieldSetting.identifier(getVariableName(context, item));
        fieldSetting.initCodeLine(generateSurfaceInitCodeLine(context, item, allSettings.isEmpty(), false));
        fieldSetting.fieldName(context.getNamer().publicFieldName(Name.anyLower(item.getVarName())));
        fieldSetting.isMap(item.getType().isMap());
        fieldSetting.isArray(!item.getType().isMap() && item.getType().isRepeated());
        fieldSetting.elementTypeName(context.getTypeTable().getFullNameFor(item.getType()));
        if (item.getOneofConfig() != null) {
            fieldSetting.oneofConfig(OneofConfigView.newBuilder().groupName(namer.publicFieldName(item.getOneofConfig().groupName())).variantType(namer.getOneofVariantTypeName(item.getOneofConfig())).build());
        }
        fieldSetting.required(isRequired(fieldConfig, context));
        String formatMethodName = "";
        String transformParamFunctionName = "";
        // If resource name converters should only be used in the sample, we need to convert the
        // resource name to a string before passing it or setting it on the next thing
        boolean needsConversion = context.getFeatureConfig().useResourceNameConvertersInSampleOnly(context, fieldConfig);
        // flattened method implementation when setting fields on the proto object).
        if (context.getFeatureConfig().useResourceNameConverters(fieldConfig) && !context.isFlattenedMethodContext()) {
            needsConversion = true;
        }
        if (needsConversion) {
            if (fieldConfig.getField().isRepeated()) {
                // TODO (https://github.com/googleapis/toolkit/issues/1806) support repeated one-ofs
                transformParamFunctionName = namer.getResourceTypeFormatListMethodName(context.getTypeTable(), fieldConfig);
            } else {
                formatMethodName = namer.getResourceNameFormatMethodName();
            }
        }
        fieldSetting.transformParamFunctionName(transformParamFunctionName);
        fieldSetting.formatMethodName(formatMethodName);
        allSettings.add(fieldSetting.build());
    }
    return allSettings;
}
Also used : FieldSettingView(com.google.api.codegen.viewmodel.FieldSettingView) InitCodeNode(com.google.api.codegen.metacode.InitCodeNode) FieldConfig(com.google.api.codegen.config.FieldConfig) ArrayList(java.util.ArrayList)

Example 3 with InitCodeNode

use of com.google.api.codegen.metacode.InitCodeNode in project toolkit by googleapis.

the class InitCodeTransformer method buildInitCodeView.

/**
 * Transform {@code InitCodeNode}s into {@code InitCodeView}.
 *
 * @param orderedItems These nodes are converted into request-initialization code. It contains all
 *     initializations regardless of whether they are parameters to the sample function. The
 *     initialization is "shallow": children nodes are not initialized. If children nodes should
 *     also be initialized, callers must also include them in the list.
 * @param libArguments Used by samples for flattened client lib methods. These nodes contain
 *     values that become arguments to the method.
 * @param sampleFuncParams Subset of {@code orderedItems} containing only items that are function
 *     parameters. Unlike {@code orderedItems}, the {@code sampleFuncParams} are "deep". The init
 *     code for these nodes and their children are commented out so that they don't clobber the
 *     function arguments.
 */
private InitCodeView buildInitCodeView(MethodContext context, List<InitCodeNode> orderedItems, List<InitCodeNode> libArguments, List<InitCodeNode> sampleFuncParams) {
    ImportTypeTable typeTable = context.getTypeTable();
    SurfaceNamer namer = context.getNamer();
    // Initialize the type table with the apiClassName since each sample will be using the
    // apiClass.
    typeTable.getAndSaveNicknameFor(namer.getFullyQualifiedApiWrapperClassName(context.getInterfaceConfig()));
    List<FieldSettingView> fieldSettings = getFieldSettings(context, libArguments);
    List<FieldSettingView> optionalFieldSettings = fieldSettings.stream().filter(f -> !f.required()).collect(Collectors.toList());
    List<FieldSettingView> requiredFieldSettings = fieldSettings.stream().filter(FieldSettingView::required).collect(Collectors.toList());
    List<SampleFunctionParameterView> argDefaultParams = new ArrayList<>();
    List<InitCodeLineView> argDefaultLines = new ArrayList<>();
    for (InitCodeNode param : sampleFuncParams) {
        List<InitCodeNode> paramInits = param.listInInitializationOrder();
        argDefaultLines.addAll(generateSurfaceInitCodeLines(context, paramInits));
        // The param itself is always at the end.
        InitCodeLineView initLine = argDefaultLines.get(argDefaultLines.size() - 1);
        checkArgument(initLine.lineType() == InitCodeLineType.SimpleInitLine, "Standalone samples only support primitive types for CLI arguments for now.");
        SimpleInitCodeLineView simpleInitLine = (SimpleInitCodeLineView) initLine;
        argDefaultParams.add(SampleFunctionParameterView.newBuilder().initValue(simpleInitLine.initValue()).identifier(simpleInitLine.identifier()).upperCamelIdentifier(param.getIdentifier().toUpperCamel()).typeName(simpleInitLine.typeName()).isEnum(simpleInitLine.isEnum()).cliFlagName(param.getIdentifier().toLowerUnderscore()).cliFlagDefaultValue(getCliFlagDefaultValue(param)).description(param.getDescription()).build());
        // Since we're going to write the inits for the params here,
        // remove so we don't init twice.
        orderedItems.removeAll(paramInits);
    }
    return InitCodeView.newBuilder().argDefaultLines(argDefaultLines).argDefaultParams(argDefaultParams).lines(generateSurfaceInitCodeLines(context, orderedItems)).topLevelLines(generateSurfaceInitCodeLines(context, libArguments)).fieldSettings(fieldSettings).optionalFieldSettings(optionalFieldSettings).requiredFieldSettings(requiredFieldSettings).importSection(importSectionTransformer.generateImportSection(context, orderedItems)).topLevelIndexFileImportName(namer.getTopLevelIndexFileImportName()).build();
}
Also used : SimpleInitValueView(com.google.api.codegen.viewmodel.SimpleInitValueView) TypeRef(com.google.api.tools.framework.model.TypeRef) EscaperFactory(com.google.api.codegen.util.EscaperFactory) Arrays(java.util.Arrays) ProtoFile(com.google.api.tools.framework.model.ProtoFile) InitValueView(com.google.api.codegen.viewmodel.InitValueView) PathTemplate(com.google.api.pathtemplate.PathTemplate) RepeatedResourceNameInitValueView(com.google.api.codegen.viewmodel.RepeatedResourceNameInitValueView) StructureInitCodeLineView(com.google.api.codegen.viewmodel.StructureInitCodeLineView) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) FieldSettingView(com.google.api.codegen.viewmodel.FieldSettingView) HashMultimap(com.google.common.collect.HashMultimap) MethodContext(com.google.api.codegen.config.MethodContext) InitValue(com.google.api.codegen.metacode.InitValue) InitCodeContext(com.google.api.codegen.metacode.InitCodeContext) Map(java.util.Map) SingleResourceNameConfig(com.google.api.codegen.config.SingleResourceNameConfig) ListInitCodeLineView(com.google.api.codegen.viewmodel.ListInitCodeLineView) ResourceNameType(com.google.api.codegen.config.ResourceNameType) FieldStructureParser(com.google.api.codegen.metacode.FieldStructureParser) InitCodeView(com.google.api.codegen.viewmodel.InitCodeView) ResourceNameOneofInitValueView(com.google.api.codegen.viewmodel.ResourceNameOneofInitValueView) SimpleInitCodeLineView(com.google.api.codegen.viewmodel.SimpleInitCodeLineView) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) InitCodeNode(com.google.api.codegen.metacode.InitCodeNode) Collectors(java.util.stream.Collectors) ProtoTypeRef(com.google.api.codegen.config.ProtoTypeRef) InitValueConfig(com.google.api.codegen.metacode.InitValueConfig) Scanner(com.google.api.codegen.util.Scanner) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Name(com.google.api.codegen.util.Name) ResourceNameInitValueView(com.google.api.codegen.viewmodel.ResourceNameInitValueView) List(java.util.List) InitCodeLineView(com.google.api.codegen.viewmodel.InitCodeLineView) InterfaceModel(com.google.api.codegen.config.InterfaceModel) Optional(java.util.Optional) ReadFileInitCodeLineView(com.google.api.codegen.viewmodel.ReadFileInitCodeLineView) ResourceNameOneofConfig(com.google.api.codegen.config.ResourceNameOneofConfig) TestValueGenerator(com.google.api.codegen.util.testing.TestValueGenerator) Iterables(com.google.common.collect.Iterables) FormattedInitValueView(com.google.api.codegen.viewmodel.FormattedInitValueView) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) InitCodeLineType(com.google.api.codegen.metacode.InitCodeLineType) SampleParameterConfig(com.google.api.codegen.config.SampleParameterConfig) OneofConfigView(com.google.api.codegen.viewmodel.OneofConfigView) ResourceNamePatternConfig(com.google.api.codegen.config.ResourceNamePatternConfig) InitCodeOutputType(com.google.api.codegen.metacode.InitCodeContext.InitCodeOutputType) SampleFunctionParameterView(com.google.api.codegen.viewmodel.SampleFunctionParameterView) SymbolTable(com.google.api.codegen.util.SymbolTable) ResourceNameConfig(com.google.api.codegen.config.ResourceNameConfig) TypeModel(com.google.api.codegen.config.TypeModel) ProtoInterfaceModel(com.google.api.codegen.config.ProtoInterfaceModel) MapEntryView(com.google.api.codegen.viewmodel.MapEntryView) ClientTestAssertView(com.google.api.codegen.viewmodel.testing.ClientTestAssertView) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ArrayDeque(java.util.ArrayDeque) FieldConfig(com.google.api.codegen.config.FieldConfig) MapInitCodeLineView(com.google.api.codegen.viewmodel.MapInitCodeLineView) ArrayList(java.util.ArrayList) SampleFunctionParameterView(com.google.api.codegen.viewmodel.SampleFunctionParameterView) StructureInitCodeLineView(com.google.api.codegen.viewmodel.StructureInitCodeLineView) ListInitCodeLineView(com.google.api.codegen.viewmodel.ListInitCodeLineView) SimpleInitCodeLineView(com.google.api.codegen.viewmodel.SimpleInitCodeLineView) InitCodeLineView(com.google.api.codegen.viewmodel.InitCodeLineView) ReadFileInitCodeLineView(com.google.api.codegen.viewmodel.ReadFileInitCodeLineView) MapInitCodeLineView(com.google.api.codegen.viewmodel.MapInitCodeLineView) FieldSettingView(com.google.api.codegen.viewmodel.FieldSettingView) InitCodeNode(com.google.api.codegen.metacode.InitCodeNode) SimpleInitCodeLineView(com.google.api.codegen.viewmodel.SimpleInitCodeLineView)

Example 4 with InitCodeNode

use of com.google.api.codegen.metacode.InitCodeNode in project toolkit by googleapis.

the class InitCodeTransformer method generateListInitCodeLine.

private InitCodeLineView generateListInitCodeLine(MethodContext context, InitCodeNode item) {
    ListInitCodeLineView.Builder surfaceLine = ListInitCodeLineView.newBuilder();
    FieldConfig fieldConfig = item.getFieldConfig();
    SurfaceNamer namer = context.getNamer();
    ImportTypeTable typeTable = context.getTypeTable();
    surfaceLine.lineType(InitCodeLineType.ListInitLine);
    surfaceLine.identifier(namer.localVarName(item.getIdentifier()));
    if (context.getFeatureConfig().useResourceNameFormatOptionInSample(context, fieldConfig)) {
        surfaceLine.elementTypeName(namer.getAndSaveElementResourceTypeName(typeTable, fieldConfig));
    } else {
        surfaceLine.elementTypeName(typeTable.getAndSaveNicknameForElementType(item.getType().makeOptional()));
    }
    List<String> entries = new ArrayList<>();
    List<InitCodeLineView> elements = new ArrayList<>();
    for (InitCodeNode child : item.getChildren().values()) {
        entries.add(namer.localVarName(child.getIdentifier()));
        elements.add(generateSurfaceInitCodeLine(context, child, elements.isEmpty(), false));
    }
    surfaceLine.elementIdentifiers(entries);
    surfaceLine.elements(elements);
    surfaceLine.descriptions(context.getNamer().getWrappedDocLines(item.getDescription(), false));
    return surfaceLine.build();
}
Also used : StructureInitCodeLineView(com.google.api.codegen.viewmodel.StructureInitCodeLineView) ListInitCodeLineView(com.google.api.codegen.viewmodel.ListInitCodeLineView) SimpleInitCodeLineView(com.google.api.codegen.viewmodel.SimpleInitCodeLineView) InitCodeLineView(com.google.api.codegen.viewmodel.InitCodeLineView) ReadFileInitCodeLineView(com.google.api.codegen.viewmodel.ReadFileInitCodeLineView) MapInitCodeLineView(com.google.api.codegen.viewmodel.MapInitCodeLineView) ListInitCodeLineView(com.google.api.codegen.viewmodel.ListInitCodeLineView) InitCodeNode(com.google.api.codegen.metacode.InitCodeNode) FieldConfig(com.google.api.codegen.config.FieldConfig) ArrayList(java.util.ArrayList)

Example 5 with InitCodeNode

use of com.google.api.codegen.metacode.InitCodeNode in project toolkit by googleapis.

the class InitCodeTransformer method sampleFuncParams.

/**
 * Returns all the nodes to be rendered as sample function parameters.
 *
 * <p>If path is:
 * <li>a normal node, returns that node.
 * <li>a ReadFile node, returns the child node of that node.
 * <li>a resource path, returns the child node whose key equals the entity name in the path.
 *
 * @param paramConfigMap the sample parameter configurations derived from {@code InitCodeContext}
 */
private List<InitCodeNode> sampleFuncParams(InitCodeNode root, List<String> paths, Map<String, SampleParameterConfig> paramConfigMap) {
    List<InitCodeNode> params = new ArrayList<>();
    for (String path : paths) {
        Scanner scanner = new Scanner(path);
        InitCodeNode node = FieldStructureParser.parsePath(root, scanner);
        int token = scanner.lastToken();
        if (token == '%') {
            scanner.scan();
            node = node.getChildren().get(scanner.tokenStr());
            node.setDescription(paramConfigMap.get(path).comment());
            params.add(node);
        } else if (node.getLineType() == InitCodeLineType.ReadFileInitLine) {
            node = node.getChildren().get(InitCodeNode.FILE_NAME_KEY);
            node.setDescription(paramConfigMap.get(path).comment());
            params.add(node);
        } else {
            node.setDescription(paramConfigMap.get(path).comment());
            params.add(node);
        }
    }
    return params;
}
Also used : Scanner(com.google.api.codegen.util.Scanner) InitCodeNode(com.google.api.codegen.metacode.InitCodeNode) ArrayList(java.util.ArrayList)

Aggregations

InitCodeNode (com.google.api.codegen.metacode.InitCodeNode)12 ArrayList (java.util.ArrayList)7 FieldConfig (com.google.api.codegen.config.FieldConfig)4 InitCodeLineView (com.google.api.codegen.viewmodel.InitCodeLineView)3 ListInitCodeLineView (com.google.api.codegen.viewmodel.ListInitCodeLineView)3 MapInitCodeLineView (com.google.api.codegen.viewmodel.MapInitCodeLineView)3 ReadFileInitCodeLineView (com.google.api.codegen.viewmodel.ReadFileInitCodeLineView)3 SimpleInitCodeLineView (com.google.api.codegen.viewmodel.SimpleInitCodeLineView)3 StructureInitCodeLineView (com.google.api.codegen.viewmodel.StructureInitCodeLineView)3 TypeModel (com.google.api.codegen.config.TypeModel)2 Scanner (com.google.api.codegen.util.Scanner)2 FieldSettingView (com.google.api.codegen.viewmodel.FieldSettingView)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 ArrayDeque (java.util.ArrayDeque)2 HashMap (java.util.HashMap)2 BatchingConfig (com.google.api.codegen.config.BatchingConfig)1 FieldModel (com.google.api.codegen.config.FieldModel)1 GrpcStreamingConfig (com.google.api.codegen.config.GrpcStreamingConfig)1 InterfaceModel (com.google.api.codegen.config.InterfaceModel)1 MethodContext (com.google.api.codegen.config.MethodContext)1