org.openapitools.codegen.config.CodegenConfigurator Java Examples

The following examples show how to use org.openapitools.codegen.config.CodegenConfigurator. 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: GenerateUtil.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
private static void commonConfig(CodegenConfigurator configurator, ServiceConfig service) {

    configurator
        .setGeneratorName(service.getMicroServiceFramework())
        .setGroupId(service.getGroupId())
        .setArtifactId(service.getArtifactId())
        .setModelPackage(service.getPackageName())
        .addAdditionalProperty("mainClassPackage", Optional.ofNullable(service.getPackageName()).orElse(""))
        .setArtifactVersion(service.getArtifactVersion())
        .addAdditionalProperty(ProjectMetaConstant.SERVICE_TYPE,
            Optional.ofNullable(service.getServiceType()).orElse("all"))
        .addAdditionalProperty(ProjectMetaConstant.SERVICE_ID, service.getServiceId());

    Optional.ofNullable(service.getProviderServiceId()).ifPresent(providerServiceId -> configurator
        .addAdditionalProperty(ProjectMetaConstant.PROVIDER_SERVICE_ID, service.getProviderServiceId()));

    if (MicroServiceFramework.SERVICECOMB.name().equalsIgnoreCase(service.getMicroServiceFramework())) {
      configurator.setLibrary(service.getProgrammingModel());
    }

    configurator.setApiPackage(
        Optional.ofNullable(service.getApiPackage()).orElse(String.format("%s.api", service.getPackageName())));
    configurator.setModelPackage(
        Optional.ofNullable(service.getModelPackage()).orElse(String.format("%s.model", service.getPackageName())));
  }
 
Example #2
Source File: AsciidocGeneratorTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateIndexAsciidocMarkupFileWithAsciidocGenerator() throws Exception {

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("asciidoc")
            .setInputSpec("src/test/resources/3_0/ping.yaml").setOutputDir(output.getAbsolutePath())
            .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY-SNIPPET-DIR")
            .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, "MY-SPEC-DIR");

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    generator.setGenerateMetadata(false);
    List<File> generatedFiles = generator.opts(clientOptInput).generate();
    TestUtils.ensureContainsFile(generatedFiles, output, "index.adoc");
}
 
Example #3
Source File: AsciidocSampleGeneratorTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void beforeClassGenerateTestMarkup() throws Exception {

    File outputTempDirectory = Files.createTempDirectory("test-asciidoc-sample-generator.").toFile();

    Assert.assertTrue(specDir.exists(), "test cancel, not specDir found to use." + specDir.getPath());
    Assert.assertTrue(snippetDir.exists(), "test cancel, not snippedDir found to use." + snippetDir.getPath());

    final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("asciidoc")
            .setInputSpec("src/test/resources/3_0/asciidoc/api-docs.json")
            .setOutputDir(outputTempDirectory.getAbsolutePath())
            .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, specDir.toString())
            .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, snippetDir.toString());

    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(configurator.toClientOptInput()).generate();

    for (File file : files) {
        if (file.getName().equals("index.adoc")) {
            this.markupFileName = file.getAbsoluteFile().toString();
            this.markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        }
    }
}
 
Example #4
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateApiWithPreceedingPathParameter_issue1347() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);
    properties.put(JavaJAXRSSpecServerCodegen.OPEN_API_SPEC_FILE_LOCATION, "openapi.yml");

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("jaxrs-spec")
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/issue_1347.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator(false);
    List<File> files = generator.opts(clientOptInput).generate();

    validateJavaSourceFiles(files);

    TestUtils.ensureContainsFile(files, output, "openapi.yml");
    TestUtils.ensureContainsFile(files, output, "src/gen/java/org/openapitools/api/DefaultApi.java");

    output.deleteOnExit();
}
 
Example #5
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePingAlternativeLocation2() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);
    properties.put(JavaJAXRSSpecServerCodegen.OPEN_API_SPEC_FILE_LOCATION, "openapi.yml");

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("jaxrs-spec")
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();

    validateJavaSourceFiles(files);
    TestUtils.ensureContainsFile(files, output, "openapi.yml");

    output.deleteOnExit();
}
 
Example #6
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePingAlternativeLocation1() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);
    properties.put(JavaJAXRSSpecServerCodegen.OPEN_API_SPEC_FILE_LOCATION, "src/main/resources/META-INF/openapi.yaml");

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("jaxrs-spec")
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();

    validateJavaSourceFiles(files);

    TestUtils.ensureContainsFile(files, output, "src/main/resources/META-INF/openapi.yaml");

    output.deleteOnExit();
}
 
Example #7
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePingNoSpecFile() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);
    properties.put(JavaJAXRSSpecServerCodegen.OPEN_API_SPEC_FILE_LOCATION, "");

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("jaxrs-spec")
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();

    validateJavaSourceFiles(files);
    TestUtils.ensureDoesNotContainsFile(files, output, "src/main/openapi/openapi.yaml");

    output.deleteOnExit();
}
 
Example #8
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePingDefaultLocation() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("jaxrs-spec")
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();

    validateJavaSourceFiles(files);

    TestUtils.ensureContainsFile(files, output, "src/main/openapi/openapi.yaml");

    output.deleteOnExit();
}
 
Example #9
Source File: JavaModelTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void generateModel() throws Exception {
    String inputSpec = "src/test/resources/3_0/petstore.json";

    final File output = Files.createTempDirectory("test").toFile();
    output.deleteOnExit();

    Assert.assertTrue(new File(inputSpec).exists());

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("java")
            .setLibrary("jersey2")
            //.addAdditionalProperty("withXml", true)
            .addAdditionalProperty(CodegenConstants.SERIALIZABLE_MODEL, true)
            .setInputSpec(inputSpec)
            .setOutputDir(output.getAbsolutePath());

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    new DefaultGenerator().opts(clientOptInput).generate();

    File orderFile = new File(output, "src/main/java/org/openapitools/client/model/Order.java");
    Assert.assertTrue(orderFile.exists());
}
 
Example #10
Source File: YamlGeneratorTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePingOtherOutputFile() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(OpenAPIYamlGenerator.OUTPUT_NAME, "ping.yaml");

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("openapi-yaml")
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();

    Assert.assertEquals(files.size(), 5);
    TestUtils.ensureContainsFile(files, output, "ping.yaml");
    TestUtils.ensureContainsFile(files, output, "README.md");
    TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore");
    TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES");
    TestUtils.ensureContainsFile(files, output, ".openapi-generator/VERSION");

    output.deleteOnExit();
}
 
Example #11
Source File: YamlGeneratorTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePing() throws Exception {
    Map<String, Object> properties = new HashMap<>();

    File output = Files.createTempDirectory("test").toFile();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("openapi-yaml")
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();
    Assert.assertEquals(files.size(), 5);
    TestUtils.ensureContainsFile(files, output, "openapi/openapi.yaml");
    TestUtils.ensureContainsFile(files, output, "README.md");
    TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore");
    TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES");
    TestUtils.ensureContainsFile(files, output, ".openapi-generator/VERSION");

    output.deleteOnExit();
}
 
Example #12
Source File: APIClientGenerationManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to generate SDK for a API for a given language
 *
 * @param apiName             name of the API
 * @param specLocation        location of the swagger spec for the API
 * @param sdkLanguage         preferred SDK language
 * @param temporaryOutputPath temporary location where the SDK archive is saved until downloaded
 */
private void generateClient(String apiName, String specLocation, String sdkLanguage, String temporaryOutputPath) {

    APIManagerConfiguration config = getAPIManagerConfiguration();
    CodegenConfigurator codegenConfigurator = new CodegenConfigurator();
    codegenConfigurator.setGroupId(config.getFirstProperty(APIConstants.CLIENT_CODEGEN_GROUPID));
    codegenConfigurator.setArtifactId(config.getFirstProperty(APIConstants.CLIENT_CODEGEN_ARTIFACTID) + apiName);
    codegenConfigurator
            .setModelPackage(config.getFirstProperty(APIConstants.CLIENT_CODEGEN_MODAL_PACKAGE) + apiName);
    codegenConfigurator.setApiPackage(config.getFirstProperty(APIConstants.CLIENT_CODEGEN_API_PACKAGE) + apiName);
    codegenConfigurator.setInputSpec(specLocation);
    codegenConfigurator.setGeneratorName(sdkLanguage);
    codegenConfigurator.setOutputDir(temporaryOutputPath);
    final ClientOptInput clientOptInput = codegenConfigurator.toClientOptInput();
    new DefaultGenerator().opts(clientOptInput).generate();

}
 
Example #13
Source File: GenerateTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void beforeEachTest() throws IOException {
    outputDirectory = Files.createTempDirectory("GenerateTest");
    generator = mock(DefaultGenerator.class);
    when(generator.generate()).thenReturn(new ArrayList<>());

    configurator = mock(CodegenConfigurator.class, mockSettings);
}
 
Example #14
Source File: DefaultGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void dryRunWithModelsOnly() throws IOException {
    Path target = Files.createTempDirectory("test");
    File output = target.toFile();
    try {
        final CodegenConfigurator configurator = new CodegenConfigurator()
                .setGeneratorName("java")
                .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml")
                .setOutputDir(target.toAbsolutePath().toString());

        final ClientOptInput clientOptInput = configurator.toClientOptInput();
        DefaultGenerator generator = new DefaultGenerator(true);

        generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true");
        generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.API_DOCS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.API_TESTS, "false");

        List<File> files = generator.opts(clientOptInput).generate();

        Assert.assertEquals(files.size(), 1);
        TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/model/SomeObj.java");
    } finally {
        output.delete();
    }
}
 
Example #15
Source File: DefaultGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void dryRunWithApisOnly() throws IOException {
    Path target = Files.createTempDirectory("test");
    File output = target.toFile();
    try {
        final CodegenConfigurator configurator = new CodegenConfigurator()
                .setGeneratorName("java")
                .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml")
                .setOutputDir(target.toAbsolutePath().toString());

        final ClientOptInput clientOptInput = configurator.toClientOptInput();
        DefaultGenerator generator = new DefaultGenerator(true);

        generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true");
        generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.API_DOCS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
        generator.setGeneratorPropertyDefault(CodegenConstants.API_TESTS, "false");

        List<File> files = generator.opts(clientOptInput).generate();

        Assert.assertEquals(files.size(), 1);
        TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/api/PingApi.java");
    } finally {
        output.delete();
    }
}
 
Example #16
Source File: GenerateBatchTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "customIncludeDeserializerFiles")
public void testDeserializerWithJsonInclude(String file) throws IOException {
    String config = getTargetResourceAsFile(file).toString();
    SimpleModule module = GenerateBatch.getCustomDeserializationModel(getIncludesDir());
    CodegenConfigurator loaded = CodegenConfigurator.fromFile(config, module);

    Map<String, Object> expectedAdditionalProperties = new HashMap<>();
    expectedAdditionalProperties.put("serverPort", "8082");
    expectedAdditionalProperties.put("dateLibrary", "java8");
    expectedAdditionalProperties.put("hideGenerationTimestamp", true);
    expectedAdditionalProperties.put("serializableModel", true);
    expectedAdditionalProperties.put("withXml", true);
    expectedAdditionalProperties.put("java8", true);
    expectedAdditionalProperties.put("useBeanValidation", true);

    assertNotNull(loaded);

    Context<?> context = loaded.toContext();
    WorkflowSettings workflowSettings = context.getWorkflowSettings();
    GeneratorSettings generatorSettings = context.getGeneratorSettings();

    assertNotNull(workflowSettings);
    assertNotNull(generatorSettings);

    assertEquals(generatorSettings.getGeneratorName(), "jaxrs-jersey");
    assertEquals(workflowSettings.getOutputDir(), "outputDir");
    assertEquals(workflowSettings.getInputSpec(), SPEC_FILE);
    assertTrue(generatorSettings.getAdditionalProperties().size() >= 7);

    Set<Map.Entry<String, Object>> actualSet = generatorSettings.getAdditionalProperties().entrySet();
    assertTrue(actualSet.containsAll(expectedAdditionalProperties.entrySet()));
}
 
Example #17
Source File: GenerateBatchTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
@Test(
        expectedExceptions = { RuntimeException.class },
        expectedExceptionsMessageRegExp = "Unable to deserialize config file: .*"
)
public void testInvalidDeserializerWithIncludeOption() {
    // JSON is valid YAML, but not the other way around, so we can't load a YAML include from a JSON config
    // to do so would require additional work.
    String config = getTargetResourceAsFile(JAXRS_DATELIB_J8_YAML_INCLUDE_JSON).toString();
    SimpleModule module = GenerateBatch.getCustomDeserializationModel(getIncludesDir());
    CodegenConfigurator loaded = CodegenConfigurator.fromFile(config, module);
    fail("Expected an exception when trying to load a YAML include from a JSON file");
}
 
Example #18
Source File: MyclientcodegenGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void launchCodeGenerator() {
  // to understand how the 'openapi-generator-cli' module is using 'CodegenConfigurator', have a look at the 'Generate' class:
  // https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java 
  final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("myClientCodegen") // use this codegen library
            .setInputSpec("../../../modules/openapi-generator/src/test/resources/2_0/petstore.yaml") // sample OpenAPI file
            // .setInputSpec("https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml") // or from the server
            .setOutputDir("out/myClientCodegen"); // output directory

  final ClientOptInput clientOptInput = configurator.toClientOptInput();
  DefaultGenerator generator = new DefaultGenerator();
  generator.opts(clientOptInput).generate();
}
 
Example #19
Source File: ApiGenerator.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
protected void generate(MustacheFactory mf, File javaSrcDir, Database database, HashMap<String, String> parentMap)
        throws Exception {
    log.info("Starting to Generate the Java classes for OpenAPI document: " + this.openApiFile.getCanonicalPath());
    String packageName = parentMap.get("packageName");
    String outputDir = this.outputDirectory.getAbsolutePath();

    CodegenConfigurator configurator = new CodegenConfigurator();
    configurator.setPackageName(packageName);
    configurator.setApiPackage(packageName);
    configurator.addDynamicProperty("configPackage", packageName);
    configurator.addDynamicProperty("basePackage", packageName);
    configurator.setModelPackage(packageName);

    //configurator.addSystemProperty("models", "");
    //configurator.addSystemProperty("modelDocs", "false");
    //configurator.addSystemProperty("modelTests", "false");

    configurator.setInputSpec(this.openApiFile.getAbsolutePath());

    configurator.setGeneratorName("org.teiid.maven.TeiidCodegen");
    configurator.setOutputDir(outputDir);
    configurator.setLibrary("spring-boot");
    configurator.addDynamicProperty("delegatePattern", "true");
    configurator.setIgnoreFileOverride(null);

    final ClientOptInput input = configurator.toClientOptInput();
    new DefaultGenerator().opts(input).generate();

    log.info("Generated the Java classes for OpenAPI document: " + this.openApiFile.getCanonicalPath());
}
 
Example #20
Source File: AsciidocGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderAttributesFlagRemovesAttributesFromMarkupHeaderSection() throws Exception {
    File output = Files.createTempDirectory("test").toFile();

    LOGGER.info("test: generating sample markup " + output.getAbsolutePath());

    Map<String, Object> props = new TreeMap<String, Object>();
    props.put("specDir", "spec");

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("asciidoc")
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath())
            .addAdditionalProperty(AsciidocDocumentationCodegen.HEADER_ATTRIBUTES_FLAG, "false")    // option avoids generation of attributes
            .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, "SPEC-DIR")
            .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY/SNIPPET/DIR");

    DefaultGenerator generator = new DefaultGenerator();
    boolean markupFileGenerated = false;
    List<File> files = generator.opts(configurator.toClientOptInput()).generate();
    for (File file : files) {
        if (file.getName().equals("index.adoc")) {
            markupFileGenerated = true;
            String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
            Assert.assertFalse(markupContent.contains(":specDir: SPEC-DIR"),
                    "not expected :specDir: in: " + markupContent.substring(0, 250));
            Assert.assertFalse(markupContent.contains(":snippetDir: MY/SNIPPET/DIR"),
                    "not expected :snippetDir: in: " + markupContent.substring(0, 250));
            Assert.assertFalse(markupContent.contains(":toc:"),
                    "not expected :toc: in: " + markupContent.substring(0, 250));               // typical attributes not found in markup.
        }
    }
    Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!");
}
 
Example #21
Source File: AsciidocGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdditionalDirectoriesGeneratedIntoHeaderAttributes() throws Exception {
    File output = Files.createTempDirectory("test").toFile();

    LOGGER.info("test: generating sample markup " + output.getAbsolutePath());

    Map<String, Object> props = new TreeMap<String, Object>();
    props.put("specDir", "spec");

    final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("asciidoc")
            .setInputSpec("src/test/resources/3_0/ping.yaml").setOutputDir(output.getAbsolutePath())
            .addAdditionalProperty(AsciidocDocumentationCodegen.SPEC_DIR, "SPEC-DIR")
            .addAdditionalProperty(AsciidocDocumentationCodegen.SNIPPET_DIR, "MY/SNIPPET/DIR");

    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(configurator.toClientOptInput()).generate();
    boolean markupFileGenerated = false;
    for (File file : files) {
        if (file.getName().equals("index.adoc")) {
            markupFileGenerated = true;
            String markupContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
            Assert.assertTrue(markupContent.contains(":specDir: SPEC-DIR"),
                    "expected :specDir: in: " + markupContent.substring(0, 250));
            Assert.assertTrue(markupContent.contains(":snippetDir: MY/SNIPPET/DIR"),
                    "expected :snippetDir: in: " + markupContent.substring(0, 250));
        }
    }
    Assert.assertTrue(markupFileGenerated, "index.adoc is not generated!");

}
 
Example #22
Source File: DefaultCodeGenerator.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Map<String, Object> config) {

  generator.setGenerateMetadata(false);
  List<CodegenConfigurator> optsList = (List<CodegenConfigurator>) config.get("configurators");
  if (optsList == null) {
    generator.addOpts(((CodegenConfigurator) config.get("configurator")).toClientOptInput());
    return;
  }
  optsList.forEach(opts -> {
    generator.addOpts(opts.toClientOptInput());
  });
}
 
Example #23
Source File: ScalaAkkaClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "override only mainPackage")
public void mainPackageTest() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put("mainPackage", "hello.world");

    File output = Files.createTempDirectory("test").toFile();
    output.deleteOnExit();

    final DefaultCodegen codegen = new ScalaAkkaClientCodegen();
    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName(codegen.getName())
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/scala_reserved_words.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator(false);

    generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true");
    generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true");

    Generator gen = generator.opts(clientOptInput);
    List<File> files = gen.generate();

    Assert.assertEquals(files.size(), 15);

    TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/model/SomeObj.scala");
    TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/core/ApiSettings.scala");
    TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/api/PingApi.scala");
}
 
Example #24
Source File: GeneratorTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private void generateServiceCombCode(String programmingModel)
    throws IOException, URISyntaxException, IllegalAccessException, NoSuchFieldException {

  Path tempDir = Files.createTempDirectory(null);
  Path specFilePath = Paths.get(GeneratorTest.class.getClassLoader().getResource("swagger.yaml").toURI());
  CodegenConfigurator configurator = new CodegenConfigurator();

  configurator.setGeneratorName("ServiceComb");
  configurator.setLibrary(programmingModel);
  configurator.setOutputDir(tempDir.toFile().getCanonicalPath() + "/ServiceComb");
  configurator.setInputSpec(specFilePath.toFile().getCanonicalPath());
  configurator.addAdditionalProperty(GeneratorExternalConfigConstant.PROVIDER_PROJECT_NAME, "mock-provider");
  configurator.addAdditionalProperty(GeneratorExternalConfigConstant.CONSUMER_PROJECT_NAME, "mock-consumer");
  configurator.addAdditionalProperty(GeneratorExternalConfigConstant.MODEL_PROJECT_NAME, "mock-model");
  DefaultCodeGenerator codeGenerator = new DefaultCodeGenerator();
  codeGenerator.configure(Collections.singletonMap("configurators", Collections.singletonList(configurator)));

  try {
    codeGenerator.generate();
  } catch (RuntimeException e) {
    fail("Run 'testGenerateProgrammingModels' failed while input " + programmingModel
        + " unexpected to catch RuntimeException: " + e.getMessage());
  }

  Object internalGenerator = ReflectUtils.getProperty(codeGenerator, "generator");
  Assert.assertEquals(MultiContractGenerator.class, internalGenerator.getClass());
  Object swaggerCodegenConfig = ReflectUtils.getProperty(internalGenerator, "config");
  Assert.assertEquals(ServiceCombCodegen.class, swaggerCodegenConfig.getClass());
  Assert.assertEquals("ServiceComb", ((ServiceCombCodegen) swaggerCodegenConfig).getName());
  Assert.assertEquals(CodegenType.SERVER, ((ServiceCombCodegen) swaggerCodegenConfig).getTag());

  tempDir.toFile().deleteOnExit();
}
 
Example #25
Source File: GeneratorTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpringCloudProject()
    throws IOException, URISyntaxException, IllegalAccessException, NoSuchFieldException {

  Path tempDir = Files.createTempDirectory(null);
  Path specFilePath = Paths.get(GeneratorTest.class.getClassLoader().getResource("swagger.yaml").toURI());
  CodegenConfigurator configurator = new CodegenConfigurator();

  configurator.setGeneratorName("SpringCloud");
  configurator.setOutputDir(tempDir.toFile().getCanonicalPath() + "/SpringCloud");
  configurator.setInputSpec(specFilePath.toFile().getCanonicalPath());
  configurator.addAdditionalProperty(GeneratorExternalConfigConstant.PROVIDER_PROJECT_NAME, "mock-provider");
  configurator.addAdditionalProperty(GeneratorExternalConfigConstant.CONSUMER_PROJECT_NAME, "mock-consumer");
  configurator.addAdditionalProperty(GeneratorExternalConfigConstant.MODEL_PROJECT_NAME, "mock-model");
  DefaultCodeGenerator codeGenerator = new DefaultCodeGenerator();
  codeGenerator.configure(Collections.singletonMap("configurators", Collections.singletonList(configurator)));

  try {
    codeGenerator.generate();
  } catch (RuntimeException e) {
    fail("Run 'testGenerateProgrammingModels' failed. Unexpected to catch RuntimeException: " + e.getMessage());
  }

  Object internalGenerator = ReflectUtils.getProperty(codeGenerator, "generator");
  Assert.assertEquals(MultiContractGenerator.class, internalGenerator.getClass());
  Object swaggerCodegenConfig = ReflectUtils.getProperty(internalGenerator, "config");
  Assert.assertEquals(SpringCloudCodegen.class, swaggerCodegenConfig.getClass());
  Assert.assertEquals("SpringCloud", ((SpringCloudCodegen) swaggerCodegenConfig).getName());
  Assert.assertEquals(CodegenType.SERVER, ((SpringCloudCodegen) swaggerCodegenConfig).getTag());
  Assert
      .assertEquals("Generates a SpringCloud server library.", ((SpringCloudCodegen) swaggerCodegenConfig).getHelp());

  tempDir.toFile().deleteOnExit();
}
 
Example #26
Source File: JavaClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testJdkHttpClient() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);
    properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");

    File output = Files.createTempDirectory("test").toFile();
    output.deleteOnExit();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("java")
            .setLibrary(JavaClientCodegen.NATIVE)
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/ping.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();

    Assert.assertEquals(files.size(), 28);
    validateJavaSourceFiles(files);

    TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"),
            "public class DefaultApi",
            "import java.net.http.HttpClient;",
            "import java.net.http.HttpRequest;",
            "import java.net.http.HttpResponse;");

    TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"),
            "public class ApiClient",
            "import java.net.http.HttpClient;",
            "import java.net.http.HttpRequest;");
}
 
Example #27
Source File: JavaClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testJdkHttpAsyncClient() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);
    properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
    properties.put(JavaClientCodegen.ASYNC_NATIVE, true);

    File output = Files.createTempDirectory("test").toFile();
    output.deleteOnExit();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("java")
            .setLibrary(JavaClientCodegen.NATIVE)
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(clientOptInput).generate();

    Assert.assertEquals(files.size(), 30);
    validateJavaSourceFiles(files);

    Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/PingApi.java");
    TestUtils.assertFileContains(defaultApi,
            "public class PingApi",
            "import java.net.http.HttpClient;",
            "import java.net.http.HttpRequest;",
            "import java.net.http.HttpResponse;",
            "import java.util.concurrent.CompletableFuture;");

    Path apiClient = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java");
    TestUtils.assertFileContains(apiClient,
            "public class ApiClient",
            "import java.net.http.HttpClient;",
            "import java.net.http.HttpRequest;");
}
 
Example #28
Source File: JavaClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizationScopeValues_Issue6733() throws IOException {
    File output = Files.createTempDirectory("test").toFile();
    output.deleteOnExit();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("java")
            .setLibrary(JavaClientCodegen.RESTEASY)
            .setValidateSpec(false)
            .setInputSpec("src/test/resources/3_0/regression-6734.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();

    DefaultGenerator generator = new DefaultGenerator();
    generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true");
    // tests if NPE will crash generation when path in yaml arent provided
    generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false");
    generator.setGenerateMetadata(false);
    List<File> files = generator.opts(clientOptInput).generate();

    Assert.assertEquals(files.size(), 1);
    files.forEach(File::deleteOnExit);
}
 
Example #29
Source File: ScalaAkkaClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "override api packages")
public void overridePackagesTest() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put("mainPackage", "hello.world");
    properties.put("apiPackage", "hello.world.api.package");
    properties.put("modelPackage", "hello.world.model.package");
    properties.put("invokerPackage", "hello.world.package.invoker");

    File output = Files.createTempDirectory("test").toFile();
    output.deleteOnExit();

    final DefaultCodegen codegen = new ScalaAkkaClientCodegen();
    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName(codegen.getName())
            .setAdditionalProperties(properties)
            .setInputSpec("src/test/resources/3_0/scala_reserved_words.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    DefaultGenerator generator = new DefaultGenerator();

    generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true");
    generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true");

    Generator gen = generator.opts(clientOptInput);

    List<File> files = gen.generate();
    Assert.assertEquals(files.size(), 15);

    TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/model/package/SomeObj.scala");
    TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/package/invoker/ApiSettings.scala");
    TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/api/package/PingApi.scala");
}
 
Example #30
Source File: JavaClientCodegenTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * See https://github.com/OpenAPITools/openapi-generator/issues/3589
 */
@Test
public void testImportMapping() throws IOException {

    Map<String, Object> properties = new HashMap<>();
    properties.put(JavaClientCodegen.JAVA8_MODE, true);
    properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");

    Map<String, String> importMappings = new HashMap<>();
    importMappings.put("TypeAlias", "foo.bar.TypeAlias");

    File output = Files.createTempDirectory("test").toFile();
    output.deleteOnExit();

    final CodegenConfigurator configurator = new CodegenConfigurator()
            .setGeneratorName("java")
            .setLibrary(JavaClientCodegen.RESTEASY)
            .setAdditionalProperties(properties)
            .setImportMappings(importMappings)
            .setInputSpec("src/test/resources/3_0/type-alias.yaml")
            .setOutputDir(output.getAbsolutePath().replace("\\", "/"));

    final ClientOptInput clientOptInput = configurator.toClientOptInput();
    Assert.assertEquals(clientOptInput.getConfig().importMapping().get("TypeAlias"), "foo.bar.TypeAlias");

    DefaultGenerator generator = new DefaultGenerator();
    generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "false");
    generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false");
    generator.setGenerateMetadata(false);
    List<File> files = generator.opts(clientOptInput).generate();
    files.forEach(File::deleteOnExit);

    Assert.assertEquals(files.size(), 1);
    TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/model/ParentType.java");

    String parentTypeContents = "";
    try {
        File file = files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get();
        parentTypeContents = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
    } catch (IOException ignored) {

    }

    final Pattern FIELD_PATTERN = Pattern.compile(".* private (.*?) typeAlias;.*", Pattern.DOTALL);
    Matcher fieldMatcher = FIELD_PATTERN.matcher(parentTypeContents);
    Assert.assertTrue(fieldMatcher.matches());

    // this is the type of the field 'typeAlias'. With a working importMapping it should
    // be 'foo.bar.TypeAlias' or just 'TypeAlias'
    Assert.assertEquals(fieldMatcher.group(1), "foo.bar.TypeAlias");
}