io.github.swagger2markup.markup.builder.MarkupLanguage Java Examples

The following examples show how to use io.github.swagger2markup.markup.builder.MarkupLanguage. 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: Swagger2MarkupTest.java    From SpringBootBucket with MIT License 6 votes vote down vote up
/**
     * 将swagger.yaml或swagger.json转换成漂亮的 AsciiDoc
     * 访问:http://localhost:9095/v2/api-docs
     * 将页面结果保存为src/main/resources/swagger.json
     */
    private void convertAsciidoc(String swaggerStr) {
//        Path localSwaggerFile = Paths.get(System.getProperty("swaggerOutputDir"), "swagger.json");
        Path outputFile = Paths.get(System.getProperty("asciiDocOutputDir"));
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();
        Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(swaggerStr)
                .withConfig(config)
                .build();
        converter.toFile(outputFile);
    }
 
Example #2
Source File: DocumentationTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
public void swagger2MarkupConfigFromMap() throws IOException {
    Path localSwaggerFile = Paths.get("/path/to/swagger.yaml");

    // tag::swagger2MarkupConfigFromMap[]
    Map<String, String> configMap = new HashMap<>(); //<1>
    configMap.put(Swagger2MarkupProperties.MARKUP_LANGUAGE, MarkupLanguage.MARKDOWN.toString());
    configMap.put(Swagger2MarkupProperties.OUTPUT_LANGUAGE, Language.DE.toString());
    configMap.put(Swagger2MarkupProperties.PATHS_GROUPED_BY, GroupBy.TAGS.toString());

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(configMap) //<2>
            .build();

    Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(localSwaggerFile)
            .withConfig(config)
            .build();
    // end::swagger2MarkupConfigFromMap[]
}
 
Example #3
Source File: Swagger2MarkupMojoTest.java    From swagger2markup-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConvertIntoMarkdown() throws Exception {
    //given
    Map<String, String> config = new HashMap<>();
    config.put(Swagger2MarkupProperties.MARKUP_LANGUAGE, MarkupLanguage.MARKDOWN.toString());

    Swagger2MarkupMojo mojo = new Swagger2MarkupMojo();
    mojo.swaggerInput = new File(INPUT_DIR, SWAGGER_INPUT_FILE).getAbsoluteFile().getAbsolutePath();
    mojo.outputDir = new File(OUTPUT_DIR).getAbsoluteFile();
    mojo.config = config;

    //when
    mojo.execute();

    //then
    Iterable<String> outputFiles = recursivelyListFileNames(mojo.outputDir);
    assertThat(outputFiles).containsOnly("definitions.md", "overview.md", "paths.md", "security.md");
}
 
Example #4
Source File: TableComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    DataFrame dataFrame = params.dataFrame;
    java.util.List<MarkupTableColumn> columnSpecs = dataFrame.getColumns().map(column -> {
                Integer widthRatio = Integer.valueOf(column.getMetaData().get(WIDTH_RATIO).getOrElse("0"));
                return new MarkupTableColumn(column.getId().getName())
                        .withWidthRatio(widthRatio)
                        .withHeaderColumn(Boolean.parseBoolean(column.getMetaData().get(HEADER_COLUMN).getOrElse("false")))
                        .withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^" + widthRatio + "a");
            }
    ).toJavaList();

    IndexedSeq<IndexedSeq<String>> columnValues = dataFrame.getColumns()
            .map(column -> ((StringColumn) column).getValues());

    java.util.List<java.util.List<String>> cells = Array.range(0, dataFrame.getRowCount())
            .map(rowNumber -> columnValues.map(values -> values.get(rowNumber)).toJavaList()).toJavaList();

    return markupDocBuilder.tableWithColumnSpecs(columnSpecs, cells);
}
 
Example #5
Source File: DefinitionComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    String definitionName = params.definitionName;
    String definitionTitle = determineDefinitionTitle(params);

    Model model = params.model;
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_BEFORE, markupDocBuilder, definitionName, model));
    markupDocBuilder.sectionTitleWithAnchorLevel(params.titleLevel, definitionTitle, definitionName);
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_BEGIN, markupDocBuilder, definitionName, model));
    String description = model.getDescription();
    if (isNotBlank(description)) {
        markupDocBuilder.paragraph(markupDescription(MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name()),
                markupDocBuilder, description));
    }
    inlineDefinitions(markupDocBuilder, typeSection(markupDocBuilder, definitionName, model), definitionName);
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_END, markupDocBuilder, definitionName, model));
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_AFTER, markupDocBuilder, definitionName, model));

    return markupDocBuilder;
}
 
Example #6
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a operation description to the document.
 *
 * @param operation the Swagger Operation
 */
private void buildDescriptionSection(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation) {
    MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder(markupDocBuilder);
    applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_BEGIN, descriptionBuilder, operation));
    String description = operation.getOperation().getDescription();
    if (isNotBlank(description)) {
        descriptionBuilder.paragraph(markupDescription(MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name()), markupDocBuilder, description));
    }
    applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_END, descriptionBuilder, operation));
    String descriptionContent = descriptionBuilder.toString();

    applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_BEFORE, markupDocBuilder, operation));
    if (isNotBlank(descriptionContent)) {
        buildSectionTitle(markupDocBuilder, labels.getLabel(DESCRIPTION));
        markupDocBuilder.text(descriptionContent);
    }
    applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_AFTER, markupDocBuilder, operation));
}
 
Example #7
Source File: SecuritySchemeDefinitionComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    String securitySchemeDefinitionName = params.securitySchemeDefinitionName;
    SecuritySchemeDefinition securitySchemeDefinition = params.securitySchemeDefinition;
    applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_BEFORE, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
    markupDocBuilder.sectionTitleWithAnchorLevel(params.titleLevel, securitySchemeDefinitionName);
    applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_BEGIN, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
    String description = securitySchemeDefinition.getDescription();
    if (isNotBlank(description)) {
        markupDocBuilder.paragraph(markupDescription(MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name()),
                markupDocBuilder, description));
    }
    buildSecurityScheme(markupDocBuilder, securitySchemeDefinition);
    applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_END, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
    applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_AFTER, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
    return markupDocBuilder;
}
 
Example #8
Source File: AbstractMarkupDocBuilderTest.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Test
public void testCopy() {
    MarkupDocBuilder builder = MarkupDocBuilders.documentBuilder(MarkupLanguage.ASCIIDOC, LineSeparator.UNIX).withAnchorPrefix("anchor-");
    MarkupDocBuilder copy = builder.copy(false);

    Assert.assertTrue(copy instanceof AbstractMarkupDocBuilder);
    AbstractMarkupDocBuilder internalCopy = (AbstractMarkupDocBuilder) copy;
    Assert.assertEquals(LineSeparator.UNIX.toString(), internalCopy.newLine);
    Assert.assertEquals("anchor-", internalCopy.anchorPrefix);

    builder = MarkupDocBuilders.documentBuilder(MarkupLanguage.ASCIIDOC, LineSeparator.WINDOWS);
    copy = builder.copy(false);

    Assert.assertTrue(copy instanceof AbstractMarkupDocBuilder);
    internalCopy = (AbstractMarkupDocBuilder) copy;
    Assert.assertEquals(LineSeparator.WINDOWS.toString(), internalCopy.newLine);
    Assert.assertNull(internalCopy.anchorPrefix);

    builder = MarkupDocBuilders.documentBuilder(MarkupLanguage.ASCIIDOC, LineSeparator.UNIX);
    builder.text("This is text");
    copy = builder.copy(true);

    Assert.assertTrue(copy instanceof AbstractMarkupDocBuilder);
    internalCopy = (AbstractMarkupDocBuilder) copy;
    Assert.assertEquals(LineSeparator.UNIX.toString(), internalCopy.newLine);
    Assert.assertNull(internalCopy.anchorPrefix);
    Assert.assertEquals("This is text", internalCopy.documentBuilder.toString());

}
 
Example #9
Source File: AbstractMarkupDocBuilder.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
protected void importMarkupStyle2(Pattern titlePattern, String titleFormat, boolean startFrom0, Reader markupText, MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = Integer.valueOf(titleMatcher.group(1)) - (startFrom0 ? 0 : 1);
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)", levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0", levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String.format(titleFormat, (startFrom0 ? 0 : 1) + titleLevel + levelOffset, title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}
 
Example #10
Source File: AbstractMarkupDocBuilder.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
protected void importMarkupStyle1(Pattern titlePattern, Markup titlePrefix, Reader markupText, MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = titleMatcher.group(1).length() - 1;
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)", levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0", levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String.format("%s %s", StringUtils.repeat(titlePrefix.toString(), 1 + titleLevel + levelOffset), title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}
 
Example #11
Source File: AbstractMarkupDocBuilder.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
protected String convert(String markupText, MarkupLanguage markupLanguage) {
    if (markupLanguage == getMarkupLanguage())
        return markupText;
    else {
        if (markupLanguage == MarkupLanguage.MARKDOWN && getMarkupLanguage() == MarkupLanguage.ASCIIDOC) {
            return AsciiDocConverterExtension.convertMarkdownToAsciiDoc(markupText, asciidocPegdownTimeoutMillis) + newLine;
        } else {
            return markupText;
        }
    }
}
 
Example #12
Source File: MyExtension.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Context context) {
    MarkupDocBuilder markupBuilder = context.getMarkupDocBuilder(); //<2>
    Position position = context.getPosition(); //<3>
    String definitionName = context.getDefinitionName().get();
    Model definitionModel = context.getModel().get();

    if (position.equals(Position.DEFINITION_END)) {
        markupBuilder.sectionTitleLevel1(definitionName) //<4>
                .paragraph(definitionModel.getDescription())
                .importMarkup(new StringReader("*Markup*"), MarkupLanguage.ASCIIDOC);
    }

    // apply is executed per definition
}
 
Example #13
Source File: DocumentationTest.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
public void swagger2MarkupConfigBuilder() {
    Path localSwaggerFile = Paths.get("/path/to/swagger.yaml");

    // tag::swagger2MarkupConfigBuilder[]
    Swagger2MarkupConfig config = (Swagger2MarkupConfig) new Swagger2MarkupConfigBuilder() //<1>
            .withMarkupLanguage(io.github.swagger2markup.MarkupLanguage.MARKDOWN) //<2>
            .withOutputLanguage(Language.DE) //<3>
            .withPathsGroupedBy(GroupBy.TAGS) //<4>
            .build(); //<5>

    Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(localSwaggerFile)
            .withConfig(config) //<6>
            .build();
    // end::swagger2MarkupConfigBuilder[]
}
 
Example #14
Source File: Swagger2MarkupConverter.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
public MarkupDocBuilder createMarkupDocBuilder() {
    MarkupLanguage markupLanguage = null;
    if (config.getMarkupLanguage() != null) {
        markupLanguage = MarkupLanguage.valueOf(config.getMarkupLanguage().name());
    }
    LineSeparator lineSeparator = null;
    if (config.getLineSeparator() != null) {
        lineSeparator = LineSeparator.valueOf(config.getLineSeparator().name());
    }
    return MarkupDocBuilders.documentBuilder(markupLanguage, lineSeparator,
            config.getAsciidocPegdownTimeoutMillis()).withAnchorPrefix(config.getAnchorPrefix());
}
 
Example #15
Source File: AbstractMarkupDocBuilder.java    From markup-document-builder with Apache License 2.0 5 votes vote down vote up
protected void importMarkupStyle2(Pattern titlePattern, String titleFormat, boolean startFrom0, Reader markupText, MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = Integer.valueOf(titleMatcher.group(1)) - (startFrom0 ? 0 : 1);
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)", levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0", levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String.format(titleFormat, (startFrom0 ? 0 : 1) + titleLevel + levelOffset, title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}
 
Example #16
Source File: AbstractMarkupDocBuilder.java    From markup-document-builder with Apache License 2.0 5 votes vote down vote up
protected void importMarkupStyle1(Pattern titlePattern, Markup titlePrefix, Reader markupText, MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = titleMatcher.group(1).length() - 1;
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)", levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0", levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String.format("%s %s", StringUtils.repeat(titlePrefix.toString(), 1 + titleLevel + levelOffset), title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}
 
Example #17
Source File: AbstractMarkupDocBuilder.java    From markup-document-builder with Apache License 2.0 5 votes vote down vote up
protected String convert(String markupText, MarkupLanguage markupLanguage) {
    if (markupLanguage == getMarkupLanguage())
        return markupText;
    else {
        if (markupLanguage == MarkupLanguage.MARKDOWN && getMarkupLanguage() == MarkupLanguage.ASCIIDOC) {
            return AsciiDocConverterExtension.convertMarkdownToAsciiDoc(markupText, asciidocPegdownTimeoutMillis) + newLine;
        } else {
            return markupText;
        }
    }
}
 
Example #18
Source File: AbstractMarkupDocBuilderTest.java    From markup-document-builder with Apache License 2.0 5 votes vote down vote up
@Test
public void testCopy() {
    MarkupDocBuilder builder = MarkupDocBuilders.documentBuilder(MarkupLanguage.ASCIIDOC, LineSeparator.UNIX).withAnchorPrefix("anchor-");
    MarkupDocBuilder copy = builder.copy(false);

    Assert.assertTrue(copy instanceof AbstractMarkupDocBuilder);
    AbstractMarkupDocBuilder internalCopy = (AbstractMarkupDocBuilder) copy;
    Assert.assertEquals(LineSeparator.UNIX.toString(), internalCopy.newLine);
    Assert.assertEquals("anchor-", internalCopy.anchorPrefix);

    builder = MarkupDocBuilders.documentBuilder(MarkupLanguage.ASCIIDOC, LineSeparator.WINDOWS);
    copy = builder.copy(false);

    Assert.assertTrue(copy instanceof AbstractMarkupDocBuilder);
    internalCopy = (AbstractMarkupDocBuilder) copy;
    Assert.assertEquals(LineSeparator.WINDOWS.toString(), internalCopy.newLine);
    Assert.assertNull(internalCopy.anchorPrefix);

    builder = MarkupDocBuilders.documentBuilder(MarkupLanguage.ASCIIDOC, LineSeparator.UNIX);
    builder.text("This is text");
    copy = builder.copy(true);

    Assert.assertTrue(copy instanceof AbstractMarkupDocBuilder);
    internalCopy = (AbstractMarkupDocBuilder) copy;
    Assert.assertEquals(LineSeparator.UNIX.toString(), internalCopy.newLine);
    Assert.assertNull(internalCopy.anchorPrefix);
    Assert.assertEquals("This is text", internalCopy.documentBuilder.toString());

}
 
Example #19
Source File: SwaggerToAsciiDocMarkdownConfluence.java    From springrestdoc with MIT License 5 votes vote down vote up
@Parameters
public static Collection<Object[]> testParams() {
    return Arrays.asList(new Object[][]{
            {"/swagger.yaml", "yaml/asciidoc", MarkupLanguage.ASCIIDOC},
            {"/swagger.yaml", "yaml/markdown", MarkupLanguage.MARKDOWN},
            {"/swagger.yaml", "yaml/confluence", MarkupLanguage.CONFLUENCE_MARKUP},

            {"/swagger.json", "json/asciidoc", MarkupLanguage.ASCIIDOC},
            {"/swagger.json", "json/markdown", MarkupLanguage.MARKDOWN},
            {"/swagger.json", "json/confluence", MarkupLanguage.CONFLUENCE_MARKUP}
    });
}
 
Example #20
Source File: OverviewDocument.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
void buildDescriptionParagraph(MarkupDocBuilder markupDocBuilder, String description) {
    if (isNotBlank(description)) {
        markupDocBuilder.paragraph(markupDescription(MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name()),
                markupDocBuilder, description));
    }
}
 
Example #21
Source File: DemoApplicationTests.java    From spring-boot-starter-samples with Apache License 2.0 4 votes vote down vote up
/**
 * 生成confluence的代码片段:
 * https://blog.csdn.net/qq_35873847/article/details/79191971
 */
//@Test
public void buildConfluence() throws Exception {

	Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()

			.withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)

			.build();

	Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))

			.withConfig(config)

			.build()

			.toFolder(Paths.get("src/docs/confluence/generated"));

}
 
Example #22
Source File: SwaggerToAsciiDocMarkdownConfluence.java    From springrestdoc with MIT License 4 votes vote down vote up
public SwaggerToAsciiDocMarkdownConfluence(String resource, String outputPath, MarkupLanguage markupLanguage) {
    this.resource = resource;
    this.outputPath = outputPath;
    this.markupLanguage = markupLanguage;
}
 
Example #23
Source File: AbstractMarkupDocBuilder.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
@Override
public MarkupDocBuilder importMarkup(Reader markupText, MarkupLanguage markupLanguage) {
    Validate.notNull(markupText, "markupText must not be null");
    Validate.notNull(markupLanguage, "markupLanguage must not be null");
    return importMarkup(markupText, markupLanguage, 0);
}
 
Example #24
Source File: DemoApplicationTests.java    From spring-boot-starter-samples with Apache License 2.0 4 votes vote down vote up
/**
 * 生成confluence的代码片段:
 * https://blog.csdn.net/qq_35873847/article/details/79191971
 */
//@Test
public void buildMarkdown() throws Exception {

	Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()

			.withMarkupLanguage(MarkupLanguage.MARKDOWN)

			.build();

	Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))

			.withConfig(config)

			.build()

			.toFolder(Paths.get("src/docs/confluence/generated"));

}
 
Example #25
Source File: Swagger2MarkupConfigBuilderTest.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
@Test
public void testConfigOfProperties() throws IOException {

    Properties properties = new Properties();
    properties.load(Swagger2MarkupConfigBuilderTest.class.getResourceAsStream("/config/config.properties"));

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(properties).build();

    assertThat(config.getAnchorPrefix()).isEqualTo("anchorPrefix");
    assertThat(config.getDefinitionOrderBy()).isEqualTo(OrderBy.AS_IS);
    assertThat(config.getDefinitionOrdering()).isNull();
    assertThat(config.getDefinitionsDocument()).isEqualTo("definitionsTest");
    assertThat(config.isGeneratedExamplesEnabled()).isTrue();
    assertThat(config.isHostnameEnabled()).isEqualTo(false);
    assertThat(config.isInlineSchemaEnabled()).isEqualTo(false);
    assertThat(config.getInterDocumentCrossReferencesPrefix()).isEqualTo("xrefPrefix");
    assertThat(config.getMarkupLanguage().name()).isEqualTo(MarkupLanguage.MARKDOWN.name());
    assertThat(config.getOperationOrderBy()).isEqualTo(OrderBy.NATURAL);
    assertThat(config.getOperationOrdering()).isEqualTo(Swagger2MarkupConfigBuilder.OPERATION_PATH_NATURAL_ORDERING.compound(Swagger2MarkupConfigBuilder.OPERATION_METHOD_NATURAL_ORDERING));
    assertThat(config.getLanguage()).isEqualTo(Language.RU);
    assertThat(config.getOverviewDocument()).isEqualTo("overviewTest");
    assertThat(config.getParameterOrderBy()).isEqualTo(OrderBy.AS_IS);
    assertThat(config.getParameterOrdering()).isNull();
    assertThat(config.getPathsDocument()).isEqualTo("pathsTest");
    assertThat(config.getPathsGroupedBy()).isEqualTo(GroupBy.TAGS);
    assertThat(config.getPropertyOrderBy()).isEqualTo(OrderBy.AS_IS);
    assertThat(config.getPropertyOrdering()).isNull();
    assertThat(config.getResponseOrderBy()).isEqualTo(OrderBy.AS_IS);
    assertThat(config.getResponseOrdering()).isNull();
    assertThat(config.getSecurityDocument()).isEqualTo("securityTest");
    assertThat(config.getSeparatedDefinitionsFolder()).isEqualTo("definitionsTest");
    assertThat(config.getSeparatedOperationsFolder()).isEqualTo("operationsTest");
    assertThat(config.isListDelimiterEnabled()).isEqualTo(true);
    assertThat(config.getListDelimiter()).isEqualTo(Character.valueOf('|'));
    assertThat(config.getTagOrderBy()).isEqualTo(OrderBy.AS_IS);
    assertThat(config.getTagOrdering()).isNull();
    assertThat(config.isFlatBodyEnabled()).isTrue();
    assertThat(config.isPathSecuritySectionEnabled()).isFalse();
    assertThat(config.isInterDocumentCrossReferencesEnabled()).isTrue();
    assertThat(config.isSeparatedDefinitionsEnabled()).isTrue();
    assertThat(config.isSeparatedOperationsEnabled()).isTrue();
    assertThat(config.getExtensionsProperties().getKeys()).hasSize(5)
    .containsOnly("uniqueId1.customProperty1",
            "uniqueId1.customProperty2",
            "uniqueId2.customProperty1",
            "uniqueId2.customProperty2",
            "uniqueId2.customPropertyList1"
            );
    assertThat(config.getExtensionsProperties().getPathList("uniqueId2.customPropertyList1")).hasSize(2)
    .containsOnly(Paths.get("123"), Paths.get("456"));
}
 
Example #26
Source File: Swagger2MarkupConfigBuilderTest.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
@Test
public void testConfigOfDefaults() {
    Map<String, String> configMap = new HashMap<>();
    configMap.put(Swagger2MarkupProperties.MARKUP_LANGUAGE, MarkupLanguage.MARKDOWN.toString());
    configMap.put("swagger2markup.extensions.uniqueId1.customProperty1", "123");
    configMap.put("swagger2markup.extensions.uniqueId1.customProperty2", "123");
    configMap.put("swagger2markup.extensions.uniqueId2.customPropertyList1", "123,456");
    configMap.put("swagger2markup.uniqueId1.customProperty1", "123");
    configMap.put("swagger2markup.uniqueId1.customProperty2", "123");

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(configMap)
            .build();

    assertThat(config.getAnchorPrefix()).isNull();
    assertThat(config.getDefinitionOrderBy()).isEqualTo(OrderBy.NATURAL);
    assertThat(config.getDefinitionOrdering()).isEqualTo(Ordering.natural());
    assertThat(config.getDefinitionsDocument()).isEqualTo("definitions");
    assertThat(config.isGeneratedExamplesEnabled()).isFalse();
    assertThat(config.isInlineSchemaEnabled()).isEqualTo(true);
    assertThat(config.getInterDocumentCrossReferencesPrefix()).isNull();
    assertThat(config.getMarkupLanguage().name()).isEqualTo(MarkupLanguage.MARKDOWN.name());
    assertThat(config.getOperationOrderBy()).isEqualTo(OrderBy.NATURAL);
    assertThat(config.getOperationOrdering()).isNotNull();
    assertThat(config.getLanguage()).isEqualTo(Language.EN);
    assertThat(config.getOverviewDocument()).isEqualTo("overview");
    assertThat(config.getParameterOrderBy()).isEqualTo(OrderBy.NATURAL);
    assertThat(config.getParameterOrdering()).isEqualTo(Swagger2MarkupConfigBuilder.PARAMETER_IN_NATURAL_ORDERING.compound(Swagger2MarkupConfigBuilder.PARAMETER_NAME_NATURAL_ORDERING));
    assertThat(config.getPathsDocument()).isEqualTo("paths");
    assertThat(config.getPathsGroupedBy()).isEqualTo(GroupBy.AS_IS);
    assertThat(config.getPropertyOrderBy()).isEqualTo(OrderBy.NATURAL);
    assertThat(config.getPropertyOrdering()).isEqualTo(Ordering.natural());
    assertThat(config.getResponseOrderBy()).isEqualTo(OrderBy.NATURAL);
    assertThat(config.getResponseOrdering()).isEqualTo(Ordering.natural());
    assertThat(config.getSecurityDocument()).isEqualTo("security");
    assertThat(config.getSeparatedDefinitionsFolder()).isEqualTo("definitions");
    assertThat(config.getSeparatedOperationsFolder()).isEqualTo("operations");
    assertThat(config.getTagOrderBy()).isEqualTo(OrderBy.NATURAL);
    assertThat(config.getTagOrdering()).isEqualTo(Ordering.natural());
    assertThat(config.isFlatBodyEnabled()).isFalse();
    assertThat(config.isPathSecuritySectionEnabled()).isTrue();
    assertThat(config.isInterDocumentCrossReferencesEnabled()).isFalse();
    assertThat(config.isSeparatedDefinitionsEnabled()).isFalse();
    assertThat(config.isSeparatedOperationsEnabled()).isFalse();
    assertThat(config.getExtensionsProperties().getKeys()).hasSize(3)
    .containsOnly("uniqueId1.customProperty1",
            "uniqueId1.customProperty2",
            "uniqueId2.customPropertyList1"
            );
    assertThat(config.getExtensionsProperties().getString("uniqueId1.customProperty1").get()).isEqualTo("123");
    assertThat(config.getExtensionsProperties().getPathList("uniqueId2.customPropertyList1")).hasSize(1)
    .containsOnly(Paths.get("123,456"));
}
 
Example #27
Source File: DocumentController.java    From sc-generator with Apache License 2.0 4 votes vote down vote up
public InputStream generatorDoc(Swagger swagger, String extension, String title, String language) throws FileNotFoundException {

        String filePath = folder + "/" + new Date().getTime() + "/";

        Swagger2MarkupConfigBuilder builder = new Swagger2MarkupConfigBuilder();
        if (extension.equalsIgnoreCase("md")) {
            builder.withMarkupLanguage(MarkupLanguage.MARKDOWN);
        } else {
            builder.withMarkupLanguage(MarkupLanguage.ASCIIDOC);
        }


        Swagger2MarkupConfig config = builder.withBasePathPrefix()
                .withInterDocumentCrossReferences()
                .withPathsGroupedBy(GroupBy.TAGS)
                .withTagOrdering(OrderBy.AS_IS)
                .withoutPathSecuritySection()
                .withOutputLanguage(Language.valueOf(language.toUpperCase()))
                .withGeneratedExamples()
                .withFlatBody()
                .build();


        Swagger2MarkupConverter.from(swagger)
                .withConfig(config)
                .build()
                .toFile(Paths.get(filePath + "index"));

        if (extension.equalsIgnoreCase("html") || extension.equalsIgnoreCase("pdf") || extension.equalsIgnoreCase("epub3")) {
            Attributes toc = new Attributes("toc");
            toc.setTitle(title);
            //auto, left, right, macro, preamble
            toc.setTableOfContents(Placement.LEFT);
            //html5, docbook5, docbook45
            toc.setDocType("docbook5");
            toc.setSectNumLevels(4);
            OptionsBuilder optionsBuilder = OptionsBuilder.options()
                    .headerFooter(true)
                    .inPlace(true)
                    .toFile(true)
                    .attributes(toc)
                    .safe(SafeMode.SAFE);


            if (extension.equalsIgnoreCase("pdf")) {
                optionsBuilder.backend("pdf");
                asciidoctor.convertDirectory(new AsciiDocDirectoryWalker(filePath), optionsBuilder);
                return new FileInputStream(filePath + "index.pdf");
            } else if (extension.equalsIgnoreCase("epub3")) {
                optionsBuilder.backend("epub3");
                asciidoctor.convertDirectory(new AsciiDocDirectoryWalker(filePath), optionsBuilder);
                return new FileInputStream(filePath + "index.epub3");
            } else {
                optionsBuilder.backend("html5");
                asciidoctor.convertDirectory(new AsciiDocDirectoryWalker(filePath), optionsBuilder);
                return new FileInputStream(filePath + "index.html");
            }
        } else if (extension.equalsIgnoreCase("md")) {
            return new FileInputStream(filePath + "index.md");
        } else if (extension.equalsIgnoreCase("adoc")) {
            return new FileInputStream(filePath + "index.adoc");
        } else {
            return new FileInputStream(filePath);
        }
    }
 
Example #28
Source File: AbstractMarkupDocBuilder.java    From markup-document-builder with Apache License 2.0 4 votes vote down vote up
@Override
public MarkupDocBuilder importMarkup(Reader markupText, MarkupLanguage markupLanguage) {
    Validate.notNull(markupText, "markupText must not be null");
    Validate.notNull(markupLanguage, "markupLanguage must not be null");
    return importMarkup(markupText, markupLanguage, 0);
}
 
Example #29
Source File: BodyParameterComponent.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    SwaggerPathOperation operation = params.operation;
    List<ObjectType> inlineDefinitions = params.inlineDefinitions;
    if (config.isFlatBodyEnabled()) {
        List<Parameter> parameters = operation.getOperation().getParameters();
        if (CollectionUtils.isNotEmpty(parameters)) {
            for (Parameter parameter : parameters) {
                if (StringUtils.equals(parameter.getIn(), "body")) {
                    ParameterAdapter parameterAdapter = new ParameterAdapter(context,
                            operation, parameter, definitionDocumentResolver);

                    Type type = parameterAdapter.getType();
                    inlineDefinitions.addAll(parameterAdapter.getInlineDefinitions());

                    buildSectionTitle(markupDocBuilder, labels.getLabel(BODY_PARAMETER));
                    String description = parameter.getDescription();
                    if (isNotBlank(description)) {
                        MarkupLanguage markupLanguage = MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name());
                        markupDocBuilder.paragraph(markupDescription(markupLanguage, markupDocBuilder, description));
                    }

                    MarkupDocBuilder typeInfos = copyMarkupDocBuilder(markupDocBuilder);
                    typeInfos.italicText(labels.getLabel(NAME_COLUMN)).textLine(COLON + parameter.getName());
                    typeInfos.italicText(labels.getLabel(FLAGS_COLUMN)).textLine(COLON + (BooleanUtils.isTrue(parameter.getRequired()) ? labels.getLabel(FLAGS_REQUIRED).toLowerCase() : labels.getLabel(FLAGS_OPTIONAL).toLowerCase()));

                    if (!(type instanceof ObjectType)) {
                        typeInfos.italicText(labels.getLabel(TYPE_COLUMN)).textLine(COLON + type.displaySchema(markupDocBuilder));
                    }

                    markupDocBuilder.paragraph(typeInfos.toString(), true);

                    if (type instanceof ObjectType) {
                        List<ObjectType> localDefinitions = new ArrayList<>();

                        propertiesTableComponent.apply(markupDocBuilder, PropertiesTableComponent.parameters(
                                ((ObjectType) type).getProperties(),
                                operation.getId(),
                                localDefinitions
                        ));

                        inlineDefinitions.addAll(localDefinitions);
                    }
                }
            }
        }
    }
    return markupDocBuilder;
}
 
Example #30
Source File: ResponseComponent.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    SwaggerPathOperation operation = params.operation;
    Map<String, Response> responses = operation.getOperation().getResponses();

    MarkupDocBuilder responsesBuilder = copyMarkupDocBuilder(markupDocBuilder);
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_BEGIN, responsesBuilder, operation));
    if (MapUtils.isNotEmpty(responses)) {
        StringColumn.Builder httpCodeColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(HTTP_CODE_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "2");
        StringColumn.Builder descriptionColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "14")
                .putMetaData(TableComponent.HEADER_COLUMN, "true");
        StringColumn.Builder schemaColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(SCHEMA_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "4")
                .putMetaData(TableComponent.HEADER_COLUMN, "true");

        Map<String, Response> sortedResponses = toSortedMap(responses, config.getResponseOrdering());
        sortedResponses.forEach((String responseName, Response response) -> {
            String schemaContent = labels.getLabel(NO_CONTENT);
            if (response.getResponseSchema() != null) {
                Model model = response.getResponseSchema();
                Type type = null;

                if (model != null) {
                    type = ModelUtils.getType(model, definitions, definitionDocumentResolver);
                } else {
                    type = new BasicType("string", responseName);
                }

                if (config.isInlineSchemaEnabled()) {
                    type = createInlineType(type, labels.getLabel(RESPONSE) + " " + responseName, operation.getId() + " " + labels.getLabel(RESPONSE) + " " + responseName, params.inlineDefinitions);
                }

                schemaContent = type.displaySchema(markupDocBuilder);
            }

            MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder(markupDocBuilder);

            descriptionBuilder.text(markupDescription(MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name()),
                    markupDocBuilder, response.getDescription()));

            Map<String, Property> headers = response.getHeaders();
            if (MapUtils.isNotEmpty(headers)) {
                descriptionBuilder.newLine(true).boldText(labels.getLabel(HEADERS_COLUMN)).text(COLON);
                for (Map.Entry<String, Property> header : headers.entrySet()) {
                    descriptionBuilder.newLine(true);
                    Property headerProperty = header.getValue();
                    PropertyAdapter headerPropertyAdapter = new PropertyAdapter(headerProperty);
                    Type propertyType = headerPropertyAdapter.getType(definitionDocumentResolver);
                    String headerDescription = markupDescription(MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name()),
                            markupDocBuilder, headerProperty.getDescription());
                    Optional<Object> optionalDefaultValue = headerPropertyAdapter.getDefaultValue();

                    descriptionBuilder
                            .literalText(header.getKey())
                            .text(String.format(" (%s)", propertyType.displaySchema(markupDocBuilder)));

                    if (isNotBlank(headerDescription) || optionalDefaultValue.isPresent()) {
                        descriptionBuilder.text(COLON);

                        if (isNotBlank(headerDescription) && !headerDescription.endsWith("."))
                            headerDescription += ".";

                        descriptionBuilder.text(headerDescription);

                        optionalDefaultValue.ifPresent(o -> descriptionBuilder.text(" ")
                                .boldText(labels.getLabel(DEFAULT_COLUMN))
                                .text(COLON).literalText(Json.pretty(o)));
                    }
                }
            }

            httpCodeColumnBuilder.add(boldText(markupDocBuilder, responseName));
            descriptionColumnBuilder.add(descriptionBuilder.toString());
            schemaColumnBuilder.add(schemaContent);
        });

        responsesBuilder = tableComponent.apply(responsesBuilder, TableComponent.parameters(httpCodeColumnBuilder.build(),
                descriptionColumnBuilder.build(),
                schemaColumnBuilder.build()));
    }
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_END, responsesBuilder, operation));
    String responsesContent = responsesBuilder.toString();

    applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_BEFORE, markupDocBuilder, operation));
    if (isNotBlank(responsesContent)) {
        markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(RESPONSES));
        markupDocBuilder.text(responsesContent);
    }
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_AFTER, markupDocBuilder, operation));
    return markupDocBuilder;
}