web结构springmvc项目集成swagger离线文档

导入Swagger2Html

springmvc集成swagger

package com.huiyu.swagger;

import com.huiyu.util.OfficeUtil;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.apache.http.HttpRequest;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.AttributesBuilder;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.SafeMode;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Paths;

/**
 * Swagger接口文档转为html文档
 */
public class Swagger2Html {

    private static final String DEFAULT_SWAGGER_API = "http://192.168.0.102:9991/gtkj/v2/api-docs?group=default";

    private static final String DEFAULT_ADOC_PATH = "off-line/adoc/api.adoc";

    private static final String DEFAULT_HTML_PATH = "off-line/html/api.html";

    public static void main(String[] args) throws Exception {
//        String swaggerApi = args.length > 0 ? args[0] : DEFAULT_SWAGGER_API;
//        String adocPath = args.length > 1 ? args[1] : DEFAULT_ADOC_PATH;
//        String htmlPath = args.length > 2 ? args[2] : DEFAULT_HTML_PATH;
//
//        System.out.println("swaggerApi: " + swaggerApi);
//        System.out.println("adocPath: " + adocPath);
//        System.out.println("htmlPath: " + htmlPath);
//
//        generateAsciiDocsToFile(swaggerApi, adocPath);
//
//        convert2Html(adocPath, htmlPath);
        String path = ClassLoader.getSystemResource("").getFile();//注意getResource("")里面是空字符串
        FileInputStream inputStream = new FileInputStream(path + "/off-line/html/api.html");
//        System.out.println("*** success!!! ***");

    }

    /**
     * 获取项目地址,并生成htmL
     * @param request
     * @throws Exception
     */
    public static void generate(HttpServletRequest request, String path) throws Exception {
        path = path.substring(1);
        String adocPath = path + DEFAULT_ADOC_PATH;
        String htmlPath = path + DEFAULT_HTML_PATH;
        String requestURI = request.getRequestURI();//获取访问路径: 项目名+servlet
        StringBuffer requestURL = request.getRequestURL();// 获取完整路径:
        String swaggerApi = requestURL.substring(0, requestURL.indexOf(requestURI));
        String contextPath  = request.getContextPath();
        swaggerApi += contextPath + "/v2/api-docs?group=%E7%94%A8%E6%88%B7";

        generateAsciiDocsToFile(swaggerApi, adocPath);
        File file = new File(path + "/off-line/html");
        if (!file.exists()){
            file.mkdirs();
        }
        convert2Html(adocPath, htmlPath);
    }

    /**
     * 生成AsciiDocs格式文档,并汇总成一个文件
     */
    private static void generateAsciiDocsToFile(String swaggerApi, String filePath) throws Exception {
        // 输出Ascii到单个文件
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL(swaggerApi))
                .withConfig(config)
                .build()
                .toFileWithoutExtension(Paths.get(filePath));
        System.out.println("path:" + Paths.get(filePath));
    }

    /**
     * convert AsciiDoc files using AsciidoctorJ.
     * 参考: https://github.com/asciidoctor/asciidoctor-maven-plugin/blob/master/src/main/java/org/asciidoctor/maven/AsciidoctorMojo.java
     */
    private static void convert2Html(String sourceFile, String targetFile) throws Exception {
        try (Asciidoctor asciidoctor = Asciidoctor.Factory.create()) {
            AttributesBuilder attributes = AttributesBuilder.attributes()
                    .sourceHighlighter("coderay")
                    .attribute("toc", "left")
                    .attribute("toclevels", "3")
                    .attribute("sectnums");

            OptionsBuilder options = OptionsBuilder.options()
                    .docType("book")
                    .backend("html")
                    .safe(SafeMode.UNSAFE)
                    .headerFooter(true)
                    .attributes(attributes)
                    .toFile(new File(targetFile));

            asciidoctor.convertFile(new File(sourceFile), options);
        }
    }
}

通过接口调用


	/**
	 * 查看移动审批离线文档
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="getOffLineApiHtml",produces={"text/html;charset=utf-8"})
	@ApiOperation(value = "查看移动审批离线文档", httpMethod = "GET", notes = "查看移动审批离线文档")
	@ApiResponses({ @ApiResponse(code = 200, message = "成功"), @ApiResponse(code = 400, message = "失败") })
	@ResponseBody
	public void getOffLineApiHtml(HttpServletRequest request, HttpServletResponse response, boolean isOnLine) throws Exception {
		String path = this.getClass().getClassLoader().getResource("").getFile();//注意getResource("")里面是空字符串
		File f = new File(path + "/off-line/html/api.html");
		if (!f.exists()) {
			Swagger2Html.generate(request, path);
		}
		BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
		byte[] buf = new byte[1024];
		int len = 0;

		response.reset(); // 非常重要

		if (isOnLine) { // 在线打开方式
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
			// 文件名应该编码成UTF-8
		} else { // 纯下载方式
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
		}

		OutputStream out = response.getOutputStream();
		while ((len = br.read(buf)) > 0)
		out.write(buf, 0, len);
		br.close();
		out.close();
	}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值