org.openapitools.codegen.CodegenConfig Java Examples

The following examples show how to use org.openapitools.codegen.CodegenConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CodeGenMojo.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * This method enables conversion of true/false strings in
 * config.additionalProperties (configuration/configOptions) to proper booleans.
 * This enables mustache files to handle the properties better.
 *
 * @param config
 */
private void adjustAdditionalProperties(final CodegenConfig config) {
    Map<String, Object> configAdditionalProperties = config.additionalProperties();
    Set<String> keySet = configAdditionalProperties.keySet();
    for (String key : keySet) {
        Object value = configAdditionalProperties.get(key);
        if (value != null) {
            if (value instanceof String) {
                String stringValue = (String) value;
                if (stringValue.equalsIgnoreCase("true")) {
                    configAdditionalProperties.put(key, Boolean.TRUE);
                } else if (stringValue.equalsIgnoreCase("false")) {
                    configAdditionalProperties.put(key, Boolean.FALSE);
                }
            }
        } else {
            configAdditionalProperties.put(key, Boolean.FALSE);
        }
    }
}
 
Example #2
Source File: GenerateBatch.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * When an object implementing interface <code>Runnable</code> is used
 * to create a thread, starting the thread causes the object's
 * <code>run</code> method to be called in that separately executing
 * thread.
 * <p>
 * The general contract of the method <code>run</code> is that it may
 * take any action whatsoever.
 *
 * @see Thread#run()
 */
@Override
public void run() {
    String name = "";
    try {
        GlobalSettings.reset();

        ClientOptInput opts = configurator.toClientOptInput();
        CodegenConfig config = opts.getConfig();
        name = config.getName();
        
        Path target = Paths.get(config.getOutputDir());
        Path updated = rootDir.resolve(target);
        config.setOutputDir(updated.toString());

        System.out.printf(Locale.ROOT, "[%s] Generating %s (outputs to %s)…%n", Thread.currentThread().getName(), name, updated.toString());

        DefaultGenerator defaultGenerator = new DefaultGenerator();
        defaultGenerator.opts(opts);

        defaultGenerator.generate();

        System.out.printf(Locale.ROOT, "[%s] Finished generating %s…%n", Thread.currentThread().getName(), name);
        successes.incrementAndGet();
    } catch (Throwable e) {
        failures.incrementAndGet();
        String failedOn = name;
        if (StringUtils.isEmpty(failedOn)) {
            failedOn = "unspecified";
        }
        System.err.printf(Locale.ROOT, "[%s] Generation failed for %s: (%s) %s%n", Thread.currentThread().getName(), failedOn, e.getClass().getSimpleName(), e.getMessage());
        e.printStackTrace(System.err);
        if (exitOnError) {
            System.exit(1);
        }
    } finally {
        GlobalSettings.reset();
    }
}
 
Example #3
Source File: AsciidocGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateIndexAsciidocMarkupContent() throws Exception {
    final File output = Files.createTempDirectory("test").toFile();
    output.mkdirs();
    output.deleteOnExit();

    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/ping.yaml");
    CodegenConfig codegenConfig = new AsciidocDocumentationCodegen();
    codegenConfig.setOutputDir(output.getAbsolutePath());
    ClientOptInput clientOptInput = new ClientOptInput().openAPI(openAPI).config(codegenConfig);

    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();
    boolean markupFileGenerated = false;
    for (File file : files) {
        if (file.getName().equals("index.adoc")) {
            markupFileGenerated = true;
            String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
            // check on some basic asciidoc markup content
            Assert.assertTrue(markupContent.contains("= ping test"),
                    "expected = header in: " + markupContent.substring(0, 50));
            Assert.assertTrue(markupContent.contains(":toc: "),
                    "expected = :toc: " + markupContent.substring(0, 50));
        }
    }
    Assert.assertTrue(markupFileGenerated, "Default api file is not generated!");
}
 
Example #4
Source File: ConfigHelp.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private void generateYamlSample(StringBuilder sb, CodegenConfig config) {

        for (CliOption langCliOption : config.cliOptions()) {

            sb.append("# Description: ").append(langCliOption.getDescription()).append(newline);

            Map<String, String> enums = langCliOption.getEnum();
            if (enums != null) {
                sb.append("# Available Values:").append(newline);

                for (Map.Entry<String, String> entry : enums.entrySet()) {
                    sb.append("#    ").append(entry.getKey()).append(newline);
                    sb.append("#         ").append(entry.getValue()).append(newline);
                }
            }

            String defaultValue = langCliOption.getDefault();

            if (defaultValue != null) {
                sb.append(langCliOption.getOpt()).append(": ").append(defaultValue).append(newline);
            } else {
                sb.append("# ").append(langCliOption.getOpt()).append(": ").append(newline);
            }

            sb.append(newline);
        }
    }
 
Example #5
Source File: GeneratorTemplateContentLocator.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Get the template file path with template dir prepended, and use the library template if exists.
 *
 * Precedence:
 * 1) (template dir)/libraries/(library)
 * 2) (template dir)
 * 3) (embedded template dir)/libraries/(library)
 * 4) (embedded template dir)
 *
 * Where "template dir" may be user defined and "embedded template dir" are the built-in templates for the given generator.
 *
 * @param relativeTemplateFile Template file
 * @return String Full template file path
 */
@Override
public String getFullTemplatePath(String relativeTemplateFile) {
    CodegenConfig config = this.codegenConfig;

    //check the supplied template library folder for the file
    final String library = config.getLibrary();
    if (StringUtils.isNotEmpty(library)) {
        //look for the file in the library subfolder of the supplied template
        final String libTemplateFile = buildLibraryFilePath(config.templateDir(), library, relativeTemplateFile);
        if (new File(libTemplateFile).exists() || this.getClass().getClassLoader().getResource(libTemplateFile) != null) {
            return libTemplateFile;
        }
    }

    //check the supplied template main folder for the file
    final String template = config.templateDir() + File.separator + relativeTemplateFile;
    if (new File(template).exists() || this.getClass().getClassLoader().getResource(template) != null) {
        return template;
    }

    //try the embedded template library folder next
    if (StringUtils.isNotEmpty(library)) {
        final String embeddedLibTemplateFile = buildLibraryFilePath(config.embeddedTemplateDir(), library, relativeTemplateFile);
        if (embeddedTemplateExists(embeddedLibTemplateFile)) {
            // Fall back to the template file embedded/packaged in the JAR file library folder...
            return embeddedLibTemplateFile;
        }
    }

    // Fall back to the template file for generator root directory embedded/packaged in the JAR file...
    String loc = config.embeddedTemplateDir() + File.separator + relativeTemplateFile;
    if (embeddedTemplateExists(loc)) {
        return loc;
    }

    return null;
}
 
Example #6
Source File: OneOfImplementorAdditionalData.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Adds stored data to given implementing model
 *
 * @param cc CodegenConfig running this operation
 * @param implcm the implementing model
 * @param implImports imports of the implementing model
 * @param addInterfaceImports whether or not to add the interface model as import (will vary by language)
 */
@SuppressWarnings("unchecked")
public void addToImplementor(CodegenConfig cc, CodegenModel implcm, List<Map<String, String>> implImports, boolean addInterfaceImports) {
    implcm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());

    // Add implemented interfaces
    for (String intf : additionalInterfaces) {
        List<String> impl = (List<String>) implcm.getVendorExtensions().get("x-implements");
        impl.add(intf);
        if (addInterfaceImports) {
            // Add imports for interfaces
            implcm.imports.add(intf);
            Map<String, String> importsItem = new HashMap<String, String>();
            importsItem.put("import", cc.toModelImport(intf));
            implImports.add(importsItem);
        }
    }

    // Add oneOf-containing models properties - we need to properly set the hasMore values to make rendering correct
    if (implcm.vars.size() > 0 && additionalProps.size() > 0) {
        implcm.vars.get(implcm.vars.size() - 1).hasMore = true;
    }
    for (int i = 0; i < additionalProps.size(); i++) {
        CodegenProperty var = additionalProps.get(i);
        if (i == additionalProps.size() - 1) {
            var.hasMore = false;
        } else {
            var.hasMore = true;
        }
        implcm.vars.add(var);
    }

    // Add imports
    for (Map<String, String> oneImport : additionalImports) {
        // exclude imports from this package - these are imports that only the oneOf interface needs
        if (!implImports.contains(oneImport) && !oneImport.getOrDefault("import", "").startsWith(cc.modelPackage())) {
            implImports.add(oneImport);
        }
    }
}
 
Example #7
Source File: Generator.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static Map<String, CliOption> getOptions(String language) {
    CodegenConfig config;
    try {
        config = CodegenConfigLoader.forName(language);
    } catch (Exception e) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT,"Unsupported target %s supplied. %s",
                language, e));
    }
    Map<String, CliOption> map = new LinkedHashMap<>();
    for (CliOption option : config.cliOptions()) {
        map.put(option.getOpt(), option);
    }
    return map;
}
 
Example #8
Source File: TemplateTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> readSwaggerModelInfo(String swaggerYamlFile, CodegenConfig config) throws IOException {

    Map<String, Object> templateData = new HashMap<>();
    String swaggerString = readResourceInClasspath(swaggerYamlFile);
    Swagger swagger = new SwaggerParser().parse(swaggerString);

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    SwaggerParseResult result = new OpenAPIParser().readContents(swaggerString, null, options);
    OpenAPI openAPI = result.getOpenAPI();

    Components components = openAPI.getComponents();

    Map<String, Model> definitions = swagger.getDefinitions();
    if (definitions == null) {
      return templateData;
    }
    List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
    for (String key : components.getSchemas().keySet()) {
      Schema mm = components.getSchemas().get(key);
      CodegenModel cm = config.fromModel(key, mm);
      Map<String, String> item = new HashMap<String, String>();
      item.put("import", config.toModelImport(cm.classname));
      imports.add(item);
    }
    templateData.put("imports", imports);
    return templateData;
  }
 
Example #9
Source File: ServiceCombCodegenTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultValue() {
  CodegenConfig codegenConfig = CodegenConfigLoader.forName("ServiceComb");
  Assert.assertEquals(ServiceCombCodegen.class, codegenConfig.getClass());
  ServiceCombCodegen serviceCombCodegen = (ServiceCombCodegen) codegenConfig;
  serviceCombCodegen.processOpts();

  Map<String, Object> additionalProperties = serviceCombCodegen.additionalProperties();
  Assert.assertEquals("domain.orgnization.project.sample", additionalProperties.get("mainClassPackage"));
  Assert.assertEquals("domain.orgnization.project.sample.api", additionalProperties.get("apiPackage"));
  Assert.assertEquals("domain.orgnization.project.sample.model", additionalProperties.get("modelPackage"));
}
 
Example #10
Source File: URLPathUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static String getScheme(URL url, CodegenConfig config) {
    String scheme;
    if (url != null) {
        scheme = url.getProtocol();
    } else {
        scheme = "https";
    }
    if (config != null) {
        scheme = config.escapeText(scheme);
    }
    return scheme;
}
 
Example #11
Source File: TypeScriptAureliaClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #12
Source File: Swift5OptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #13
Source File: MysqlSchemaOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #14
Source File: ElixirClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #15
Source File: PhpClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #16
Source File: PhpSlim4ServerOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #17
Source File: TypeScriptAngularJsClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #18
Source File: TypescriptAngularArrayAndObjectIntegrationTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return new TypeScriptAngularClientCodegen();
}
 
Example #19
Source File: TypescriptAngularPestoreIntegrationTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return new TypeScriptAngularClientCodegen();
}
 
Example #20
Source File: TypeScriptAngularClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #21
Source File: TypescriptAngularAdditionalPropertiesIntegrationTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return new TypeScriptAngularClientCodegen();
}
 
Example #22
Source File: TypeScriptFetchClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #23
Source File: TypescriptNodeES5IntegrationTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return new TypeScriptNodeClientCodegen();
}
 
Example #24
Source File: TypescriptNodeEnumIntegrationTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return new TypeScriptNodeClientCodegen();
}
 
Example #25
Source File: TypeScriptNodeClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #26
Source File: ListGenerators.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() {
    List<CodegenConfig> generators = new ArrayList<>();
    List<Stability> stabilities = Arrays.asList(Stability.values());

    if (!StringUtils.isEmpty(include)) {
        List<String> includes = Arrays.asList(include.split(","));
        if (includes.size() != 0 && !includes.contains("all")) {
            stabilities = includes.stream()
                    .map(Stability::forDescription)
                    .collect(Collectors.toList());
        }
    }

    for (CodegenConfig codegenConfig : CodegenConfigLoader.getAll()) {
        GeneratorMetadata meta = codegenConfig.getGeneratorMetadata();
        if (meta != null && stabilities.contains(meta.getStability())) {
            generators.add(codegenConfig);
        }
    }

    StringBuilder sb = new StringBuilder();

    if (shortened) {
        for (int i = 0; i < generators.size(); i++) {
            CodegenConfig generator = generators.get(i);
            if (i != 0) {
                sb.append(",");
            }
            sb.append(generator.getName());
        }
    } else {
        CodegenType[] types = CodegenType.values();

        sb.append("The following generators are available:");

        sb.append(System.lineSeparator());
        sb.append(System.lineSeparator());

        for (CodegenType type : types) {
            appendForType(sb, type, type.name(), generators);
        }
        appendForType(sb, null, "UNSPECIFIED", generators);
    }

    System.out.printf(Locale.ROOT, "%s%n", sb.toString());
}
 
Example #27
Source File: ListGenerators.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
private void appendForType(StringBuilder sb, CodegenType type, String typeName, List<CodegenConfig> generators) {
    List<CodegenConfig> list = generators.stream()
            .filter(g -> Objects.equal(type, g.getTag()))
            .sorted(Comparator.comparing(CodegenConfig::getName))
            .collect(Collectors.toList());

    if(!list.isEmpty()) {
        if (docusaurus || githubNestedIndex) {
            sb.append("## ").append(typeName).append(" generators");
        } else {
            sb.append(typeName).append(" generators:");
        }
        sb.append(System.lineSeparator());

        list.forEach(generator -> {
            GeneratorMetadata meta = generator.getGeneratorMetadata();
            if (docusaurus || githubNestedIndex) {
                sb.append("* ");
                String idPrefix = docusaurus ? "generators/" : "";
                String id = idPrefix + generator.getName() + ".md";
                sb.append("[").append(generator.getName());

                if (meta != null && meta.getStability() != null && meta.getStability() != Stability.STABLE) {
                    sb.append(" (").append(meta.getStability().value()).append(")");
                }

                sb.append("](").append(id).append(")");

                // trailing space is important for markdown list formatting
                sb.append("  ");
            } else {
                sb.append("    - ");
                sb.append(generator.getName());

                if (meta != null && meta.getStability() != null && meta.getStability() != Stability.STABLE) {
                    sb.append(" (").append(meta.getStability().value()).append(")");
                }
            }
            sb.append(System.lineSeparator());
        });

        sb.append(System.lineSeparator());
        sb.append(System.lineSeparator());
    }
}
 
Example #28
Source File: Meta.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() {
    final File targetDir = new File(outputFolder);
    LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath());

    String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator";
    String kebabName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);

    List<SupportingFile> supportingFiles = "kotlin".equals(language) ?
            ImmutableList.of(
                    new SupportingFile("kotlin/build_gradle.mustache", "", "build.gradle.kts"),
                    new SupportingFile("kotlin/gradle.properties", "", "gradle.properties"),
                    new SupportingFile("kotlin/settings.mustache", "", "settings.gradle"),
                    new SupportingFile("kotlin/generatorClass.mustache", on(File.separator).join("src/main/kotlin", asPath(targetPackage)), mainClass.concat(".kt")),
                    new SupportingFile("kotlin/generatorClassTest.mustache", on(File.separator).join("src/test/kotlin", asPath(targetPackage)), mainClass.concat("Test.kt")),
                    new SupportingFile("kotlin/README.mustache", "", "README.md"),

                    new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
                    new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
                    new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
                    new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()))
            : ImmutableList.of(
                    new SupportingFile("pom.mustache", "", "pom.xml"),
                    new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
                    new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
                    new SupportingFile("README.mustache", "", "README.md"),
                    new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
                    new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
                    new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
                    new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));

    String currentVersion = buildInfo.getVersion();

    Map<String, Object> data =
            new ImmutableMap.Builder<String, Object>()
                    .put("generatorPackage", targetPackage)
                    .put("generatorClass", mainClass)
                    .put("name", name)
                    .put("kebabName", kebabName)
                    .put("generatorType", type)
                    .put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass)
                    .put("openapiGeneratorVersion", currentVersion).build();


    with(supportingFiles).convert(processFiles(targetDir, data));
}
 
Example #29
Source File: ObjcClientOptionsTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
Example #30
Source File: ServiceCombCodegenTest.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadImpl() {
  CodegenConfig codegenConfig = CodegenConfigLoader.forName("ServiceComb");
  Assert.assertEquals(ServiceCombCodegen.class, codegenConfig.getClass());
}