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

The following examples show how to use io.github.swagger2markup.markup.builder.MarkupDocBuilder. 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: TableComponentTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Test
public void testTable() throws URISyntaxException {
    StringColumn.Builder typeColumnBuilder = StringColumn.builder(StringColumnId.of("type"));
    typeColumnBuilder.add("type1").add("type2").add("type3");

    StringColumn.Builder nameColumnBuilder = StringColumn.builder(StringColumnId.of("name"));
    nameColumnBuilder.add("name1").add("").add("name3");

    StringColumn.Builder descriptionColumnBuilder = StringColumn.builder(StringColumnId.of("description"));
    descriptionColumnBuilder.add("").add("").add("");

    Swagger2MarkupConverter.SwaggerContext context = createContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    markupDocBuilder = new TableComponent(context).apply(markupDocBuilder,
            TableComponent.parameters(
                    typeColumnBuilder.build(),
                    nameColumnBuilder.build(),
                    descriptionColumnBuilder.build()));
    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));
}
 
Example #2
Source File: LicenseInfoComponentTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Test
public void testLicenseInfoComponent() throws URISyntaxException {

    Info info = new Info()
            .license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0"))
            .termsOfService("Bla bla bla");

    Swagger2MarkupConverter.SwaggerContext context = createContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    markupDocBuilder = new LicenseInfoComponent(context).apply(markupDocBuilder, LicenseInfoComponent.parameters(info, OverviewDocument.SECTION_TITLE_LEVEL));
    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));

}
 
Example #3
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 #4
Source File: ExamplesUtil.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a map of examples from a map of properties. If defined examples are found, those are used. Otherwise,
 * examples are generated from the type.
 *
 * @param properties       the map of properties
 * @param definitions      the map of definitions
 * @param markupDocBuilder the markup builder
 * @param refStack         map to detect cyclic references
 * @return a Map of examples
 */
private static Map<String, Object> exampleMapForProperties(Map<String, Property> properties, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) {
    Map<String, Object> exampleMap = new LinkedHashMap<>();
    if (properties != null) {
        for (Map.Entry<String, Property> property : properties.entrySet()) {
            Object exampleObject = property.getValue().getExample();
            if (exampleObject == null) {
                if (property.getValue() instanceof RefProperty) {
                    exampleObject = generateExampleForRefModel(true, ((RefProperty) property.getValue()).getSimpleRef(), definitions, definitionDocumentResolver, markupDocBuilder, refStack);
                } else if (property.getValue() instanceof ArrayProperty) {
                    exampleObject = generateExampleForArrayProperty((ArrayProperty) property.getValue(), definitions, definitionDocumentResolver, markupDocBuilder, refStack);
                } else if (property.getValue() instanceof MapProperty) {
                    exampleObject = generateExampleForMapProperty((MapProperty) property.getValue(), markupDocBuilder);
                }
                if (exampleObject == null) {
                    Property valueProperty = property.getValue();
                    exampleObject = PropertyAdapter.generateExample(valueProperty, markupDocBuilder);
                }
            }
            exampleMap.put(property.getKey(), exampleObject);
        }
    }
    return exampleMap;
}
 
Example #5
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
/**
 * Builds inline schema definitions
 *
 * @param markupDocBuilder the docbuilder do use for output
 * @param definitions      all inline definitions to display
 * @param uniquePrefix     unique prefix to prepend to inline object names to enforce unicity
 */
private void inlineDefinitions(MarkupDocBuilder markupDocBuilder, List<ObjectType> definitions, String uniquePrefix) {
    if (CollectionUtils.isNotEmpty(definitions)) {
        for (ObjectType definition : definitions) {
            addInlineDefinitionTitle(markupDocBuilder, definition.getName(), definition.getUniqueName());

            List<ObjectType> localDefinitions = new ArrayList<>();
            propertiesTableComponent.apply(markupDocBuilder, PropertiesTableComponent.parameters(
                    definition.getProperties(),
                    uniquePrefix,
                    localDefinitions
            ));
            for (ObjectType localDefinition : localDefinitions)
                inlineDefinitions(markupDocBuilder, Collections.singletonList(localDefinition), localDefinition.getUniqueName());
        }
    }

}
 
Example #6
Source File: UriSchemeComponentTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Test
public void testUriSchemeComponent() throws URISyntaxException {

    Swagger swagger = new Swagger().host("http://localhost").basePath("/v2");
    swagger.addScheme(Scheme.HTTP);
    swagger.addScheme(Scheme.HTTPS);

    Swagger2MarkupConverter.SwaggerContext context = createContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    markupDocBuilder = new UriSchemeComponent(context).apply(markupDocBuilder, UriSchemeComponent.parameters(swagger, OverviewDocument.SECTION_TITLE_LEVEL));
    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));

}
 
Example #7
Source File: SecuritySchemeDefinitionComponentTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecuritySchemeDefinitionComponentWithOAuth() throws URISyntaxException {
    //Given
    Path file = Paths.get(SecuritySchemeDefinitionComponentTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(file).build();
    Swagger swagger = converter.getContext().getSchema();

    SecuritySchemeDefinition securitySchemeDefinition = swagger.getSecurityDefinitions().get("petstore_auth");

    Swagger2MarkupConverter.SwaggerContext context = converter.getContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    markupDocBuilder = new SecuritySchemeDefinitionComponent(context).apply(
            markupDocBuilder, SecuritySchemeDefinitionComponent.parameters("petstore_auth",
                    securitySchemeDefinition,
                    OverviewDocument.SECTION_TITLE_LEVEL));
    markupDocBuilder.writeToFileWithoutExtension(oauthOutputDirectory, StandardCharsets.UTF_8);

    Path expectedFile = getExpectedFile(O_AUTH_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, oauthOutputDirectory, getReportName(O_AUTH_NAME));

}
 
Example #8
Source File: PathOperationComponentTest.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithQueryParamExample() throws URISyntaxException {
    String COMPONENT_NAME = "path_operation_with_query_param_example";
    Path outputDirectory = getOutputFile(COMPONENT_NAME);
    FileUtils.deleteQuietly(outputDirectory.toFile());

    Map<String, String> configMap = new HashMap<>();
    configMap.put("swagger2markup.generatedExamplesEnabled", "true");  // enable example

    //Given
    Path file = Paths.get(PathOperationComponentTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(configMap).build();
    Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(file).withConfig(config) .build();
    Swagger swagger = converter.getContext().getSchema();

    io.swagger.models.Path path = swagger.getPaths().get("/pets/findByTags");
    List<SwaggerPathOperation> pathOperations = PathUtils.toPathOperationsList("/pets/findByTags", path);

    Swagger2MarkupConverter.SwaggerContext context = converter.getContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    //When
    markupDocBuilder = new PathOperationComponent(context,
            new DefinitionDocumentResolverFromOperation(context),
            new SecurityDocumentResolver(context)).
            apply(markupDocBuilder, PathOperationComponent.parameters(pathOperations.get(0)));

    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    //Then
    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));
}
 
Example #9
Source File: ArrayType.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Override
public String displaySchema(MarkupDocBuilder docBuilder) {
    String ofTypeDisplay = ofType.displaySchema(docBuilder);
    if (isNotBlank(this.collectionFormat))
        return String.format("< %s > array(%s)", ofTypeDisplay, collectionFormat);
    else
        return String.format("< %s > array", ofTypeDisplay);
}
 
Example #10
Source File: ParameterTableComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
private String getParameterNameColumnContent(MarkupDocBuilder markupDocBuilder, ParameterAdapter parameter) {
    MarkupDocBuilder parameterNameContent = copyMarkupDocBuilder(markupDocBuilder);

    parameterNameContent.boldTextLine(parameter.getName(), true);
    if (parameter.getRequired())
        parameterNameContent.italicText(labels.getLabel(FLAGS_REQUIRED).toLowerCase());
    else
        parameterNameContent.italicText(labels.getLabel(FLAGS_OPTIONAL).toLowerCase());
    return parameterNameContent.toString();
}
 
Example #11
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a operation title to the document.
 *
 * @param title  the operation title
 * @param anchor optional anchor (null => auto-generate from title)
 */
private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
    if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
        markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor);
    } else {
        markupDocBuilder.sectionTitleWithAnchorLevel3(title, anchor);
    }
}
 
Example #12
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
private List<ObjectType> buildResponsesSection(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation) {
    List<ObjectType> inlineDefinitions = new ArrayList<>();

    responseComponent.apply(markupDocBuilder, ResponseComponent.parameters(
            operation,
            getSectionTitleLevel(),
            inlineDefinitions
    ));

    return inlineDefinitions;
}
 
Example #13
Source File: BodyParameterComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
private void buildSectionTitle(MarkupDocBuilder markupDocBuilder, String title) {
    if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
        markupDocBuilder.sectionTitleLevel3(title);
    } else {
        markupDocBuilder.sectionTitleLevel4(title);
    }
}
 
Example #14
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
private void buildConsumesSection(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation) {
    List<String> consumes = operation.getOperation().getConsumes();
    if (CollectionUtils.isNotEmpty(consumes)) {
        consumesComponent.apply(markupDocBuilder, ConsumesComponent.parameters(consumes,
                getSectionTitleLevel()));
    }

}
 
Example #15
Source File: ExamplesUtil.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Generates an example object from a simple reference
 *
 * @param generateMissingExamples specifies the missing examples should be generated
 * @param simpleRef               the simple reference string
 * @param definitions             the map of definitions
 * @param markupDocBuilder        the markup builder
 * @param refStack                map to detect cyclic references
 * @return returns an Object or Map of examples
 */
private static Object generateExampleForRefModel(boolean generateMissingExamples, String simpleRef, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) {
    Model model = definitions.get(simpleRef);
    Object example = null;
    if (model != null) {
        example = model.getExample();
        if (example == null && generateMissingExamples) {
            if (!refStack.containsKey(simpleRef)) {
                refStack.put(simpleRef, 1);
            } else {
                refStack.put(simpleRef, refStack.get(simpleRef) + 1);
            }
            if (refStack.get(simpleRef) <= MAX_RECURSION_TO_DISPLAY) {
                if (model instanceof ComposedModel) {
                    //FIXME: getProperties() may throw NullPointerException
                    example = exampleMapForProperties(((ObjectType) ModelUtils.getType(model, definitions, definitionDocumentResolver)).getProperties(), definitions, definitionDocumentResolver, markupDocBuilder, new HashMap<>());
                } else {
                    example = exampleMapForProperties(model.getProperties(), definitions, definitionDocumentResolver, markupDocBuilder, refStack);
                }
            } else {
                return "...";
            }
            refStack.put(simpleRef, refStack.get(simpleRef) - 1);
        }
    }
    return example;
}
 
Example #16
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a example title to the document.
 *
 * @param title the section title
 */
private void buildExampleTitle(MarkupDocBuilder markupDocBuilder, String title) {
    if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
        markupDocBuilder.sectionTitleLevel4(title);
    } else {
        markupDocBuilder.sectionTitleLevel5(title);
    }
}
 
Example #17
Source File: ProducesComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(SwaggerLabels.PRODUCES));
    markupDocBuilder.unorderedList(params.produces.stream()
            .map(value -> literalText(markupDocBuilder, value)).collect(Collectors.toList()));
    return markupDocBuilder;
}
 
Example #18
Source File: SecurityDocument.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the security MarkupDocument.
 *
 * @return the security MarkupDocument
 */
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, SecurityDocument.Parameters params) {
    Map<String, SecuritySchemeDefinition> definitions = params.securitySchemeDefinitions;
    if (MapUtils.isNotEmpty(definitions)) {
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
        buildSecurityTitle(markupDocBuilder, labels.getLabel(SECURITY));
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
        buildSecuritySchemeDefinitionsSection(markupDocBuilder, definitions);
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
    }
    return markupDocBuilder;
}
 
Example #19
Source File: PathsDocument.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a operation title to the document.
 *
 * @param title  the operation title
 * @param anchor optional anchor (null => auto-generate from title)
 */
private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
    if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
        markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor);
    } else {
        markupDocBuilder.sectionTitleWithAnchorLevel3(title, anchor);
    }
}
 
Example #20
Source File: ExamplesUtil.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
private static Object generateExampleForMapProperty(MapProperty property, MarkupDocBuilder markupDocBuilder) {
    if (property.getExample() != null) {
        return property.getExample();
    }
    Map<String, Object> exampleMap = new LinkedHashMap<>();
    Property valueProperty = property.getAdditionalProperties();
    if (valueProperty.getExample() != null) {
        return valueProperty.getExample();
    }
    exampleMap.put("string", PropertyAdapter.generateExample(valueProperty, markupDocBuilder));
    return exampleMap;
}
 
Example #21
Source File: PathOperationComponentTest.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Test
public void testPathOperationComponent() throws URISyntaxException {
    String COMPONENT_NAME = "path_operation";
    Path outputDirectory = getOutputFile(COMPONENT_NAME);
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //Given
    Path file = Paths.get(PathOperationComponentTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(file).build();
    Swagger swagger = converter.getContext().getSchema();

    io.swagger.models.Path path = swagger.getPaths().get("/pets");
    List<SwaggerPathOperation> pathOperations = PathUtils.toPathOperationsList("/pets", path);

    Swagger2MarkupConverter.SwaggerContext context = converter.getContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    //When
    markupDocBuilder = new PathOperationComponent(context,
            new DefinitionDocumentResolverFromOperation(context),
            new SecurityDocumentResolver(context)).
            apply(markupDocBuilder, PathOperationComponent.parameters(pathOperations.get(0)));

    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    //Then
    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));
}
 
Example #22
Source File: PathsDocument.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the paths section. Groups the paths either as-is, by tags or using regex.
 *
 * @param paths the Swagger paths
 */
private void buildsPathsSection(MarkupDocBuilder markupDocBuilder, Map<String, Path> paths) {
    List<SwaggerPathOperation> pathOperations = PathUtils.toPathOperationsList(paths, getHostname(), getBasePath(), config.getOperationOrdering());
    if (CollectionUtils.isNotEmpty(pathOperations)) {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            pathOperations.forEach(operation -> buildOperation(markupDocBuilder, operation, config));
        } else if (config.getPathsGroupedBy() == GroupBy.TAGS) {
            Validate.notEmpty(context.getSchema().getTags(), "Tags must not be empty, when operations are grouped by tags");
            // Group operations by tag
            Multimap<String, SwaggerPathOperation> operationsGroupedByTag = TagUtils.groupOperationsByTag(pathOperations, config.getOperationOrdering());

            Map<String, Tag> tagsMap = TagUtils.toSortedMap(context.getSchema().getTags(), config.getTagOrdering());

            tagsMap.forEach((String tagName, Tag tag) -> {
                markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(tagName), tagName + "_resource");
                String description = tag.getDescription();
                if (StringUtils.isNotBlank(description)) {
                    markupDocBuilder.paragraph(description);
                }
                operationsGroupedByTag.get(tagName).forEach(operation -> buildOperation(markupDocBuilder, operation, config));

            });
        } else if (config.getPathsGroupedBy() == GroupBy.REGEX) {
            Validate.notNull(config.getHeaderPattern(), "Header regex pattern must not be empty when operations are grouped using regex");

            Pattern headerPattern = config.getHeaderPattern();
            Multimap<String, SwaggerPathOperation> operationsGroupedByRegex = RegexUtils.groupOperationsByRegex(pathOperations, headerPattern);
            Set<String> keys = operationsGroupedByRegex.keySet();
            String[] sortedHeaders = RegexUtils.toSortedArray(keys);

            for (String header : sortedHeaders) {
                markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(header), header + "_resource");
                operationsGroupedByRegex.get(header).forEach(operation -> buildOperation(markupDocBuilder, operation, config));
            }
        }
    }
}
 
Example #23
Source File: DefinitionComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds inline schema definitions
 *
 * @param markupDocBuilder the docbuilder do use for output
 * @param definitions      all inline definitions to display
 * @param uniquePrefix     unique prefix to prepend to inline object names to enforce unicity
 */
private void inlineDefinitions(MarkupDocBuilder markupDocBuilder, List<ObjectType> definitions, String uniquePrefix) {
    if (CollectionUtils.isNotEmpty(definitions)) {
        for (ObjectType definition : definitions) {
            addInlineDefinitionTitle(definition.getName(), definition.getUniqueName(), markupDocBuilder);

            List<ObjectType> localDefinitions = new ArrayList<>();
            propertiesTableComponent.apply(markupDocBuilder, new PropertiesTableComponent.Parameters(definition.getProperties(), uniquePrefix, localDefinitions));
            for (ObjectType localDefinition : localDefinitions)
                inlineDefinitions(markupDocBuilder, Collections.singletonList(localDefinition), localDefinition.getUniqueName());
        }
    }
}
 
Example #24
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the example section of a Swagger Operation.
 *
 * @param operation the Swagger Operation
 */
private void buildExamplesSection(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation, List<PageBreakLocations> locations) {
    PathExample pathGenerator;
    switch (config.getRequestExamplesFormat().toLowerCase()) {
        case "curl":
            pathGenerator = new CurlPathExample(context, definitionDocumentResolver, operation);
            break;
        case "invoke-webrequest":
            pathGenerator = new InvokeWebRequestPathExample(context, definitionDocumentResolver, operation);
            break;
        case "basic":
            pathGenerator = new BasicPathExample(context, definitionDocumentResolver, operation);
            break;
        default:
            logger.warn(
                    "Unknown format name '{}' for requestExamplesFormat config parameter, falling back to 'basic'",
                    config.getRequestExamplesFormat());
            pathGenerator = new BasicPathExample(context, definitionDocumentResolver, operation);
    }

    Map<String, Object> generatedRequestExampleMap = ExamplesUtil.generateRequestExampleMap(pathGenerator, definitions, markupDocBuilder);
    Map<String, Object> generatedResponseExampleMap = ExamplesUtil.generateResponseExampleMap(config.isGeneratedExamplesEnabled(), operation, definitions, definitionDocumentResolver, markupDocBuilder);

    boolean beforeExampleRequestBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_REQUEST);
    boolean afterExampleRequestBreak = locations.contains(AFTER_OPERATION_EXAMPLE_REQUEST);
    boolean beforeExampleResponseBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_RESPONSE);
    boolean afterExampleResponseBreak = locations.contains(AFTER_OPERATION_EXAMPLE_RESPONSE);

    exampleMap(markupDocBuilder, generatedRequestExampleMap, labels.getLabel(EXAMPLE_REQUEST), labels.getLabel(REQUEST), beforeExampleRequestBreak, afterExampleRequestBreak);
    exampleMap(markupDocBuilder, generatedResponseExampleMap, labels.getLabel(EXAMPLE_RESPONSE), labels.getLabel(RESPONSE), beforeExampleResponseBreak, afterExampleResponseBreak);
}
 
Example #25
Source File: PathOperationComponentTest.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlineSchema() throws URISyntaxException {
    String COMPONENT_NAME = "path_operation_inline_schema";
    Path outputDirectory = getOutputFile(COMPONENT_NAME);
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //Given
    Path file = Paths.get(PathOperationComponentTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
    Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(file).build();
    Swagger swagger = converter.getContext().getSchema();

    io.swagger.models.Path path = swagger.getPaths().get("/LaunchCommand");
    List<SwaggerPathOperation> pathOperations = PathUtils.toPathOperationsList("/LaunchCommand", path);

    Swagger2MarkupConverter.SwaggerContext context = converter.getContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    //When
    markupDocBuilder = new PathOperationComponent(context,
            new DefinitionDocumentResolverFromOperation(context),
            new SecurityDocumentResolver(context)).
            apply(markupDocBuilder, PathOperationComponent.parameters(pathOperations.get(0)));

    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    //Then
    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));

}
 
Example #26
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 #27
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the parameters section
 *
 * @param operation the Swagger Operation
 */
private List<ObjectType> buildParametersSection(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation) {

    List<ObjectType> inlineDefinitions = new ArrayList<>();

    parameterTableComponent.apply(markupDocBuilder, ParameterTableComponent.parameters(
            operation,
            inlineDefinitions,
            getSectionTitleLevel()
    ));

    return inlineDefinitions;
}
 
Example #28
Source File: PathsDocument.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the paths MarkupDocument.
 *
 * @return the paths MarkupDocument
 */
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, PathsDocument.Parameters params) {
    Map<String, Path> paths = params.paths;
    if (MapUtils.isNotEmpty(paths)) {
        applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
        buildPathsTitle(markupDocBuilder);
        applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
        buildsPathsSection(markupDocBuilder, paths);
        applyPathsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
        applyPathsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
    }
    return markupDocBuilder;
}
 
Example #29
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the security section of a Swagger Operation.
 *
 * @param operation the Swagger Operation
 */
private void buildSecuritySchemeSection(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation) {
    if (config.isPathSecuritySectionEnabled()) {
        securitySchemeComponent.apply(markupDocBuilder, SecuritySchemeComponent.parameters(
                operation,
                getSectionTitleLevel()
        ));
    }
}
 
Example #30
Source File: PathOperationComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a operation section title to the document.
 *
 * @param title the section title
 */
private void buildSectionTitle(MarkupDocBuilder markupDocBuilder, String title) {
    if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
        markupDocBuilder.sectionTitleLevel3(title);
    } else {
        markupDocBuilder.sectionTitleLevel4(title);
    }
}