io.swagger.parser.OpenAPIParser Java Examples

The following examples show how to use io.swagger.parser.OpenAPIParser. 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: APIMgtLatencyStatsHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void setSwaggerToMessageContext(MessageContext messageContext) {
    // Read OpenAPI from local entry
    if (openAPI == null && apiUUID != null) {
        synchronized (this) {
            if (openAPI == null) {
                long startTime = System.currentTimeMillis();
                Entry localEntryObj = (Entry) messageContext.getConfiguration().getLocalRegistry().get(apiUUID);
                if (localEntryObj != null) {
                    swagger = localEntryObj.getValue().toString();
                    OpenAPIParser parser = new OpenAPIParser();
                    openAPI = parser.readContents(swagger,
                            null, null).getOpenAPI();
                }
                long endTime = System.currentTimeMillis();
                if (log.isDebugEnabled()) {
                    log.debug("Time to parse the swagger(ms) : " + (endTime - startTime));
                }
            }
        }
    }
    // Add OpenAPI to message context
    messageContext.setProperty(APIMgtGatewayConstants.OPEN_API_OBJECT, openAPI);
    // Add swagger String to message context
    messageContext.setProperty(APIMgtGatewayConstants.OPEN_API_STRING, swagger);
}
 
Example #2
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void addsImportForSetArgument() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
        .readLocation("src/test/resources/3_0/arrayParameter.yaml", null, new ParseOptions()).getOpenAPI();

    openAPI.getComponents().getParameters().get("operationsQueryParam").setSchema(new ArraySchema().uniqueItems(true));
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
        .openAPI(openAPI)
        .config(codegen);

    DefaultGenerator generator = new DefaultGenerator(false);
    generator.opts(input).generate();

    Path path = Paths.get(outputPath + "/src/gen/java/org/openapitools/api/ExamplesApi.java");

    assertFileContains(path, "\nimport java.util.Set;\n");
}
 
Example #3
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void addsImportForSetResponse() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
        .readLocation("src/test/resources/3_0/setResponse.yaml", null, new ParseOptions()).getOpenAPI();

    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
        .openAPI(openAPI)
        .config(codegen);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(input).generate();

    Path path = Paths.get(outputPath + "/src/gen/java/org/openapitools/api/ExamplesApi.java");

    assertFileContains(path, "\nimport java.util.Set;\n");
}
 
Example #4
Source File: JavaJaxrsBaseTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotAddDefaultValueDocumentationForContainers() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/arrayParameter.yaml", null, new ParseOptions()).getOpenAPI();
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
            .openAPI(openAPI)
            .config(codegen);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(input).generate();

    assertFileNotContains(Paths.get(outputPath + "/src/gen/java/org/openapitools/api/ExamplesApi.java"),  "DefaultValue");
}
 
Example #5
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private Map<String, File> generateFiles(SpringCodegen codegen, String filePath) throws IOException {
    final File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    final String outputPath = output.getAbsolutePath().replace('\\', '/');

    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    final ClientOptInput input = new ClientOptInput();
    final OpenAPI openAPI = new OpenAPIParser().readLocation(filePath, null, new ParseOptions()).getOpenAPI();
    input.openAPI(openAPI);
    input.config(codegen);

    final DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(input).generate();

    return files.stream().collect(Collectors.toMap(e -> e.getName().replace(outputPath, ""), i -> i));
}
 
Example #6
Source File: JavaJaxrsBaseTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void addDefaultValueDocumentationForNonContainers() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/arrayParameter.yaml", null, new ParseOptions()).getOpenAPI();

    openAPI.getComponents().getParameters().get("operationsQueryParam").setSchema(new StringSchema()._default("default"));
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
    .openAPI(openAPI)
    .config(codegen);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/gen/java/org/openapitools/api/ExamplesApi.java"),  "DefaultValue");
}
 
Example #7
Source File: HaskellServantCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateRootEndpoint() throws IOException {
    // given
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    final HaskellServantCodegen codegen = new HaskellServantCodegen();
    codegen.setOutputDir(output.getAbsolutePath());

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/rootOperation.yaml", null, new ParseOptions())
            .getOpenAPI();

    ClientOptInput input = new ClientOptInput();
    input.setOpenAPI(openAPI);
    input.setConfig(codegen);

    // when
    DefaultGenerator generator = new DefaultGenerator();
    generator.setGenerateMetadata(false);
    generator.opts(input).generate();

    // then
    TestUtils.assertFileNotContains(Paths.get(outputPath + "/lib/RootOperation/API.hs"), "\"\" :>");
}
 
Example #8
Source File: OpenAPIStyleValidatorTask.java    From openapi-style-validator with Apache License 2.0 6 votes vote down vote up
@TaskAction
public void execute() {
    if (inputFile == null) {
        throw new GradleException(String.format("The input file is not defined, set the '%s' option", INPUT_FILE));
    }
    getLogger().quiet(String.format("Validating spec: %s", inputFile));

    OpenAPIParser openApiParser = new OpenAPIParser();
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);

    SwaggerParseResult parserResult = openApiParser.readLocation(inputFile, null, parseOptions);
    io.swagger.v3.oas.models.OpenAPI swaggerOpenAPI = parserResult.getOpenAPI();

    org.eclipse.microprofile.openapi.models.OpenAPI openAPI = SwAdapter.toOpenAPI(swaggerOpenAPI);
    OpenApiSpecStyleValidator openApiSpecStyleValidator = new OpenApiSpecStyleValidator(openAPI);

    ValidatorParameters parameters = createValidatorParameters();
    List<StyleError> result = openApiSpecStyleValidator.validate(parameters);
    if (!result.isEmpty()) {
        getLogger().error("OpenAPI Specification does not meet the requirements. Issues:\n");
        result.stream().map(StyleError::toString).forEach(m -> getLogger().error(String.format("\t%s", m)));
        throw new GradleException("OpenAPI Style validation failed");
    }
}
 
Example #9
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private static SwaggerParseResult getParseResult(
        CodegenConfigurator configurator) {
    try {
        List<AuthorizationValue> authorizationValues = AuthParser
                .parse(configurator.getAuth());
        String inputSpec = configurator.loadSpecContent(
                configurator.getInputSpecURL(), authorizationValues);
        ParseOptions options = new ParseOptions();
        options.setResolve(true);
        return new OpenAPIParser().readContents(inputSpec,
                authorizationValues, options);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unexpected error while generating vaadin-connect TypeScript endpoint wrappers. "
                        + String.format("Can't read file '%s'",
                                configurator.getInputSpecURL()),
                e);
    }
}
 
Example #10
Source File: OpenAPIConfiguration.java    From openapi-petstore with Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI openapi(
        @Value("classpath:/openapi.yaml") Resource openapiResource,
        @Value("${openapi.openAPIPetstore.base-path:/v3}") String apiBasePath) throws IOException {
    try(InputStream is = openapiResource.getInputStream()) {
        OpenAPI openAPI = new OpenAPIParser()
                .readContents(StreamUtils.copyToString(is, Charset.defaultCharset()), null, new ParseOptions())
                .getOpenAPI();
        ObjectNode node = Yaml.mapper().readValue(openapiResource.getInputStream(), ObjectNode.class);
        if (node.get("servers") == null) {
            openAPI.setServers(Collections.singletonList(new Server().url(apiBasePath)));
        }
        return openAPI;
    }
}
 
Example #11
Source File: KotlinModelCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private void checkModel(AbstractKotlinCodegen codegen, boolean mutable, String... props) throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/generic.yaml", null, new ParseOptions()).getOpenAPI();
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "models");
    codegen.additionalProperties().put(AbstractKotlinCodegen.MODEL_MUTABLE, mutable);

    ClientOptInput input = new ClientOptInput()
            .openAPI(openAPI)
            .config(codegen);

    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, "true");

    generator.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/main/kotlin/models/Animal.kt"), props);
}
 
Example #12
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void importMapping() {
    DefaultCodegen codegen = new DefaultCodegen();
    codegen.importMapping.put("TypeAlias", "foo.bar.TypeAlias");

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/type-alias.yaml", null, new ParseOptions()).getOpenAPI();
    codegen.setOpenAPI(openAPI);

    CodegenModel codegenModel = codegen.fromModel("ParentType", openAPI.getComponents().getSchemas().get("ParentType"));

    Assert.assertEquals(codegenModel.vars.size(), 1);
    Assert.assertEquals(codegenModel.vars.get(0).getBaseType(), "TypeAlias");
}
 
Example #13
Source File: Main.java    From openapi-style-validator with Apache License 2.0 5 votes vote down vote up
static List<StyleError> validate(OptionManager optionManager, CommandLine commandLine) {
    OpenAPIParser openApiParser = new OpenAPIParser();
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);

    SwaggerParseResult parserResult = openApiParser.readLocation(optionManager.getSource(commandLine), null, parseOptions);
    io.swagger.v3.oas.models.OpenAPI swaggerOpenAPI = parserResult.getOpenAPI();

    org.eclipse.microprofile.openapi.models.OpenAPI openAPI = SwAdapter.toOpenAPI(swaggerOpenAPI);
    OpenApiSpecStyleValidator openApiSpecStyleValidator = new OpenApiSpecStyleValidator(openAPI);

    ValidatorParameters parameters = optionManager.getOptionalValidatorParametersOrDefault(commandLine);
    return openApiSpecStyleValidator.validate(parameters);
}
 
Example #14
Source File: SwaggerConverter.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private OpenAPI parseV2(ParseOptions options) {
    OpenAPI openAPI;
    try {
        openAPI = new OpenAPIParser().readContents(this.defn, null, options).getOpenAPI();
        // parse again to resolve refs , may be there is a cleaner way
        String string =
                Yaml.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(openAPI);
        openAPI = new OpenAPIV3Parser().readContents(string, null, options).getOpenAPI();
    } catch (JsonProcessingException e) {
        LOG.warn(e.getMessage());
        openAPI = null;
    }
    return openAPI;
}
 
Example #15
Source File: SwaggerConverter.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public List<String> getErrorMessages() {
    ParseOptions options = new ParseOptions();
    options.setResolveFully(true);
    SwaggerParseResult res =
            new OpenAPIV3Parser().readContents(this.defn, new ArrayList<>(), options);
    if (res.getOpenAPI() == null) {
        // try v2
        res = new OpenAPIParser().readContents(this.defn, new ArrayList<>(), options);
    }
    if (res != null && res.getMessages() != null) {
        errors.addAll(res.getMessages());
    }
    errors.addAll(this.generators.getErrorMessages());
    return errors;
}
 
Example #16
Source File: JavaJaxrsBaseTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void doNotGenerateJsonAnnotationForPolymorphismIfJsonExclude() throws IOException {
    codegen.additionalProperties().put("jackson", false);
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/generic.yaml", null, new ParseOptions()).getOpenAPI();
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
            .openAPI(openAPI)
            .config(codegen);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(input).generate();


    String jsonTypeInfo = "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = \"className\", visible = true)";
    String jsonSubType = "@JsonSubTypes({\n" +
            "  @JsonSubTypes.Type(value = Dog.class, name = \"Dog\"),\n" +
            "  @JsonSubTypes.Type(value = Cat.class, name = \"Cat\"),\n" +
            "})";
    assertFileNotContains(Paths.get(outputPath + "/src/gen/java/org/openapitools/model/Animal.java"),  jsonTypeInfo, jsonSubType);
}
 
Example #17
Source File: JavaJaxrsBaseTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void generateJsonAnnotationForPolymorphism() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/generic.yaml", null, new ParseOptions()).getOpenAPI();
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
            .openAPI(openAPI)
            .config(codegen);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(input).generate();

    String jsonTypeInfo = "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = \"className\", visible = true)";
    String jsonSubType = "@JsonSubTypes({\n" +
            "  @JsonSubTypes.Type(value = Dog.class, name = \"Dog\"),\n" +
            "  @JsonSubTypes.Type(value = Cat.class, name = \"Cat\"),\n" +
            "  @JsonSubTypes.Type(value = BigDog.class, name = \"BigDog\"),\n" +
            "})";
    assertFileContains(Paths.get(outputPath + "/src/gen/java/org/openapitools/model/Animal.java"), jsonTypeInfo, jsonSubType);
}
 
Example #18
Source File: GenerateUtil.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
static void generateDocument(String contractLocation, String documentOutput, String type) throws IOException {

    // TODO: support users to addParamCtx other getGenerator type soon
    DocGenerator docGenerator = GeneratorFactory.getGenerator(DocGenerator.class, type);
    if (docGenerator == null) {
      throw new RuntimeException("Cannot found document generator's implementation");
    }

    Files.walkFileTree(Paths.get(contractLocation), new SimpleFileVisitor<Path>() {

      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

        if (Files.isDirectory(file)) {
          return super.visitFile(file, attrs);
        }
        Map<String, Object> docGeneratorConfig = new HashMap<>();

        SwaggerParseResult swaggerParseResult = new OpenAPIParser()
            .readLocation(file.toUri().toURL().toString(), null, null);
        OpenAPI openAPI = swaggerParseResult.getOpenAPI();
        if (openAPI == null) {
          return super.visitFile(file, attrs);
        }
        docGeneratorConfig.put("contractContent", openAPI);
        docGeneratorConfig.put("outputPath",
            documentOutput + File.separator + file.getParent().toFile().getName() + File.separator + file.toFile()
                .getName()
                .substring(0, file.toFile().getName().indexOf(".")));

        docGenerator.configure(docGeneratorConfig);
        docGenerator.generate();

        return super.visitFile(file, attrs);
      }
    });
  }
 
Example #19
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void generateFormatForDateAndDateTimeQueryParam() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/issue_2053.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.openAPI(openAPI);
    input.config(codegen);

    DefaultGenerator generator = new DefaultGenerator();

    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.opts(input).generate();

    assertFileContains(
            Paths.get(outputPath + "/src/main/java/org/openapitools/api/ElephantsApi.java"),
            "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)"
    );
    assertFileContains(
            Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java"),
            "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)"
    );
}
 
Example #20
Source File: ContractsSwaggerUIGeneratorTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Test
public void testContractTransferToSwaggerUI() throws IOException {

  InputStream in = ContractsSwaggerUIGeneratorTest.class.getClassLoader().getResourceAsStream("HelloEndPoint.yaml");

  StringBuilder sb = new StringBuilder();
  byte[] bytes = new byte[1024];
  int len = -1;
  while ((len = in.read(bytes)) != -1) {
    sb.append(new String(bytes, 0, len));
  }

  OpenAPIParser openAPIParser = new OpenAPIParser();
  SwaggerParseResult swaggerParseResult = openAPIParser.readContents(sb.toString(), null, null);

  Path tempDir = Files.createTempDirectory(null);
  Path outputPath = Paths.get(tempDir.toFile().getAbsolutePath()
      + File.separator + "swagger-ui.html");
  DocGenerator docGenerator = GeneratorFactory.getGenerator(DocGenerator.class, "default");
  Map<String, Object> docGeneratorConfig = new HashMap<>();
  docGeneratorConfig.put("contractContent", swaggerParseResult.getOpenAPI());
  docGeneratorConfig.put("outputPath", outputPath.toFile().getCanonicalPath());
  Objects.requireNonNull(docGenerator).configure(docGeneratorConfig);
  docGenerator.generate();

  Assert.assertTrue(Files.exists(outputPath));
  FileUtils.deleteDirectory(tempDir.toFile());
}
 
Example #21
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 #22
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void doAnnotateDatesOnModelParameters() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/issue_5436.yml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.openAPI(openAPI);
    input.config(codegen);

    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, "false");

    generator.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java"),
            "AnimalParams");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/model/AnimalParams.java"),
            "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)",
            "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)");
}
 
Example #23
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void doGenerateCookieParams() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/issue_5386.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.openAPI(openAPI);
    input.config(codegen);

    DefaultGenerator generator = new DefaultGenerator();

    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.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ElephantsApi.java"), "@CookieValue");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java"), "@CookieValue");
    assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/BirdsApi.java"), "@CookieValue");
}
 
Example #24
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void doGenerateRequestParamForSimpleParam() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/issue_3248.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.openAPI(openAPI);
    input.config(codegen);

    DefaultGenerator generator = new DefaultGenerator();

    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.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/MonkeysApi.java"), "@RequestParam");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ElephantsApi.java"), "@RequestParam");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java"), "@RequestParam");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/BearsApi.java"), "@RequestParam");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/CamelsApi.java"), "@RequestParam");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/PandasApi.java"), "@RequestParam");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/CrocodilesApi.java"), "@RequestParam");
    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/PolarBearsApi.java"), "@RequestParam");
}
 
Example #25
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void doNotGenerateRequestParamForObjectQueryParam() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/objectQueryParam.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.setOpenAPI(openAPI);
    input.setConfig(codegen);

    DefaultGenerator generator = new DefaultGenerator();

    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.opts(input).generate();

    assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/PonyApi.java"), "@RequestParam");
}
 
Example #26
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGenerateRequestParamForRefParams_3248_Regression() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/3248-regression.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.setOpenAPI(openAPI);
    input.setConfig(codegen);

    DefaultGenerator generator = new DefaultGenerator();

    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.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java"),
            "@RequestParam(value = \"format\"",
            "@RequestParam(value = \"query\"");
}
 
Example #27
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGenerateRequestParamForRefParams_3248_RegressionDates() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/3248-regression-dates.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.setOpenAPI(openAPI);
    input.setConfig(codegen);

    DefaultGenerator generator = new DefaultGenerator();

    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.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java"),
            "@RequestParam(value = \"start\"");
}
 
Example #28
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGenerateRequestBodyRequiredAttribute_3134_Regression() throws Exception {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/3134-regression.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput();
    input.setOpenAPI(openAPI);
    input.setConfig(codegen);

    DefaultGenerator generator = new DefaultGenerator();

    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.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java"),
            "@RequestBody(required = false");
}
 
Example #29
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private void beanValidationForFormatEmail(boolean useBeanValidation, boolean performBeanValidation, boolean java8, String contains, String notContains) throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/issue_4876_format_email.yaml", null, new ParseOptions()).getOpenAPI();

    SpringCodegen codegen = new SpringCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.setUseBeanValidation(useBeanValidation);
    codegen.setPerformBeanValidation(performBeanValidation);
    codegen.setJava8(java8);

    ClientOptInput input = new ClientOptInput();
    input.openAPI(openAPI);
    input.config(codegen);

    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");

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

    assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/model/PersonWithEmail.java"), contains);
    assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/model/PersonWithEmail.java"), notContains);
}
 
Example #30
Source File: JWTValidatorTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testJWTValidatorExpiredInCacheTenant() throws ParseException, APISecurityException,
        APIManagementException,
        IOException {

    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com");
    SignedJWT signedJWT =
            SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" +
                    "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" +
                    ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" +
                    "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" +
                    "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" +
                    "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" +
                    "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" +
                    "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" +
                    "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" +
                    ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" +
                    "CEFVQS1U3oY9" +
                    "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" +
                    "UMTwZ8" +
                    "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" +
                    "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" +
                    "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" +
                    "EuSe9w");
    JWTConfigurationDto jwtConfigurationDto = new JWTConfigurationDto();
    JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class);
    APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class);
    Cache gatewayTokenCache = Mockito.mock(Cache.class);
    Cache invalidTokenCache = Mockito.mock(Cache.class);
    Cache gatewayKeyCache = Mockito.mock(Cache.class);
    Cache gatewayJWTTokenCache = Mockito.mock(Cache.class);
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    jwtValidationInfo.setValid(true);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis());
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5L);
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    Mockito.when(jwtValidationService.validateJWTToken(signedJWT)).thenReturn(jwtValidationInfo);
    JWTValidatorWrapper jwtValidator
            = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto,
            jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt =
            Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS))
            .thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus");
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION))
            .thenReturn("true");
    jwtValidator.setApiManagerConfiguration(apiManagerConfiguration);
    OpenAPIParser parser = new OpenAPIParser();
    String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json"));
    OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("api1");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO);
    AuthenticationContext authenticate = jwtValidator.authenticate(signedJWT, messageContext, openAPI);
    Mockito.verify(apiKeyValidator, Mockito.only())
            .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
                    Mockito.anyString(), Mockito.anyString());
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.when(gatewayTokenCache.get(signedJWT.getSignature().toString())).thenReturn("abc.com");
    String cacheKey = GatewayUtils
            .getAccessTokenCacheKey(signedJWT.getSignature().toString(), "/api1", "1.0", "/pet/findByStatus",
                    "GET");
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis() - 100);
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis());
    Mockito.when(gatewayKeyCache.get(cacheKey)).thenReturn(jwtValidationInfo);
    try {
        authenticate = jwtValidator.authenticate(signedJWT, messageContext, openAPI);

    } catch (APISecurityException e) {
        Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    }
    Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWT);
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(2)).get(signedJWT.getSignature().toString());
    Mockito.verify(invalidTokenCache, Mockito.times(1)).put(signedJWT.getSignature().toString(), "abc.com");
}