Java源码示例:org.openapitools.codegen.CodegenConfig

示例1
/**
 * 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);
        }
    }
}
 
示例2
@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"));
}
 
示例3
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;
  }
 
示例4
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;
}
 
示例5
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;
}
 
示例6
/**
 * 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);
        }
    }
}
 
示例7
/**
 * 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;
}
 
示例8
@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!");
}
 
示例9
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);
        }
    }
 
示例10
/**
 * 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();
    }
}
 
示例11
@Test
public void testLoadImpl() {
  CodegenConfig codegenConfig = CodegenConfigLoader.forName("SpringCloud");
  Assert.assertEquals(SpringCloudCodegen.class, codegenConfig.getClass());
}
 
示例12
@Test
public void testLoadImpl() {
  CodegenConfig codegenConfig = CodegenConfigLoader.forName("ServiceComb");
  Assert.assertEquals(ServiceCombCodegen.class, codegenConfig.getClass());
}
 
示例13
public static String getScheme(OpenAPI openAPI, CodegenConfig config) {
    URL url = getServerURL(openAPI, config.serverVariableOverrides());
    return getScheme(url, config);
}
 
示例14
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例15
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例16
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例17
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例18
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例19
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例20
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例21
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例22
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例23
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例24
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例25
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例26
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例27
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例28
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例29
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}
 
示例30
@Override
protected CodegenConfig getCodegenConfig() {
    return clientCodegen;
}