001package com.credibledoc.substitution.doc.module.substitution.markdown.table;
002
003import com.credibledoc.substitution.core.resource.ResourceService;
004import com.credibledoc.substitution.core.template.TemplateService;
005import com.github.javaparser.JavaParser;
006import com.github.javaparser.ast.CompilationUnit;
007import com.github.javaparser.ast.body.EnumConstantDeclaration;
008import com.github.javaparser.ast.body.EnumDeclaration;
009import com.github.javaparser.javadoc.Javadoc;
010import lombok.RequiredArgsConstructor;
011import net.steppschuh.markdowngenerator.table.Table;
012import org.springframework.stereotype.Service;
013
014import javax.inject.Inject;
015
016/**
017 * This service generates markdown tables, see the {@link #createMarkdownTableFromEnum(Table.Builder, Class)} method.
018 *
019 * @author Kyrylo Semenko
020 */
021@Service
022@RequiredArgsConstructor(onConstructor = @__(@Inject))
023public class TableService {
024
025    private static final String EMPTY_STRING = "";
026    private static final String ONE_SPACE = " ";
027    private static final String NEW_LINE = "\\r\\n|\\n";
028
029    /**
030     * Generates content of a table with two columns from {@link Enum} fields.
031     * <p>
032     * Example of usage:
033     * <pre>
034     *     public String generate() {
035     *         Table.Builder tableBuilder = new Table.Builder()
036     *                 .addRow("Application name", "Description");
037     *
038     *         return tableService.createMarkdownTableFromEnum(tableBuilder, TacticHolder.class);
039     *     }
040     * </pre>
041     *
042     * @param tableBuilder en empty table with header
043     * @param enumClass    the data source
044     * @return the first column with enum fields and a second column with
045     * fields JavaDoc
046     */
047    public String createMarkdownTableFromEnum(Table.Builder tableBuilder, Class<?> enumClass) {
048        String resourceRelativePath = ResourceService.getInstance().getResource(enumClass);
049
050        String sourceCode = TemplateService.getInstance()
051                .getTemplateContent(resourceRelativePath);
052
053        CompilationUnit compilationUnit = JavaParser.parse(sourceCode);
054
055        EnumDeclaration enumDeclaration = (EnumDeclaration) compilationUnit.getTypes().get(0);
056        for (EnumConstantDeclaration enumConstantDeclaration : enumDeclaration.getEntries()) {
057            String name = enumConstantDeclaration.getName().asString();
058            String javadocString = EMPTY_STRING;
059            Javadoc javadoc = enumConstantDeclaration.getJavadoc().orElse(null);
060            if (javadoc != null) {
061                javadocString = javadoc.toText().replaceAll(NEW_LINE, ONE_SPACE);
062            }
063            tableBuilder.addRow(name, javadocString);
064        }
065        return tableBuilder.build().toString();
066    }
067}