Search in sources :

Example 6 with Model

use of com.google.api.tools.framework.model.Model in project toolkit by googleapis.

the class ModelTypeNameConverterTestUtil method getTestType.

public static TypeRef getTestType(String fileName, TemporaryFolder tempDir, String... path) {
    String yamlFileName = fileName + ".yaml";
    fileName = fileName + ".proto";
    TestDataLocator locator = TestDataLocator.create(CodegenTestUtil.class);
    locator.addTestDataSource(CodegenTestUtil.class, "testsrc/common");
    Model model = CodegenTestUtil.readModel(locator, tempDir, new String[] { fileName }, new String[] { yamlFileName });
    ProtoContainerElement container = getElementWithName(model.getFiles(), fileName);
    if (container == null) {
        throw new IllegalStateException("file not found: " + fileName);
    }
    for (int i = 0; i < path.length; i++) {
        String pathElement = path[i];
        MessageType messageType = getElementWithName(container.getMessages(), pathElement);
        EnumType enumType = getElementWithName(container.getEnums(), pathElement);
        if (messageType != null) {
            container = messageType;
        } else if (enumType != null && i == path.length - 1) {
            return TypeRef.of(enumType);
        } else if (enumType != null) {
            throw new IllegalStateException("enum type cannot contain further elements: " + enumType);
        } else {
            throw new IllegalStateException("element not found: " + pathElement);
        }
    }
    if (container instanceof MessageType) {
        return TypeRef.of((MessageType) container);
    }
    throw new IllegalStateException("not a type: " + container);
}
Also used : EnumType(com.google.api.tools.framework.model.EnumType) Model(com.google.api.tools.framework.model.Model) ProtoContainerElement(com.google.api.tools.framework.model.ProtoContainerElement) TestDataLocator(com.google.api.tools.framework.model.testing.TestDataLocator) MessageType(com.google.api.tools.framework.model.MessageType)

Example 7 with Model

use of com.google.api.tools.framework.model.Model in project toolkit by googleapis.

the class LongRunningConfig method createLongRunningConfig.

/**
 * Creates an instance of LongRunningConfig based on protofile annotations. If there is matching
 * long running config from GAPIC config, use the GAPIC config's timeout values.
 */
@Nullable
static LongRunningConfig createLongRunningConfig(Method method, DiagCollector diagCollector, @Nonnull LongRunningConfigProto longRunningConfigProto, ProtoParser protoParser) {
    int preexistingErrors = diagCollector.getErrorCount();
    Model model = method.getModel();
    OperationInfo operationTypes = protoParser.getLongRunningOperation(method);
    if (operationTypes == null || operationTypes.equals(operationTypes.getDefaultInstanceForType())) {
        return null;
    }
    String responseTypeName = qualifyLroTypeName(operationTypes.getResponseType(), method, protoParser);
    String metadataTypeName = qualifyLroTypeName(operationTypes.getMetadataType(), method, protoParser);
    TypeRef returnType = model.getSymbolTable().lookupType(responseTypeName);
    TypeRef metadataType = model.getSymbolTable().lookupType(metadataTypeName);
    if (returnType == null) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Type not found for long running config: '%s'", responseTypeName));
    } else if (!returnType.isMessage()) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Type for long running config is not a message: '%s'", responseTypeName));
    }
    if (metadataType == null) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Metadata type not found for long running config: '%s'", metadataTypeName));
    } else if (!metadataType.isMessage()) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Metadata type for long running config is not a message: '%s'", metadataTypeName));
    }
    if (diagCollector.getErrorCount() - preexistingErrors > 0) {
        return null;
    }
    LongRunningConfig.Builder builder = getGapicConfigLroRetrySettingsOrDefault(diagCollector, longRunningConfigProto);
    return builder.setReturnType(ProtoTypeRef.create(returnType)).setMetadataType(ProtoTypeRef.create(metadataType)).build();
}
Also used : OperationInfo(com.google.longrunning.OperationInfo) TypeRef(com.google.api.tools.framework.model.TypeRef) Model(com.google.api.tools.framework.model.Model) Nullable(javax.annotation.Nullable)

Example 8 with Model

use of com.google.api.tools.framework.model.Model in project toolkit by googleapis.

the class GapicTestBase2 method createTestConfig.

/**
 * Creates the constructor arguments to be passed onto this class (GapicTestBase2) to create test
 * methods. The idForFactory String is passed to GapicProviderFactory to get the GapicProviders
 * provided by that id, and then the snippet file names are scraped from those providers, and a
 * set of arguments is created for each combination of GapicProvider x snippet that
 * GapicProviderFactory returns.
 */
public static Object[] createTestConfig(String idForFactory, String[] gapicConfigFileNames, String packageConfigFileName, String apiName) {
    Model model = Model.create(Service.getDefaultInstance());
    GapicProductConfig productConfig = GapicProductConfig.createDummyInstance();
    PackageMetadataConfig packageConfig = PackageMetadataConfig.createDummyPackageMetadataConfig();
    GapicGeneratorConfig generatorConfig = GapicGeneratorConfig.newBuilder().id(idForFactory).enabledArtifacts(Arrays.asList("surface", "test")).build();
    List<GapicProvider> providers = MainGapicProviderFactory.defaultCreate(model, productConfig, generatorConfig, packageConfig);
    List<String> snippetNames = new ArrayList<>();
    for (GapicProvider provider : providers) {
        snippetNames.addAll(provider.getSnippetFileNames());
    }
    String baseline = idForFactory + "_" + apiName + ".baseline";
    return new Object[] { idForFactory, gapicConfigFileNames, packageConfigFileName, snippetNames, apiName, baseline };
}
Also used : GapicProductConfig(com.google.api.codegen.config.GapicProductConfig) GapicGeneratorConfig(com.google.api.codegen.gapic.GapicGeneratorConfig) Model(com.google.api.tools.framework.model.Model) PackageMetadataConfig(com.google.api.codegen.config.PackageMetadataConfig) GapicProvider(com.google.api.codegen.gapic.GapicProvider) ArrayList(java.util.ArrayList)

Example 9 with Model

use of com.google.api.tools.framework.model.Model in project toolkit by googleapis.

the class PythonImportSectionTransformer method generateTypesProtoImports.

private ImportSectionView.Builder generateTypesProtoImports(Model model, GapicProductConfig productConfig) {
    ImportSectionView.Builder importView = ImportSectionView.newBuilder();
    ModelTypeTable allTypeTable = emptyTypeTable(productConfig);
    // Imports from the same API client library package.
    Set<ImportFileView> localImports = new TreeSet<>(importFileViewComparator());
    // Shared imports, e.g. protobuf imports.
    Set<ImportFileView> sharedImports = new TreeSet<>(importFileViewComparator());
    // All imports.
    Set<ImportFileView> appImports = new TreeSet<>(importFileViewComparator());
    Set<String> localImportNames = new HashSet<>();
    Set<String> sharedImportNames = new HashSet<>();
    SymbolTable symbolTable = model.getSymbolTable();
    Collection<ProtoFile> localImportFiles = productConfig.getInterfaceConfigMap().keySet().stream().map(symbolTable::lookupInterface).filter(Objects::nonNull).map(Interface::getFile).collect(ImmutableSet.toImmutableSet());
    Iterable<ProtoFile> allFiles = model.reachable(model.getFiles());
    // Skip API interfaces excluded from interface configs.
    Collection<ProtoFile> skippedFiles = Streams.stream(allFiles).filter(ProtoFile::isSource).flatMap(f -> f.getInterfaces().stream()).filter(Interface::isReachable).filter(i -> productConfig.getInterfaceConfig(i) == null).map(Interface::getFile).collect(ImmutableSet.toImmutableSet());
    // Can't use Collection#removeAll since allFiles is an Iterable.
    Iterable<ProtoFile> protoFileDependencies = Streams.stream(allFiles).filter(f -> !skippedFiles.contains(f)).collect(ImmutableSet.toImmutableSet());
    // Save proto file import names to the type table for disambiguation.
    populateTypeTable(protoFileDependencies, allTypeTable, localImportNames, sharedImportNames, localImportFiles);
    // Get disambiguated imports.
    for (Map.Entry<String, TypeAlias> entry : allTypeTable.getImports().entrySet()) {
        String importFullName = entry.getKey();
        String nickName = entry.getValue().getNickname();
        appImports.add(generateAppImport(importFullName, nickName));
        if (localImportNames.contains(importFullName)) {
            localImports.add(generateAppImport(importFullName, nickName));
        } else if (sharedImportNames.contains(importFullName)) {
            sharedImports.add(generateAppImport(importFullName, nickName));
        }
    }
    importView.localImports(ImmutableList.copyOf(localImports));
    importView.sharedImports(ImmutableList.copyOf(sharedImports));
    importView.appImports(ImmutableList.copyOf(appImports));
    return importView;
}
Also used : TypeRef(com.google.api.tools.framework.model.TypeRef) ImportFileView(com.google.api.codegen.viewmodel.ImportFileView) MessageType(com.google.api.tools.framework.model.MessageType) ProtoFile(com.google.api.tools.framework.model.ProtoFile) ImportSectionView(com.google.api.codegen.viewmodel.ImportSectionView) ImportTypeView(com.google.api.codegen.viewmodel.ImportTypeView) SymbolTable(com.google.api.tools.framework.model.SymbolTable) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) InitCodeLineType(com.google.api.codegen.metacode.InitCodeLineType) Map(java.util.Map) com.google.api.codegen.transformer(com.google.api.codegen.transformer) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) InitCodeNode(com.google.api.codegen.metacode.InitCodeNode) Streams(com.google.common.collect.Streams) PythonTypeTable(com.google.api.codegen.util.py.PythonTypeTable) Objects(java.util.Objects) com.google.api.codegen.config(com.google.api.codegen.config) List(java.util.List) TypeAlias(com.google.api.codegen.util.TypeAlias) TreeMap(java.util.TreeMap) Interface(com.google.api.tools.framework.model.Interface) Comparator(java.util.Comparator) Model(com.google.api.tools.framework.model.Model) Collections(java.util.Collections) ImportFileView(com.google.api.codegen.viewmodel.ImportFileView) ProtoFile(com.google.api.tools.framework.model.ProtoFile) SymbolTable(com.google.api.tools.framework.model.SymbolTable) TypeAlias(com.google.api.codegen.util.TypeAlias) TreeSet(java.util.TreeSet) Objects(java.util.Objects) Map(java.util.Map) TreeMap(java.util.TreeMap) ImportSectionView(com.google.api.codegen.viewmodel.ImportSectionView) HashSet(java.util.HashSet)

Example 10 with Model

use of com.google.api.tools.framework.model.Model in project toolkit by googleapis.

the class GapicTestBase2 method createTestConfig.

/**
 * Creates the constructor arguments to be passed onto this class (GapicTestBase2) to create test
 * methods. The langauge String is passed to GapicGeneratorFactory to get the GapicGenerators
 * provided by that language, and then the snippet file names are scraped from those generators,
 * and a set of arguments is created for each combination of CodeGenerator x snippet that
 * GapicGeneratorFactory returns.
 */
public static Object[] createTestConfig(TargetLanguage language, String[] gapicConfigFileNames, String packageConfigFileName, String apiName, String protoPackage, String clientPackage, String grpcServiceConfigFileName, String[] sampleConfigFileNames, String baseline, TransportProtocol transportProtocol, String... baseNames) {
    Model model = Model.create(Service.getDefaultInstance());
    GapicProductConfig productConfig = GapicProductConfig.createDummyInstance();
    PackageMetadataConfig packageConfig = PackageMetadataConfig.createDummyPackageMetadataConfig();
    ArtifactFlags artifactFlags = new ArtifactFlags(Arrays.asList("surface", "test", "samples"), ArtifactType.LEGACY_GAPIC_AND_PACKAGE, true);
    List<CodeGenerator<?>> generators = GapicGeneratorFactory.create(language, model, productConfig, packageConfig, artifactFlags);
    List<String> snippetNames = new ArrayList<>();
    for (CodeGenerator<?> generator : generators) {
        snippetNames.addAll(generator.getInputFileNames());
    }
    // autogenerated name will be provided.
    if (baseline == null) {
        StringBuilder suffix = new StringBuilder();
        if (gapicConfigFileNames == null || gapicConfigFileNames.length == 0) {
            suffix.append("_no_gapic_config");
        }
        if (!Strings.isNullOrEmpty(grpcServiceConfigFileName)) {
            suffix.append("_with_grpc_service_config");
        }
        baseline = language.toString().toLowerCase() + "_" + apiName + suffix + ".baseline";
    }
    baseNames = Lists.asList(apiName, baseNames).toArray(new String[0]);
    return new Object[] { language, gapicConfigFileNames, sampleConfigFileNames, packageConfigFileName, snippetNames, baseline, protoPackage, clientPackage, grpcServiceConfigFileName, transportProtocol, baseNames };
}
Also used : GapicProductConfig(com.google.api.codegen.config.GapicProductConfig) Model(com.google.api.tools.framework.model.Model) PackageMetadataConfig(com.google.api.codegen.config.PackageMetadataConfig) ArrayList(java.util.ArrayList) CodeGenerator(com.google.api.codegen.common.CodeGenerator)

Aggregations

Model (com.google.api.tools.framework.model.Model)14 GapicProductConfig (com.google.api.codegen.config.GapicProductConfig)5 ProtoApiModel (com.google.api.codegen.config.ProtoApiModel)4 ViewModel (com.google.api.codegen.viewmodel.ViewModel)4 TestDataLocator (com.google.api.tools.framework.model.testing.TestDataLocator)4 ArrayList (java.util.ArrayList)4 ConfigProto (com.google.api.codegen.ConfigProto)3 MixedPathTestDataLocator (com.google.api.codegen.MixedPathTestDataLocator)3 ApiModel (com.google.api.codegen.config.ApiModel)3 InterfaceModel (com.google.api.codegen.config.InterfaceModel)3 PackageMetadataConfig (com.google.api.codegen.config.PackageMetadataConfig)3 ImmutableList (com.google.common.collect.ImmutableList)3 Test (org.junit.Test)3 CodeGenerator (com.google.api.codegen.common.CodeGenerator)2 MethodModel (com.google.api.codegen.config.MethodModel)2 PackageInfoView (com.google.api.codegen.viewmodel.PackageInfoView)2 Diag (com.google.api.tools.framework.model.Diag)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 List (java.util.List)2 ProtoFileView (com.google.api.codegen.ProtoFileView)1