徹底經過Spring Boot工程 Java代碼,將swagger json 一鍵解析爲html頁面、導出word和execel的解析算法,不須要任何網上那些相似於「SwaggerMarkup2」等插件來實現。css
因爲業務須要,準備開發一個openapi開放平臺,相似於阿里巴巴的CSB雲服務總線項目,用於企業內外服務能力的打通和統一開放管理,提供獨特的跨環境服務級聯機制和常見協議適配支持,實現了對api接口的對外發布和訂閱審覈,讓企業內外都可以更方便的使用到api接口。html
其中須要實現一個核心功能,服務的導入功能,經過swagger json將咱們其餘項目中已經寫好的接口一鍵導入到這個api開放平臺並生成api接口詳情頁,那麼這就須要實現一個swagger json解析的操做。前端
下面立刻進入正題,本文主要也是分享一下,本身解析swagger json爲html、word等功能的代碼、思路以及界面。java
將下圖這樣的swagger json解析出一個個api接口詳情頁。node
經過json解析完能夠顯示全部的接口信息,如圖:git
這是單個接口的api詳情信息,以下圖:程序員
點擊按鈕導出api詳情頁爲word的效果展現,如圖:github
導出word: web
我這邊實現兩種思路,一是直接解析swagger json而後直接存入實體類生成爲html,還要一種是創建好實體類以及數據庫表後,將swagger json解析入庫入表作持久化,再經過表中數據渲染到頁面上。算法
下面我是介紹的swagger json入庫入表再渲染爲html的方案。
步驟大概是:首先定義好建好表,寫好實體類後,再開始實現swagger json解析的算法。
@ApiModel(value = "服務資源表", description = "服務資源表") public class ServiceResource implements Serializable{ /** * 程序序列化ID */ private static final long serialVersionUID=1L; /** * 服務ID */ @ApiModelProperty(value = "服務ID") private String id; /** * 租戶 */ @ApiModelProperty(value = "租戶") private String gmtTenant; /** * 建立時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "建立時間") private Date gmtCreate; public Date getGmtCreate(){ return gmtCreate==null?null:(Date) gmtCreate.clone(); } public void setGmtCreate(Date gmtCreate){ this.gmtCreate = gmtCreate==null?null:(Date) gmtCreate.clone(); } /** * 建立人 */ @ApiModelProperty(value = "建立人") private String gmtCreator; /** * 建立人名稱 */ @ApiModelProperty(value = "建立人名稱") private String gmtCrtname; /** * 最後修改時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "最後修改時間") private Date gmtModified; public Date getGmtModified(){ return gmtModified==null?null:(Date) gmtModified.clone(); } public void setGmtModified(Date gmtModified){ this.gmtModified = gmtModified==null?null:(Date) gmtModified.clone(); } /** * 最後修改人 */ @ApiModelProperty(value = "最後修改人") private String gmtModifiedby; /** * 最後修改人名稱 */ @ApiModelProperty(value = "最後修改人名稱") private String gmtMfyname; /** * 服務名稱 */ @ApiModelProperty(value = "服務名稱") private String serviceName; /** * 請求地址 */ @ApiModelProperty(value = "請求地址") private String requestUrl; /** * 請求方法 */ @ApiModelProperty(value = "請求方法") private String requestMethod; /** * 請求格式 */ @ApiModelProperty(value = "請求類型") private String contentType; /** * 返回類型 */ @ApiModelProperty(value = "返回類型") private String callContentType; /** * 服務描述 */ @ApiModelProperty(value = "服務描述") private String serviceDesc; /** * 服務版本 */ @ApiModelProperty(value = "服務版本") private String serviceVersion; /** * 是否有效 */ @ApiModelProperty(value = "是否有效") private Integer isValid; /** * 是否發佈 */ @ApiModelProperty(value = "是否發佈") private Integer isRelease; /** * 是否發佈 */ @ApiModelProperty(value = "是否須要受權訪問") private Integer isAuthorizedAccess; /** * 操做id */ @ApiModelProperty(value = "操做id") private String operationId; private Integer isDelete; private String routeUuid; private String currentCatalogId; public static long getSerialVersionUID() { return serialVersionUID; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getGmtTenant() { return gmtTenant; } public void setGmtTenant(String gmtTenant) { this.gmtTenant = gmtTenant; } public String getGmtCreator() { return gmtCreator; } public void setGmtCreator(String gmtCreator) { this.gmtCreator = gmtCreator; } public String getGmtCrtname() { return gmtCrtname; } public void setGmtCrtname(String gmtCrtname) { this.gmtCrtname = gmtCrtname; } public String getGmtModifiedby() { return gmtModifiedby; } public void setGmtModifiedby(String gmtModifiedby) { this.gmtModifiedby = gmtModifiedby; } public String getGmtMfyname() { return gmtMfyname; } public void setGmtMfyname(String gmtMfyname) { this.gmtMfyname = gmtMfyname; } public String getServiceName() { if(!StringUtils.isEmpty(serviceName)){ return serviceName.replaceAll(" ", ""); } return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getRequestUrl() { return requestUrl; } public void setRequestUrl(String requestUrl) { this.requestUrl = requestUrl; } public String getRequestMethod() { return requestMethod; } public void setRequestMethod(String requestMethod) { this.requestMethod = requestMethod; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getCallContentType() { return callContentType; } public void setCallContentType(String callContentType) { this.callContentType = callContentType; } public String getServiceDesc() { return serviceDesc; } public void setServiceDesc(String serviceDesc) { this.serviceDesc = serviceDesc; } public String getServiceVersion() { return serviceVersion; } public void setServiceVersion(String serviceVersion) { this.serviceVersion = serviceVersion; } public Integer getIsValid() { return isValid; } public void setIsValid(Integer isValid) { this.isValid = isValid; } public Integer getIsRelease() { return isRelease; } public void setIsRelease(Integer isRelease) { this.isRelease = isRelease; } public Integer getIsAuthorizedAccess() { return isAuthorizedAccess; } public void setIsAuthorizedAccess(Integer isAuthorizedAccess) { this.isAuthorizedAccess = isAuthorizedAccess; } public String getOperationId() { return operationId; } public void setOperationId(String operationId) { this.operationId = operationId; } public Integer getIsDelete() { return isDelete; } public void setIsDelete(Integer isDelete) { this.isDelete = isDelete; } public String getRouteUuid() { return routeUuid; } public void setRouteUuid(String routeUuid) { this.routeUuid = routeUuid; } public String getCurrentCatalogId() { return currentCatalogId; } public void setCurrentCatalogId(String currentCatalogId) { this.currentCatalogId = currentCatalogId; } }
@Data @ApiModel(value = "服務請求信息表", description = "服務請求信息表") public class ServiceRequest implements Serializable{ /** * 程序序列化ID */ private static final long serialVersionUID=1L; /** * 服務ID */ @ApiModelProperty(value = "服務ID") private String id; /** * 租戶 */ @ApiModelProperty(value = "租戶") private String gmtTenant; /** * 建立時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "建立時間") private Date gmtCreate; public Date getGmtCreate(){ return gmtCreate==null?null:(Date) gmtCreate.clone(); } public void setGmtCreate(Date gmtCreate){ this.gmtCreate = gmtCreate==null?null:(Date) gmtCreate.clone(); } /** * 建立人 */ @ApiModelProperty(value = "建立人") private String gmtCreator; /** * 建立人名稱 */ @ApiModelProperty(value = "建立人名稱") private String gmtCrtname; /** * 最後修改時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "最後修改時間") private Date gmtModified; public Date getGmtModified(){ return gmtModified==null?null:(Date) gmtModified.clone(); } public void setGmtModified(Date gmtModified){ this.gmtModified = gmtModified==null?null:(Date) gmtModified.clone(); } /** * 最後修改人 */ @ApiModelProperty(value = "最後修改人") private String gmtModifiedby; /** * 最後修改人名稱 */ @ApiModelProperty(value = "最後修改人名稱") private String gmtMfyname; /** * 服務資源ID */ @ApiModelProperty(value = "服務資源ID") private String serviceId; /** * 參數名稱 */ @ApiModelProperty(value = "參數名稱") private String reqName; /** * 參數描述 */ @ApiModelProperty(value = "參數描述") private String reqDesc; /** * 參數類型 */ @ApiModelProperty(value = "參數類型") private String reqType; /** * 參數長度 */ @ApiModelProperty(value = "參數長度") private Integer reqLength; /** * 是否必填 */ @ApiModelProperty(value = "是否必填") private Integer isRequired; /** * 參數來源 */ @ApiModelProperty(value = "參數來源") private String reqFrom; }
@Data @ApiModel(value = "服務響應信息表", description = "服務響應信息表") public class ServiceResponse implements Serializable{ /** * 程序序列化ID */ private static final long serialVersionUID=1L; /** * 服務ID */ @ApiModelProperty(value = "服務ID") private String id; /** * 租戶 */ @ApiModelProperty(value = "租戶") private String gmtTenant; /** * 建立時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "建立時間") private Date gmtCreate; public Date getGmtCreate(){ return gmtCreate==null?null:(Date) gmtCreate.clone(); } public void setGmtCreate(Date gmtCreate){ this.gmtCreate = gmtCreate==null?null:(Date) gmtCreate.clone(); } /** * 建立人 */ @ApiModelProperty(value = "建立人") private String gmtCreator; /** * 建立人名稱 */ @ApiModelProperty(value = "建立人名稱") private String gmtCrtname; /** * 最後修改時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "最後修改時間") private Date gmtModified; public Date getGmtModified(){ return gmtModified==null?null:(Date) gmtModified.clone(); } public void setGmtModified(Date gmtModified){ this.gmtModified = gmtModified==null?null:(Date) gmtModified.clone(); } /** * 最後修改人 */ @ApiModelProperty(value = "最後修改人") private String gmtModifiedby; /** * 最後修改人名稱 */ @ApiModelProperty(value = "最後修改人名稱") private String gmtMfyname; /** * 服務資源ID */ @ApiModelProperty(value = "服務資源ID") private String serviceId; /** * 屬性名稱 */ @ApiModelProperty(value = "屬性名稱") private String propName; /** * 屬性描述 */ @ApiModelProperty(value = "屬性描述") private String propDesc; /** * 屬性類型 */ @ApiModelProperty(value = "屬性類型") private String propType; /** * 屬性長度 */ @ApiModelProperty(value = "屬性長度") private Integer propLength; }
@Data @ApiModel(value = "服務響應狀態表", description = "服務響應狀態表") public class ResponseStatus implements Serializable{ /** * 程序序列化ID */ private static final long serialVersionUID=1L; /** * 服務ID */ @ApiModelProperty(value = "服務ID") private String id; /** * 租戶 */ @ApiModelProperty(value = "租戶") private String gmtTenant; /** * 建立時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "建立時間") private Date gmtCreate; public Date getGmtCreate(){ return gmtCreate==null?null:(Date) gmtCreate.clone(); } public void setGmtCreate(Date gmtCreate){ this.gmtCreate = gmtCreate==null?null:(Date) gmtCreate.clone(); } /** * 建立人 */ @ApiModelProperty(value = "建立人") private String gmtCreator; /** * 建立人名稱 */ @ApiModelProperty(value = "建立人名稱") private String gmtCrtname; /** * 最後修改時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "最後修改時間") private Date gmtModified; public Date getGmtModified(){ return gmtModified==null?null:(Date) gmtModified.clone(); } public void setGmtModified(Date gmtModified){ this.gmtModified = gmtModified==null?null:(Date) gmtModified.clone(); } /** * 最後修改人 */ @ApiModelProperty(value = "最後修改人") private String gmtModifiedby; /** * 最後修改人名稱 */ @ApiModelProperty(value = "最後修改人名稱") private String gmtMfyname; /** * 服務資源ID */ @ApiModelProperty(value = "服務資源ID") private String serviceId; /** * 狀態碼 */ @ApiModelProperty(value = "狀態碼") private String statusCode; /** * 狀態描述 */ @ApiModelProperty(value = "狀態描述") private String statusDesc; /** * 狀態說明 */ @ApiModelProperty(value = "狀態說明") private String statusRemark; }
@ApiModel(value = "服務類別表", description = "服務類別表") public class ServiceCatalog implements Serializable{ /** * 程序序列化ID */ private static final long serialVersionUID=1L; /** * 服務ID */ @ApiModelProperty(value = "服務ID") private String id; /** * 租戶 */ @ApiModelProperty(value = "租戶") private String gmtTenant; /** * 建立時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "建立時間") private Date gmtCreate; public Date getGmtCreate(){ return gmtCreate==null?null:(Date) gmtCreate.clone(); } public void setGmtCreate(Date gmtCreate){ this.gmtCreate = gmtCreate==null?null:(Date) gmtCreate.clone(); } /** * 建立人 */ @ApiModelProperty(value = "建立人") private String gmtCreator; /** * 建立人名稱 */ @ApiModelProperty(value = "建立人名稱") private String gmtCrtname; /** * 最後修改時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "最後修改時間") private Date gmtModified; public Date getGmtModified(){ return gmtModified==null?null:(Date) gmtModified.clone(); } public void setGmtModified(Date gmtModified){ this.gmtModified = gmtModified==null?null:(Date) gmtModified.clone(); } /** * 最後修改人 */ @ApiModelProperty(value = "最後修改人") private String gmtModifiedby; /** * 最後修改人名稱 */ @ApiModelProperty(value = "最後修改人名稱") private String gmtMfyname; /** * 上級目錄ID */ @ApiModelProperty(value = "上級目錄ID") private String pid; /** * 目錄名稱 */ @ApiModelProperty(value = "目錄名稱") private String catalogName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getGmtTenant() { return gmtTenant; } public void setGmtTenant(String gmtTenant) { this.gmtTenant = gmtTenant; } public String getGmtCreator() { return gmtCreator; } public void setGmtCreator(String gmtCreator) { this.gmtCreator = gmtCreator; } public String getGmtCrtname() { return gmtCrtname; } public void setGmtCrtname(String gmtCrtname) { this.gmtCrtname = gmtCrtname; } public String getGmtModifiedby() { return gmtModifiedby; } public void setGmtModifiedby(String gmtModifiedby) { this.gmtModifiedby = gmtModifiedby; } public String getGmtMfyname() { return gmtMfyname; } public void setGmtMfyname(String gmtMfyname) { this.gmtMfyname = gmtMfyname; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getCatalogName() { if(!StringUtils.isEmpty(catalogName)){ return catalogName.replaceAll(" ", ""); } return catalogName; } public void setCatalogName(String catalogName) { this.catalogName = catalogName; } }
@Data @ApiModel(value = "服務類別關係表", description = "服務類別關係表") public class ServiceCatalogRela implements Serializable{ /** * 程序序列化ID */ private static final long serialVersionUID=1L; /** * 服務ID */ @ApiModelProperty(value = "服務ID") private String id; /** * 租戶 */ @ApiModelProperty(value = "租戶") private String gmtTenant; /** * 建立時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "建立時間") private Date gmtCreate; public Date getGmtCreate(){ return gmtCreate==null?null:(Date) gmtCreate.clone(); } public void setGmtCreate(Date gmtCreate){ this.gmtCreate = gmtCreate==null?null:(Date) gmtCreate.clone(); } /** * 建立人 */ @ApiModelProperty(value = "建立人") private String gmtCreator; /** * 建立人名稱 */ @ApiModelProperty(value = "建立人名稱") private String gmtCrtname; /** * 最後修改時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ApiModelProperty(value = "最後修改時間") private Date gmtModified; public Date getGmtModified(){ return gmtModified==null?null:(Date) gmtModified.clone(); } public void setGmtModified(Date gmtModified){ this.gmtModified = gmtModified==null?null:(Date) gmtModified.clone(); } /** * 最後修改人 */ @ApiModelProperty(value = "最後修改人") private String gmtModifiedby; /** * 最後修改人名稱 */ @ApiModelProperty(value = "最後修改人名稱") private String gmtMfyname; /** * 目錄ID */ @ApiModelProperty(value = "目錄ID") private String catalogId; /** * 服務ID */ @ApiModelProperty(value = "服務ID") private String serviceId; }
@Data public class SwaggerModelAttr implements Serializable { private static final long serialVersionUID = -4074067438450613643L; /** * 類名 */ private String className = StringUtils.EMPTY; /** * 屬性名 */ private String name = StringUtils.EMPTY; /** * 類型 */ private String type = StringUtils.EMPTY; /** * 屬性描述 */ private String description; /** * 嵌套屬性列表 */ private List<SwaggerModelAttr> properties = new ArrayList<>(); }
/** * @program: share-capacity-platform * @description: javabean轉html 傳遞給前端的dto實體類 * @author: liumingyu * @date: 2020-04-14 16:35 **/ @Data public class SwaggerHtmlDto { /** * 大標題 */ private String title; /** * 小標題 */ private String tag; /** * 版本 */ private String version; /** * 封裝服務資源 */ private ServiceResource serviceResource; /** * 封裝請求參數list */ private List<ServiceRequest> requestList; /** * 封裝響應狀態碼list */ private List<ResponseStatus> responseStatusList; /** * 封裝返回屬性list */ private List<ServiceResponse> responseList; }
實體類就是以上這些,將swagger json解析後存入相應的實體類字段中。
下面開始swagger json的解析代碼:
public interface SwaggerJsonImportService { /** * swaggerJson導入業務表 * * @param jsonUrl jsonUrl * @param serviceSwagger swaggerJson * @param isAuthorized 是否須要受權訪問 * @return net.evecom.scplatform.common.entry.CommonResp<java.lang.String> * @throws IOException * @Author Torres Liu * @Description //TODO swaggerJson導入業務表 * @Date 2020/4/24 5:07 下午 * @Param [jsonUrl, serviceSwagger, isAuthorized] **/ CommonResp<String> swaggerJsonImport(String jsonUrl, ServiceSwagger serviceSwagger, String isAuthorized) throws IOException; /** * 導出SwaggerJson * * @param serviceId 服務id * @param catalogId 目錄id * @return net.evecom.scplatform.common.entry.CommonResp<java.lang.String> * @Author Torres Liu * @Description //TODO 導出SwaggerJson * @Date 2020/4/22 9:41 上午 * @Param [serviceId, catalogId] **/ List<SwaggerHtmlDto> swaggerJsonExport(String serviceId, String catalogId); }
下面是一大堆枯燥的json解析,你們都是程序員,我就不作過多的講解代碼,有須要學習的能夠參照我代碼中的註釋,寫的都比較詳細。
package xxxxxxxx; import cn.hutool.json.JSONObject; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import net.evecom.scplatform.common.entry.CommonResp; import net.evecom.scplatform.common.entry.system.CommonEntry; import net.evecom.scplatform.common.entry.system.UserUtil; import net.evecom.scplatform.common.utils.text.IDUtils; import net.evecom.scplatform.openapi.dao.*; import net.evecom.scplatform.openapi.entity.*; import net.evecom.scplatform.openapi.entity.dto.SwaggerHtmlDto; import net.evecom.scplatform.openapi.service.SwaggerJsonImportService; import net.evecom.scplatform.openapi.util.SwaggerJsonUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; /** * @author Torres Liu * @description //TODO 服務導入/導出 業務層 * @date 2020-04-10 14:06 下午 **/ @SuppressWarnings({"unchecked", "rawtypes"}) @Slf4j @Service @Transactional(rollbackFor = Exception.class) public class SwaggerJsonImportServiceImpl implements SwaggerJsonImportService { @Autowired private RestTemplate restTemplate; @Autowired private ServiceCatalogDao serviceCatalogDao; @Autowired private ServiceResourceDao serviceResourceDao; @Autowired private ServiceRequestDao serviceRequestDao; @Autowired private ResponseStatusDao responseStatusDao; @Autowired private ServiceResponseDao serviceResponseDao; @Autowired private ServiceCatalogRelaDao serviceCatalogRelaDao; @Value("${kong.server-addr}") private String kongServerAddr; /** * array */ private static final String ARRAY_VAL = "array"; /** * $ref */ private static final String REF_VAL = "$ref"; /** * format */ private static final String FORMAT_VAL = "format"; /** * schema */ private static final String SCHEMA_VAL = "schema"; /** * 成功的code */ private static final int SUCCESS_CODE = 200; /** * 遞歸次數 */ private static final int RECURSION_NUMS = 199; /** * 經過JSON或URL導入服務 * * @param jsonUrl * @param serviceSwagger * @param isAuthorized * @return net.evecom.scplatform.common.entry.CommonResp<java.lang.String> * @author Torres Liu * @description //TODO 經過JSON或URL導入服務 * @date 2020/4/24 5:46 下午 **/ @Override @Transactional(rollbackFor = Exception.class) public CommonResp<String> swaggerJsonImport(String jsonUrl, ServiceSwagger serviceSwagger, String isAuthorized) throws IOException { String jsonStr = ""; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //提早生成 一級標題的id字段 by liumingyu String firstTitleUuid = IDUtils.new32UUID(); //獲取前端傳入的是否受權標識 by liumingyu String isAuthorizedAccessStr = StringUtils.defaultIfBlank(isAuthorized, "0"); Integer isAuthorizedAccess = Integer.valueOf(isAuthorizedAccessStr); try { //判斷是經過url or json傳入數據 by liumingyu if (!StringUtils.isBlank(jsonUrl) && "".equals(serviceSwagger.getSwaggerJson())) { //判斷url的有效性 boolean urlValidity = ifUrlValidity(jsonUrl); //判斷url是不是swagger的url boolean swaggerUrl = ifSwaggerUrl(jsonUrl); if (urlValidity && swaggerUrl) { HttpGet httpGet = new HttpGet(jsonUrl); CloseableHttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == SUCCESS_CODE) { HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity, "utf-8"); jsonStr = string; } response.close(); httpClient.close(); } else { return CommonResp.exception("傳入的url不正確!"); } } else if (serviceSwagger != null && !"".equals(serviceSwagger.getSwaggerJson())) { String swaggerJson = serviceSwagger.getSwaggerJson(); //判斷字符串是否爲json格式 boolean isJson = isJson(swaggerJson); if (isJson) { JSONObject jsonObject = new JSONObject(swaggerJson); Object o = JSON.toJSON(jsonObject); jsonStr = com.alibaba.fastjson.JSONObject.toJSONString(o); } else { return CommonResp.exception("傳入的json格式不正確!"); } } else { return CommonResp.exception("服務導入URL或JSON出錯!"); } //獲取當前租戶 String gmtTenant = UserUtil.getLoginUser().getGmtTenant(); //獲取當前用戶id String userId = UserUtil.getLoginUser().getId(); String gmtCreator = (userId != null) ? userId : ""; //轉換 JSON string to Map by liumingyu Map<String, Object> map = SwaggerJsonUtils.readValue(jsonStr, HashMap.class); //解析info by liumingyu Map<String, Object> infoMap = (Map<String, Object>) map.get("info"); //拿到一級標題 by liumingyu String catalogName = (String) infoMap.get("title"); //拿到全部二級標題(類標題)的List by liumingyu List<Map<String, String>> tags = (List<Map<String, String>>) map.get("tags"); //若是表中沒有該一級標題名稱,須要新增一個 by liumingyu if (catalogName != null) { //查詢庫中是否有當前登陸用戶且pid爲-1的根目錄 ServiceCatalog catalogBeanByCreatorAndPid = serviceCatalogDao.findByCreatorAndPid(gmtCreator, "-1"); //查詢庫中是否存在該一級標題名稱 by liumingyu ServiceCatalog catalogBean = serviceCatalogDao.findByCatalogNameAndCreator(gmtCreator, catalogName); //若不存在該標題名稱,新增一級目錄和二級目錄 by liumingyu //1.插入一級二級標題數據到服務目錄表 by liumingyu if (catalogBean == null && catalogBeanByCreatorAndPid != null) { ServiceCatalog serviceCatalog = new ServiceCatalog(); serviceCatalog.setId(firstTitleUuid); //將根目錄id做爲一級目錄的pid serviceCatalog.setPid(catalogBeanByCreatorAndPid.getId()); serviceCatalog.setCatalogName(catalogName); serviceCatalogDao.add(serviceCatalog); //添加二級標題(目錄)by liumingyu addTags(tags, firstTitleUuid, gmtTenant, gmtCreator); } else { //存在的話只要新增二級標題 by liumingyu //拿到該一級目錄的id by liumingyu if (catalogBean != null && catalogBean.getId() != null) { String fatherId = catalogBean.getId(); //添加二級標題(目錄)by liumingyu addTags(tags, fatherId, gmtTenant, gmtCreator); } } } //解析model by liumingyu Map<String, SwaggerModelAttr> definitinMapOld = parseDefinitions(map); Map<String, Map<String, Object>> definitinMap = newParseDefinitions(map); //獲取服務版本(取得是一級info的版本號)by liumingyu String version = (String) infoMap.get("version"); //解析paths by liumingyu Map<String, Map<String, Object>> paths = (Map<String, Map<String, Object>>) map.get("paths"); //解析bashPath by liumingyu String basePath = (String) map.get("basePath"); String[] basePathSplit = null; if (basePath != null && !"".equals(basePath)) { basePathSplit = basePath.split(","); } if (paths != null) { //經過entrySet()取出映射關係,iterator()迭代,存放到迭代器中 by liumingyu Iterator<Map.Entry<String, Map<String, Object>>> it = paths.entrySet().iterator(); //開始遍歷paths by liumingyu while (it.hasNext()) { //拿到單個path的數據信息,用map的Entry對象存起來 by liumingyu Map.Entry<String, Map<String, Object>> path = it.next(); Iterator<Map.Entry<String, Object>> it2 = path.getValue().entrySet().iterator(); //請求url by liumingyu String requestUrl = ""; if (basePathSplit.length > 0 && !"/".equals(basePathSplit[0])) { //拼接 bashPath + url by liumingyu requestUrl = kongServerAddr + basePathSplit[0] + path.getKey(); } else { requestUrl = kongServerAddr + path.getKey(); } while (it2.hasNext()) { Map.Entry<String, Object> it2Request = it2.next(); //請求方法 GET / POST 等等 by liumingyu String requestMethod = it2Request.getKey().toUpperCase(); //拿到某個接口(服務)的具體數據 by liumingyu Map<String, Object> content = (Map<String, Object>) it2Request.getValue(); //服務名稱 by liumingyu String serviceName = String.valueOf(content.get("summary")); //該服務的操做id by liumingyu String operationId = String.valueOf(content.get("operationId")); //請求體 by liumingyu List<LinkedHashMap> parametersList = (ArrayList) content.get("parameters"); //響應Code體 by liumingyu Map<String, Object> responsesList = (Map<String, Object>) content.get("responses"); //服務描述 by liumingyu String serviceDesc = ""; String description = String.valueOf(content.get("description")); if (!"".equals(description) && description != null) { serviceDesc = description; } //請求參數格式,相似於 multipart/form-data by liumingyu String contentType = ""; List<String> consumes = (List) content.get("consumes"); if (consumes != null && consumes.size() > 0) { contentType = StringUtils.join(consumes, ","); } //返回參數格式,相似於 application/json by liumingyu String callContentType = ""; List<String> produces = (List) content.get("produces"); List<String> newProduces = new ArrayList<>(); for (String produce : produces) { String newProduce = ""; if ("*/*".equals(produce) || "".equals(produce)) { newProduce = "application/json"; } else { newProduce = produce; } newProduces.add(newProduce); } if (newProduces != null && newProduces.size() > 0) { callContentType = StringUtils.join(newProduces, ","); } //服務版本默認爲1.0 by liumingyu String serviceVersion = "1.0"; serviceVersion = StringUtils.defaultIfBlank(version, serviceVersion); //查詢當前庫中是否存在operationId和服務名稱,若是存在 後續全部數據不會進行添加 by liumingyu List<ServiceResource> listByOperationId = serviceResourceDao.findByOperationId(operationId, serviceName, userId); //若operationId不存在庫中====>才進行後續的添加操做 by liumingyu if (listByOperationId.size() == 0) { //封裝serviceResource表 by liumingyu ServiceResource resourceTable = new ServiceResource(); //聲明一個uuid 做爲本輪遍歷的resource表主鍵id,也是本輪遍歷其餘表對應的serviceId by liumingyu String thisResourceId = IDUtils.new32UUID(); resourceTable.setId(thisResourceId); resourceTable.setServiceName(serviceName); resourceTable.setServiceDesc(serviceDesc); resourceTable.setRequestUrl(requestUrl); resourceTable.setRequestMethod(requestMethod); resourceTable.setContentType(contentType); resourceTable.setCallContentType(callContentType); resourceTable.setServiceVersion(serviceVersion); resourceTable.setIsValid(1); resourceTable.setIsRelease(0); resourceTable.setIsDelete(0); resourceTable.setRouteUuid(UUID.randomUUID().toString()); //前端傳入--->是否受權標識 by liumingyu resourceTable.setIsAuthorizedAccess(isAuthorizedAccess); //添加操做id by liumingyu resourceTable.setOperationId(operationId); //2.添加數據到serviceResource表 by liumingyu serviceResourceDao.add(resourceTable); //處理parametersList數據轉爲ServiceRequest表List對象 by liumingyu List<ServiceRequest> serviceRequestList = processRequestList(parametersList, definitinMap); //3.添加數據到serviceRequest表 by liumingyu addServiceRequest(serviceRequestList, thisResourceId, gmtTenant); //處理responsesList數據轉爲ResponseStatus表List對象 by liumingyu List<ResponseStatus> responseStatusList = processResponseStatusList(responsesList, definitinMap); //4.添加數據到ResponseStatus表 by liumingyu addResponseStatus(responseStatusList, thisResourceId, gmtTenant); //取出來狀態是200時的返回值 by liumingyu Map<String, Object> responsesObj = (Map<String, Object>) responsesList.get("200"); if (responsesObj != null && responsesObj.get(SCHEMA_VAL) != null) { //處理相應的返回值 by liumingyu SwaggerModelAttr swaggerModelAttr = processResponseModelAttrs(responsesObj, definitinMapOld); //拿到properties數據,這個List裏面就是須要的返回值數據 by liumingyu List<SwaggerModelAttr> propertiesList = swaggerModelAttr.getProperties(); //5.添加數據到ServiceResponse表(傳遞propertiesList和主表的id) by liumingyu addServiceResponse(propertiesList, thisResourceId, gmtTenant); } //操做服務類別關係表(目錄和服務關係表) by liumingyu String tagsName = String.valueOf(((List) content.get("tags")).get(0)); //6.添加數據到目錄關係表 by liumingyu addCatalogRela(tagsName, thisResourceId, gmtCreator); } else { log.info("迭代器當前執行到的對象operationId「" + operationId + "」已存在數據庫中,不進行插入"); } } } } } catch (Exception e) { log.error("服務導入失敗", e); return CommonResp.exception("服務導入失敗"); } return CommonResp.succeed("服務導入成功!"); } /** * 服務導出Json * * @param serviceId * @param catalogId * @return java.util.List<net.evecom.scplatform.openapi.entity.dto.SwaggerHtmlDto> * @author Torres Liu * @description //TODO 服務導出Json * @date 2020/4/24 5:50 下午 **/ @Override public List<SwaggerHtmlDto> swaggerJsonExport(String serviceId, String catalogId) { String titleName = ""; List<SwaggerHtmlDto> result = new ArrayList<>(); try { if (serviceId != null && !"".equals(serviceId)) { SwaggerHtmlDto thisDto = new SwaggerHtmlDto(); //根據serviceId查詢所需數據 ServiceResource resourceTable = serviceResourceDao.findById(serviceId); List<ServiceRequest> requestList = serviceRequestDao.findByServiceId(serviceId); List<ResponseStatus> responseStatusList = responseStatusDao.findByServiceId(serviceId); List<ServiceResponse> serviceResponseList = serviceResponseDao.findByServiceId(serviceId); ServiceCatalog thisCatalogBean = serviceCatalogDao.findById(catalogId == null ? "" : catalogId); //將數據set到自定義封裝的dto實體中 thisDto.setServiceResource(resourceTable); thisDto.setRequestList(requestList); thisDto.setResponseStatusList(responseStatusList); thisDto.setResponseList(serviceResponseList); //聲明一個標題名 titleName = resourceTable.getServiceName(); if (thisCatalogBean != null) { thisDto.setTag(thisCatalogBean.getCatalogName()); titleName = thisCatalogBean.getCatalogName() + "-" + titleName; String thisCatalogPid = thisCatalogBean.getPid(); ServiceCatalog pidBean = serviceCatalogDao.findById(thisCatalogPid); if (pidBean != null) { thisDto.setTitle(pidBean.getCatalogName()); titleName = pidBean.getCatalogName() + "-" + titleName; } } thisDto.setVersion(resourceTable.getServiceVersion()); //將全部數據add至result result.add(thisDto); return result; } } catch (Exception e) { log.error("服務導出異常:", e); } return result; } /** * @param tags * @param pid * @param gmtTenant * @return void * @author Torres Liu * @description //TODO 將json的二級標題,新增至目錄表做爲二級目錄,pid爲一級目錄id * @date 2020/4/24 5:52 下午 **/ private void addTags(List<Map<String, String>> tags, String pid, String gmtTenant, String gmtCreator) { if (tags != null) { gmtTenant = (gmtTenant != null) ? gmtTenant : ""; List<ServiceCatalog> catalogList = new ArrayList<>(); for (Map tag : tags) { String name = (String) tag.get("name"); if (name != null && !"".equals(name)) { ServiceCatalog catalogBean2 = serviceCatalogDao.findByCatalogNameAndCreator(gmtCreator, name); //若是沒有該二級目錄則開始新增二級目錄 by liumingyu if (catalogBean2 == null && pid != null) { ServiceCatalog serviceCatalogBean = new ServiceCatalog(); serviceCatalogBean.setPid(pid); serviceCatalogBean.setCatalogName(name); serviceCatalogBean.setId(IDUtils.new32UUID()); catalogList.add(serviceCatalogBean); } } } if (catalogList.size() > 0) { //傳入List批量添加 serviceCatalogDao.batchAdd(catalogList, new CommonEntry(), gmtTenant); } } } /** * @param serviceRequestList * @param thisResourceId * @param gmtTenant * @return void * @author Torres Liu * @description //TODO 添加數據到 服務請求表 * @date 2020/4/24 5:52 下午 **/ private void addServiceRequest(List<ServiceRequest> serviceRequestList, String thisResourceId, String gmtTenant) { List<ServiceRequest> requestList = new ArrayList<>(); if (serviceRequestList != null && thisResourceId != null) { gmtTenant = (gmtTenant != null) ? gmtTenant : ""; for (ServiceRequest requestParameter : serviceRequestList) { ServiceRequest requestTable = new ServiceRequest(); requestTable.setId(IDUtils.new32UUID()); requestTable.setServiceId(thisResourceId); requestTable.setReqName(requestParameter.getReqName()); requestTable.setReqDesc(requestParameter.getReqDesc()); requestTable.setIsRequired(requestParameter.getIsRequired()); requestTable.setReqType(requestParameter.getReqType()); requestTable.setReqFrom(requestParameter.getReqFrom()); requestList.add(requestTable); } if (requestList.size() > 0) { //批量添加數據 serviceRequestDao.batchAdd(requestList, new CommonEntry(), gmtTenant); } } } /** * @param responseStatusList * @param thisResourceId * @param gmtTenant * @return void * @author Torres Liu * @description //TODO 添加數據到 響應狀態表 * @date 2020/4/24 5:54 下午 **/ private void addResponseStatus(List<ResponseStatus> responseStatusList, String thisResourceId, String gmtTenant) { List<ResponseStatus> statusList = new ArrayList<>(); if (responseStatusList != null && thisResourceId != null) { gmtTenant = (gmtTenant != null) ? gmtTenant : ""; for (ResponseStatus response : responseStatusList) { ResponseStatus responseStatusTable = new ResponseStatus(); responseStatusTable.setId(IDUtils.new32UUID()); responseStatusTable.setServiceId(thisResourceId); responseStatusTable.setStatusCode(response.getStatusCode()); responseStatusTable.setStatusDesc(response.getStatusDesc()); responseStatusTable.setStatusRemark(response.getStatusRemark()); statusList.add(responseStatusTable); } if (statusList.size() > 0) { //批量添加數據 responseStatusDao.batchAdd(statusList, new CommonEntry(), gmtTenant); } } } /** * @param propertiesList * @param thisResourceId * @param gmtTenant * @return void * @author Torres Liu * @description //TODO 添加數據到 服務響應表 * @date 2020/4/24 5:55 下午 **/ private void addServiceResponse(List<SwaggerModelAttr> propertiesList, String thisResourceId, String gmtTenant) { List<ServiceResponse> responseList = new ArrayList<>(); if (propertiesList != null && thisResourceId != null) { gmtTenant = (gmtTenant != null) ? gmtTenant : ""; //添加數據到serviceResponse表 by liumingyu for (SwaggerModelAttr p : propertiesList) { ServiceResponse serviceResponseTable = new ServiceResponse(); serviceResponseTable.setId(IDUtils.new32UUID()); //該服務id 爲前面生成的serviceResource表(主表)的主鍵(資源id)by liumingyu serviceResponseTable.setServiceId(thisResourceId); serviceResponseTable.setPropName(p.getName()); serviceResponseTable.setPropType(p.getType()); serviceResponseTable.setPropDesc(p.getDescription()); responseList.add(serviceResponseTable); } if (responseList.size() > 0) { //批量添加數據 serviceResponseDao.batchAdd(responseList, new CommonEntry(), gmtTenant); } } } /** * @param tagsName * @param thisResourceId * @return void * @author Torres Liu * @description //TODO 添加數據到目錄關係表 * @date 2020/4/24 5:55 下午 **/ private void addCatalogRela(String tagsName, String thisResourceId, String gmtCreator) { ServiceCatalogRela catalogRelaTable = new ServiceCatalogRela(); if (tagsName != null && !"".equals(tagsName) && thisResourceId != null) { //經過tagsName查出目錄id by liumingyu ServiceCatalog catalogBean = serviceCatalogDao.findByCatalogNameAndCreator(gmtCreator, tagsName); if (catalogBean != null && catalogBean.getId() != null) { String catalogId = catalogBean.getId(); catalogRelaTable.setId(IDUtils.new32UUID()); //將目錄id插入關係表 by liumingyu catalogRelaTable.setCatalogId(catalogId); //將當前的服務id插入關係表 by liumingyu catalogRelaTable.setServiceId(thisResourceId); serviceCatalogRelaDao.add(catalogRelaTable); } } } /** * @param map * @return java.util.Map<java.lang.String, net.evecom.scplatform.openapi.entity.SwaggerModelAttr> * @author Torres Liu * @description //TODO 解析Definitions * @date 2020/4/24 5:55 下午 **/ private Map<String, SwaggerModelAttr> parseDefinitions(Map<String, Object> map) { Map<String, Map<String, Object>> definitions = (Map<String, Map<String, Object>>) map.get("definitions"); Map<String, SwaggerModelAttr> definitinMap = new HashMap<>(256); if (definitions != null) { Iterator<String> modelNameIt = definitions.keySet().iterator(); while (modelNameIt.hasNext()) { String modeName = modelNameIt.next(); Map<String, Object> modeProperties = (Map<String, Object>) definitions.get(modeName).get("properties"); if (modeProperties == null) { continue; } Iterator<Map.Entry<String, Object>> mIt = modeProperties.entrySet().iterator(); List<SwaggerModelAttr> attrList = new ArrayList<>(); //解析屬性 by liumingyu while (mIt.hasNext()) { Map.Entry<String, Object> mEntry = mIt.next(); Map<String, Object> attrInfoMap = (Map<String, Object>) mEntry.getValue(); SwaggerModelAttr modeAttr = new SwaggerModelAttr(); modeAttr.setName(mEntry.getKey()); modeAttr.setType((String) attrInfoMap.get("type")); if (attrInfoMap.get(FORMAT_VAL) != null) { modeAttr.setType(modeAttr.getType() + "(" + attrInfoMap.get("format") + ")"); } modeAttr.setType(StringUtils.defaultIfBlank(modeAttr.getType(), "object")); modeAttr.setDescription((String) attrInfoMap.get("description")); attrList.add(modeAttr); } SwaggerModelAttr modeAttr = new SwaggerModelAttr(); Object title = definitions.get(modeName).get("title"); Object description = definitions.get(modeName).get("description"); modeAttr.setClassName(title == null ? "" : title.toString()); modeAttr.setDescription(description == null ? "" : description.toString()); modeAttr.setProperties(attrList); definitinMap.put("#/definitions/" + modeName, modeAttr); } } return definitinMap; } /** * @param map * @return java.util.Map<java.lang.String, java.util.Map < java.lang.String, java.lang.Object>> * @author Torres Liu * @description //TODO 解析Definitions---->new * @date 2020/4/24 5:55 下午 **/ private Map<String, Map<String, Object>> newParseDefinitions(Map<String, Object> map) { Map<String, Map<String, Object>> definitions = (Map<String, Map<String, Object>>) map.get("definitions"); Map<String, Map<String, Object>> definitinMap = new HashMap<>(256); if (definitions != null) { Iterator<String> modelNameIt = definitions.keySet().iterator(); while (modelNameIt.hasNext()) { String modeName = modelNameIt.next(); Map<String, Object> modeProperties = definitions.get(modeName); definitinMap.put("#/definitions/" + modeName, modeProperties); } } return definitinMap; } /** * @param parameters * @param definitionMap * @return java.util.List<net.evecom.scplatform.openapi.entity.ServiceRequest> * @author Torres Liu * @description //TODO 處理請求List * @date 2020/4/24 5:56 下午 **/ private List<ServiceRequest> processRequestList(List<LinkedHashMap> parameters, Map<String, Map<String, Object>> definitionMap) { List<ServiceRequest> requestList = new ArrayList<>(); Map<String, Object> myHashMap = new HashMap<>(2000); if (!CollectionUtils.isEmpty(parameters)) { for (Map<String, Object> param : parameters) { Object in = param.get("in"); ServiceRequest request = new ServiceRequest(); request.setReqName(String.valueOf(param.get("name"))); request.setReqType(param.get("type") == null ? "object" : param.get("type").toString()); request.setReqFrom(String.valueOf(in)); // 考慮對象參數類型 by liumingyu if (in != null && "body".equals(in)) { Map<String, Object> schema = (Map) param.get("schema"); //拿到 ----> #/definitions/文件目錄請求對象 Object ref = schema.get("$ref"); if (ref != null) { Map<String, Object> mapByRefValue = definitionMap.get(ref); if (mapByRefValue != null) { Map<String, Object> propertiesMap = (Map<String, Object>) mapByRefValue.get("properties"); if (propertiesMap != null) { //將properties中的值進行迭代 Iterator<Map.Entry<String, Object>> itProp = propertiesMap.entrySet().iterator(); while (itProp.hasNext()) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dataFormat = simpleDateFormat.format(new Date()); //取到單個值 ----> 如 endRow: {type: "integer", format: "int32"} Map.Entry<String, Object> entryIt = itProp.next(); Map<String, Object> itValue = (Map<String, Object>) entryIt.getValue(); String type = (String) itValue.get("type"); if (!StringUtils.isBlank(type)) { switch (type) { case "string": if (itValue.get(FORMAT_VAL) != null && !"".equals(itValue.get(FORMAT_VAL))) { String format = (String) itValue.get("format"); if ("date-time".equals(format) || "dateTime".equals(format)) { myHashMap.put(entryIt.getKey(), dataFormat); } } else { myHashMap.put(entryIt.getKey(), "string"); } break; case "integer": myHashMap.put(entryIt.getKey(), 0); break; case "number": myHashMap.put(entryIt.getKey(), 0.0); break; case "boolean": myHashMap.put(entryIt.getKey(), true); break; case "array": Integer initNum = 0; //開始調用--->遞歸算法邏輯 ifArrayRecursion(itValue, definitionMap, dataFormat, myHashMap, entryIt, initNum); break; default: myHashMap.put(entryIt.getKey(), null); break; } } } } } } request.setReqDesc(JSON.toJSONString(myHashMap)); } else { request.setReqDesc((String.valueOf(param.get("description")))); } // 是否必填 by liumingyu request.setIsRequired(0); if (param.get("required") != null) { Boolean required = (Boolean) param.get("required"); if (required == true) { request.setIsRequired(1); } } requestList.add(request); } } return requestList; } /** * @param responsesList * @param definitionMap * @return java.util.List<net.evecom.scplatform.openapi.entity.ResponseStatus> * @author Torres Liu * @description //TODO 處理返回狀態碼CodeList(像200、40四、401...) * @date 2020/4/24 5:56 下午 **/ private List<ResponseStatus> processResponseStatusList(Map<String, Object> responsesList, Map<String, Map<String, Object>> definitionMap) { List<ResponseStatus> responseStatusList = new ArrayList<>(); Iterator<Map.Entry<String, Object>> resIt = responsesList.entrySet().iterator(); while (resIt.hasNext()) { Map.Entry<String, Object> entry = resIt.next(); //聲明個響應狀態碼實體 ResponseStatus responseStatus = new ResponseStatus(); //開始迭代 狀態碼200 201 401 403 404 等等 by liumingyu responseStatus.setStatusCode(entry.getKey()); //獲取response的value 像---> {description: "OK", schema: {$ref: "#/definitions/CommonResp«string»"}} LinkedHashMap<String, Object> statusCodeInfo = (LinkedHashMap) entry.getValue(); //setDescription responseStatus.setStatusDesc(String.valueOf(statusCodeInfo.get("description"))); if ("200".equals(entry.getKey())) { Object schema = statusCodeInfo.get("schema"); if (schema != null && ((LinkedHashMap) schema).get("$ref") != null) { //定義一個存儲definition的map Map<String, Object> myHashMap = new HashMap<>(2000); Map<String, Object> myHashMap2 = new HashMap<>(2000); //若是schema不爲null,開始解析$ref ---> $ref: "#/definitions/CommonResp«string»" Object ref = ((LinkedHashMap) schema).get("$ref"); //將取到的ref的值放入definitionMap做爲key去查詢該definitions的具體內容 Map<String, Object> mapByRef1 = definitionMap.get(ref); //獲取到該definitions中的properties字段內容(裏面是code、data、msg) Map<String, Object> properties = (Map<String, Object>) mapByRef1.get("properties"); //將properties拿來迭代,繼續後續邏輯... Iterator<Map.Entry<String, Object>> itProperties = properties.entrySet().iterator(); while (itProperties.hasNext()) { //拿到entry對象,其中entryProp的key 是 code、data、msg Map.Entry<String, Object> entryProp = itProperties.next(); //取到entryProp的value Map<String, Object> valueMap = (Map<String, Object>) entryProp.getValue(); //其中若是是data,那可能裏面還存在$ref if (valueMap.get("$ref") != null || valueMap.get("items") != null) { //若是存在 繼續取出$ref的值 ---> 如 #/definitions/PageInfo«ScFile對象» Object refValue = valueMap.get("$ref"); Map<String, Object> thisItems = (Map<String, Object>) valueMap.get("items"); Object refValues = (refValue != null) ? refValue : thisItems.get("$ref"); //繼續將refValue做爲key經過definitionMap來獲取definitions Map<String, Object> mapByRefValue = definitionMap.get(refValues); if (mapByRefValue != null) { //繼續獲取該definitions中的properties的值 Map<String, Object> propertiesMap = (Map<String, Object>) mapByRefValue.get("properties"); if (propertiesMap != null) { //將properties中的值進行迭代 Iterator<Map.Entry<String, Object>> itProp = propertiesMap.entrySet().iterator(); while (itProp.hasNext()) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dataFormat = simpleDateFormat.format(new Date()); //取到單個值 ----> 如 endRow: {type: "integer", format: "int32"} Map.Entry<String, Object> entryIt = itProp.next(); // entryIt.getKey()= endRow ; entryIt.getValue() = {type: "integer", format: "int32"} Map<String, Object> itValue = (Map<String, Object>) entryIt.getValue(); String type = (String) itValue.get("type"); if (!StringUtils.isBlank(type)) { switch (type) { case "string": if (itValue.get(FORMAT_VAL) != null && !"".equals(itValue.get(FORMAT_VAL))) { String format = (String) itValue.get("format"); if ("date-time".equals(format) || "dateTime".equals(format)) { myHashMap2.put(entryIt.getKey(), dataFormat); } } else { myHashMap2.put(entryIt.getKey(), "string"); } break; case "integer": myHashMap2.put(entryIt.getKey(), 0); break; case "number": myHashMap2.put(entryIt.getKey(), 0.0); break; case "boolean": myHashMap2.put(entryIt.getKey(), true); break; case "array": Integer initNum = 0; //開始調用--->遞歸算法邏輯 ifArrayRecursion(itValue, definitionMap, dataFormat, myHashMap2, entryIt, initNum); break; default: myHashMap2.put(entryIt.getKey(), null); break; } } } } } //將myHashMap2存入data myHashMap.put(entryProp.getKey(), myHashMap2); } else { //不存在ref的直接存入map中 if (valueMap.get("type") != null) { //拿到type的值 String type = (String) valueMap.get("type"); switch (type) { case "string": myHashMap.put(entryProp.getKey(), "string"); break; case "integer": myHashMap.put(entryProp.getKey(), 0); break; case "number": myHashMap.put(entryProp.getKey(), 0.0); break; case "boolean": myHashMap.put(entryProp.getKey(), true); break; default: myHashMap.put(entryProp.getKey(), new Object()); break; } } } } responseStatus.setStatusRemark(JSON.toJSONString(myHashMap)); } } responseStatusList.add(responseStatus); } return responseStatusList; } /** * @return net.evecom.scplatform.openapi.entity.SwaggerModelAttr * @Author liumingyu * @Description //TODO 處理返回屬性列表 * @Date 2020/4/8 6:56 下午 * @Param [responseObj, definitinMap] **/ private SwaggerModelAttr processResponseModelAttrs(Map<String, Object> responseObj, Map<String, SwaggerModelAttr> definitinMap) { Map<String, Object> schema = (Map<String, Object>) responseObj.get("schema"); String type = (String) schema.get("type"); String ref = null; //數組 by liumingyu if (ARRAY_VAL.equals(type)) { Map<String, Object> items = (Map<String, Object>) schema.get("items"); if (items != null && items.get(REF_VAL) != null) { ref = (String) items.get(REF_VAL); } } //對象 by liumingyu if (schema.get(REF_VAL) != null) { ref = (String) schema.get(REF_VAL); } //其餘類型 by liumingyu SwaggerModelAttr modelAttr = new SwaggerModelAttr(); modelAttr.setType(StringUtils.defaultIfBlank(type, StringUtils.EMPTY)); if (StringUtils.isNotBlank(ref) && definitinMap.get(ref) != null) { modelAttr = definitinMap.get(ref); } return modelAttr; } /** * @param itValue * @param definitionMap * @param dataFormat * @param myHashMapPre * @param entryPreIt * @param initNums * @return void * @author Torres Liu * @description //TODO ifArray遞歸算法 [若是參數存在type=array,開始執行該遞歸邏輯,該遞歸是爲了解析json中多層嵌套array的數據] * @date 2020/4/24 5:56 下午 **/ private void ifArrayRecursion(Map<String, Object> itValue, Map<String, Map<String, Object>> definitionMap, String dataFormat, Map<String, Object> myHashMapPre, Map.Entry<String, Object> entryPreIt, Integer initNums) { if (initNums < RECURSION_NUMS) { Map<String, Object> newHashMap = new HashMap<>(128); ArrayList<Map<String, Object>> newArrayListMap1 = new ArrayList<>(); ArrayList newArrayListMap2 = new ArrayList(); //若是爲array類型,說明可能還嵌套一層的數據 Map<String, Object> items = (Map<String, Object>) itValue.get("items"); if (items.get(REF_VAL) != null || itValue.get(REF_VAL) != null) { //獲取到items中$ref的值 String itemsRef = (String) items.get("$ref"); Object itemsRefs; itemsRefs = (itemsRef != null) ? itemsRef : itValue.get(REF_VAL); //經過definitionMap獲取到itemsRef對應的definitions Map<String, Object> itemsRefMap = definitionMap.get(itemsRefs); //繼續獲取properties中的數據 Map<String, Object> itemsPropertiesMap = (Map<String, Object>) itemsRefMap.get("properties"); //聲明迭代器 if (itemsPropertiesMap != null) { Iterator<Map.Entry<String, Object>> itemsIterator = itemsPropertiesMap.entrySet().iterator(); while (itemsIterator.hasNext()) { //拿到具體對象 Map.Entry<String, Object> itemsIt = itemsIterator.next(); Map<String, Object> itemsItValue = (Map<String, Object>) itemsIt.getValue(); //取到type來爲後續類型作判斷 String itemsType = (String) itemsItValue.get("type"); if (!StringUtils.isBlank(itemsType)) { switch (itemsType) { case "string": if (itemsItValue.get("format") != null && !"".equals(itemsItValue.get("format"))) { String itemsFormat = (String) itemsItValue.get("format"); if ("date-time".equals(itemsFormat) || "dateTime".equals(itemsFormat)) { newHashMap.put(itemsIt.getKey(), dataFormat); } } else { newHashMap.put(itemsIt.getKey(), "string"); } break; case "integer": newHashMap.put(itemsIt.getKey(), 0); break; case "number": newHashMap.put(itemsIt.getKey(), 0.0); break; case "boolean": newHashMap.put(itemsIt.getKey(), true); break; case "array": Integer nums = initNums + 1; ifArrayRecursion(itemsItValue, definitionMap, dataFormat, newHashMap, itemsIt, nums); default: newHashMap.put(itemsIt.getKey(), new Object()); break; } } } } newArrayListMap1.add(newHashMap); myHashMapPre.put(entryPreIt.getKey(), newArrayListMap1); } else { //沒有ref的也要去解析array String typeArray = (String) items.get("type"); switch (typeArray) { case "string": newArrayListMap2.add("string"); break; case "integer": newArrayListMap2.add(0); break; case "number": newArrayListMap2.add(0.0); break; case "boolean": newArrayListMap2.add(true); break; default: newArrayListMap2.add(new Object()); break; } myHashMapPre.put(entryPreIt.getKey(), newArrayListMap2); } } else { log.info("當前對象遞歸次數超過199次!!!"); System.out.println("當前對象遞歸次數超過199次!!!"); } } /** * 判斷是否爲有效url * * @param urlStr * @return boolean * @author Torres Liu * @description //TODO 判斷是否爲有效url * @date 2020/4/29 5:08 下午 **/ private boolean ifUrlValidity(String urlStr) { URL url; HttpURLConnection con; int state = -1; try { url = new URL(urlStr); con = (HttpURLConnection) url.openConnection(); state = con.getResponseCode(); if (state != 200) { return false; } } catch (Exception e1) { return false; } return true; } /** * 判斷是否爲swaggerUrl * * @param urlStr * @return boolean * @author Torres Liu * @description //TODO 判斷是否爲swaggerUrl * @date 2020/4/29 5:09 下午 **/ private boolean ifSwaggerUrl(String urlStr) { boolean contains = urlStr.contains("api-docs"); return contains; } /** * 判斷字符串是否爲json格式 * * @param jsonStr * @return boolean * @author Torres Liu * @description //TODO 判斷字符串是否爲json格式 * @date 2020/4/29 5:09 下午 **/ private boolean isJson(String jsonStr) { try { JSONObject jsonObject = new JSONObject(jsonStr); if (jsonObject.toString() == null) { return false; } return true; } catch (Exception e) { return false; } } }
/** * @program: share-capacity-platform * @description: 導入服務 * @author: Torres Liu * @date: 2020-04-14 10:33 **/ @RestController @RequestMapping("/swaggerJsonImport") public class SwaggerJsonImportController { @Autowired private SwaggerJsonImportService swaggerJsonImportService; /** * swaggerUrl 或 swaggerJson導入服務 * * @param url jsonUrl * @param isAuthorized 是否須要受權 * @param serviceSwagger swaggerJson * @return net.evecom.scplatform.common.entry.CommonResp<java.lang.String> * @author Torres Liu * @description //TODO swaggerUrl 或 swaggerJson導入服務 * @date 2020/4/28 5:52 下午 **/ @PostMapping("/importService") public CommonResp<String> swaggerImport(@RequestParam(value = "url", required = false) String url, @RequestParam(value = "isAuthorized") String isAuthorized, @RequestBody(required = false) ServiceSwagger serviceSwagger) throws IOException { CommonResp<String> responseString = swaggerJsonImportService.swaggerJsonImport(url, serviceSwagger, isAuthorized); return responseString; } /** * 導出Json功能 * * @param serviceId 服務id * @param catalogId 目錄id * @return java.util.List<net.evecom.scplatform.openapi.entity.dto.SwaggerHtmlDto> * @author Torres Liu * @description //TODO 導出Json功能 * @date 2020/4/28 5:53 下午 **/ @GetMapping("/swaggerJsonExport") public List<SwaggerHtmlDto> swaggerJsonExport(@RequestParam("serviceId") String serviceId, @RequestParam(value = "catalogId", required = false) String catalogId) { List<SwaggerHtmlDto> swaggerHtmlDtoList = swaggerJsonImportService.swaggerJsonExport(serviceId, catalogId); return swaggerHtmlDtoList; } }
/** * @program: share-capacity-platform * @description: javabean轉swagger html詳情頁 * @author: Torres Liu * @date: 2020-04-14 22:21 **/ @Controller @RequestMapping("/beanToSwaggerHtml") public class BeanToSwaggerHtmlController { @Autowired private RestTemplate restTemplate; @Autowired private SwaggerToHtmlByBeanServiceImpl swaggerToHtmlByBeanService; @Value("${spring.application.name}") private String appName; @Value("${server.port}") private String port; /** * word方式標識 **/ private String word = "word"; /** * excel方式標識 **/ private String excel = "excel"; /** * @return java.lang.String * @Author Torres Liu * @Description //TODO bean轉api風格的html * @Date 2020/4/15 12:49 上午 * @Param [model, serviceId, catalogId] **/ @GetMapping("/beanToHtml") public String getBeanToHtml(Model model, @RequestParam("serviceId") String serviceId, @RequestParam(value = "catalogId", required = false) String catalogId, @RequestParam(value = "download", required = false, defaultValue = "1") Integer download) throws SocketException, UnknownHostException { Map<String, Object> result = swaggerToHtmlByBeanService.getBeanToHtml(serviceId, catalogId); model.addAllAttributes(result); model.addAttribute("download", download); model.addAttribute("serviceId", serviceId); model.addAttribute("catalogId", catalogId); //獲取當前IP String ipAddr = WebToolUtils.getLocalIp(); model.addAttribute("ipAndPort", "http://192.168.66.40:50092/" + appName); System.out.println("[IP] =====> "+ ipAddr); return "beanToHtmlTemplate"; } /** * @return void * @Author Torres Liu * @Description //TODO 將html導出word和excel * @Date 2020/4/15 11:21 上午 * @Param [serviceId, outputType, catalogId, response] **/ @RequestMapping("/downloadWordByBean") public void downloadWord(@RequestParam("serviceId") String serviceId, @RequestParam("outputType") String outputType, @RequestParam("catalogId") String catalogId, HttpServletResponse response) { ResponseEntity<String> forEntity = restTemplate.getForEntity("http://" + appName + ":" + "/beanToSwaggerHtml/beanToHtml?download=0&serviceId=" + serviceId + "&catalogId=" + catalogId, String.class); response.setContentType("application/octet-stream;charset=utf-8"); response.setCharacterEncoding("utf-8"); try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) { if (word.equals(outputType)) { response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("WordApi_" + System.currentTimeMillis() + ".doc", "utf-8")); } else if (excel.equals(outputType)) { response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("ExcelApi_" + System.currentTimeMillis() + ".xlsx", "utf-8")); } byte[] bytes = forEntity.getBody().getBytes("utf-8"); bos.write(bytes, 0, bytes.length); bos.flush(); } catch (IOException e) { e.printStackTrace(); } } }
public interface SwaggerBeanToHtmlService { /** * @param serviceId * @param catalogId * @return java.util.Map<java.lang.String, java.lang.Object> * @Author Torres Liu * @Description //TODO 經過serviceId獲取相應javabean轉爲html * @Date 2020/4/14 4:33 下午 **/ Map<String, Object> getBeanToHtml(String serviceId, String catalogId); }
/** * @Author Torres Liu * @Description //TODO swagger-json轉html和word格式具體實現 (解析swagger-json) * @Date 2020/4/8 3:52 下午 * @Param * @return **/ @SuppressWarnings({"unchecked", "rawtypes"}) @Slf4j @Service public class SwaggerToHtmlByBeanServiceImpl implements SwaggerBeanToHtmlService { @Autowired private ServiceResourceDao serviceResourceDao; @Autowired private ServiceRequestDao serviceRequestDao; @Autowired private ServiceResponseDao serviceResponseDao; @Autowired private ResponseStatusDao responseStatusDao; @Autowired private ServiceCatalogDao serviceCatalogDao; /** * 頂級目錄的pid */ private static final String MAX_CATALOG_PID = "-1"; /** * @param serviceId * @param catalogId * @return java.util.Map<java.lang.String, java.lang.Object> * @author Torres Liu * @description //TODO 解析===>經過serviceId獲取相應javabean轉爲html * @date 2020/4/24 6:01 下午 **/ @Override public Map<String, Object> getBeanToHtml(String serviceId, String catalogId) { //String jsonStr = ""; Map<String, Object> resultMap = new HashMap<>(50); List<SwaggerHtmlDto> result = new ArrayList<>(); try { if (serviceId != null && !"".equals(serviceId)) { SwaggerHtmlDto thisDto = new SwaggerHtmlDto(); //根據serviceId查詢所需數據 ServiceResource resourceTable = serviceResourceDao.findById(serviceId); List<ServiceRequest> requestList = serviceRequestDao.findByServiceId(serviceId); List<ResponseStatus> responseStatusList = responseStatusDao.findByServiceId(serviceId); List<ServiceResponse> serviceResponseList = serviceResponseDao.findByServiceId(serviceId); ServiceCatalog thisCatalogBean = serviceCatalogDao.findById(catalogId == null ? "" : catalogId); //將數據set到自定義封裝的dto實體中 thisDto.setServiceResource(resourceTable); thisDto.setRequestList(requestList); thisDto.setResponseStatusList(responseStatusList); thisDto.setResponseList(serviceResponseList); if (thisCatalogBean != null) { thisDto.setTag(thisCatalogBean.getCatalogName()); String thisCatalogPid = thisCatalogBean.getPid(); if (!MAX_CATALOG_PID.equals(thisCatalogPid)) { ServiceCatalog pidBean = serviceCatalogDao.findById(thisCatalogPid); if (pidBean != null) { thisDto.setTitle(pidBean.getCatalogName()); } } else { thisDto.setTitle(thisCatalogBean.getCatalogName()); } } thisDto.setVersion(resourceTable.getServiceVersion()); //將全部數據add至result result.add(thisDto); Map<String, List<SwaggerHtmlDto>> tableMap = new HashMap<>(50); if (catalogId != null && thisCatalogBean != null) { tableMap = result.stream().parallel().collect(Collectors.groupingBy(SwaggerHtmlDto::getTitle)); } else { tableMap = result.stream().parallel().collect(Collectors.groupingBy(SwaggerHtmlDto::getVersion)); } resultMap.put("tableMap", new TreeMap<>(tableMap)); } } catch (Exception e) { log.error("Javabean Convert Swagger Json Error", e); } return resultMap; } }
/** * @Author Torres Liu * @Description //TODO Swagger格式解析Json工具類 * @Date 2020/4/8 4:32 下午 * @Param * @return **/ public class SwaggerJsonUtils { private static ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); } public static <T> T readValue(String jsonStr, Class<T> clazz) throws IOException { return objectMapper.readValue(jsonStr, clazz); } public static <T> List<T> readListValue(String jsonStr, Class<T> clazz) throws IOException { JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, clazz); return objectMapper.readValue(jsonStr, javaType); } public static ArrayNode readArray(String jsonStr) throws IOException { JsonNode node = objectMapper.readTree(jsonStr); if (node.isArray()) { return (ArrayNode) node; } return null; } public static JsonNode readNode(String jsonStr) throws IOException { return objectMapper.readTree(jsonStr); } public static String writeJsonStr(Object obj) throws JsonProcessingException { return objectMapper.writeValueAsString(obj); } public static ObjectNode createObjectNode() { return objectMapper.createObjectNode(); } public static ArrayNode createArrayNode() { return objectMapper.createArrayNode(); } }
package xxxxxxxx import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.*; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class WebToolUtils { /** * UNKNOWN */ private final static String UNKNOWN = "unknown"; /** * 獲取本地IP地址 * * @throws SocketException */ public static String getLocalIp() throws UnknownHostException, SocketException { if (isWindowsOs()) { return InetAddress.getLocalHost().getHostAddress(); } else { return getLinuxLocalIp(); } } /** * 判斷操做系統是不是Windows * * @return */ public static boolean isWindowsOs() { String windowsSys = "windows"; boolean isWindowsOs = false; String osName = System.getProperty("os.name"); if (osName.toLowerCase().indexOf(windowsSys) > -1) { isWindowsOs = true; } return isWindowsOs; } /** * 獲取本地Host名稱 */ public static String getLocalHostName() throws UnknownHostException { return InetAddress.getLocalHost().getHostName(); } /** * 獲取Linux下的IP地址 * * @return IP地址 * @throws SocketException */ private static String getLinuxLocalIp() throws SocketException { String ip = ""; try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); String name = intf.getName(); if (!name.contains("docker") && !name.contains("lo")) { for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { String ipaddress = inetAddress.getHostAddress().toString(); if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) { ip = ipaddress; System.out.println(ipaddress); } } } } } } catch (SocketException ex) { System.out.println("獲取ip地址異常"); ip = "127.0.0.1"; ex.printStackTrace(); } System.out.println("IP:" + ip); return ip; } /** * 獲取用戶真實IP地址,不使用request.getRemoteAddr();的緣由是有可能用戶使用了代理軟件方式避免真實IP地址, * <p> * 但是,若是經過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP值,究竟哪一個纔是真正的用戶端的真實IP呢? * 答案是取X-Forwarded-For中第一個非unknown的有效IP字符串。 * <p> * 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, * 192.168.1.100 * <p> * 用戶真實IP爲: 192.168.1.110 * * @param request * @return */ public static String getIpAddress(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } /** * 向指定URL發送GET方法的請求 * * @param url 發送請求的URL * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return URL 所表明遠程資源的響應結果 */ public static String sendGet(String url, String param) { StringBuffer result = new StringBuffer(); BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打開和URL之間的鏈接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 創建實際的鏈接 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result.toString(); } /** * 向指定 URL 發送POST方法的請求 * @param pathUrl * @param name * @param pwd * @param phone * @param content */ public static void sendPost(String pathUrl, String name, String pwd, String phone, String content) { try { // 創建鏈接 URL url = new URL(pathUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); // //設置鏈接屬性 // 使用 URL 鏈接進行輸出 httpConn.setDoOutput(true); // 使用 URL 鏈接進行輸入 httpConn.setDoInput(true); // 忽略緩存 httpConn.setUseCaches(false); // 設置URL請求方法 httpConn.setRequestMethod("POST"); String requestString = "客服端要以以流方式發送到服務端的數據..."; // 設置請求屬性 // 得到數據字節數據,請求數據流的編碼,必須和下面服務器端處理請求流的編碼一致 byte[] requestStringBytes = requestString.getBytes("utf-8"); httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length); httpConn.setRequestProperty("Content-Type", " application/x-www-form-urlencoded"); // 維持長鏈接 httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate"); httpConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0"); httpConn.setRequestProperty("Upgrade-Insecure-Requests", "1"); httpConn.setRequestProperty("account", name); httpConn.setRequestProperty("passwd", pwd); httpConn.setRequestProperty("phone", phone); httpConn.setRequestProperty("content", content); // 創建輸出流,並寫入數據 OutputStream outputStream = httpConn.getOutputStream(); outputStream.write(requestStringBytes); outputStream.close(); // 得到響應狀態 int responseCode = httpConn.getResponseCode(); // 鏈接成功 if (HttpURLConnection.HTTP_OK == responseCode) { // 當正確響應時處理數據 StringBuffer sb = new StringBuffer(); String readLine; BufferedReader responseReader; // 處理響應流,必須與服務器響應流輸出的編碼一致 responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } responseReader.close(); } } catch (Exception ex) { ex.printStackTrace(); } } /** * 執行一個HTTP POST請求,返回請求響應的HTML * @param url * @param name * @param pwd * @param phone * @param content */ public static void doPost(String url, String name, String pwd, String phone, String content) { // 建立默認的httpClient實例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 建立httppost HttpPost httppost = new HttpPost(url); // 建立參數隊列 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("account", name)); formparams.add(new BasicNameValuePair("passwd", pwd)); formparams.add(new BasicNameValuePair("phone", phone)); formparams.add(new BasicNameValuePair("content", content)); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉鏈接,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
以上即是後端解析的代碼(dao接口和mapper.xml的sql我這邊忽略了,能夠根據本身實際業務去寫),最後附上前端代碼:
前端這邊使用了thymeleaf模板引擎。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="application/msword"/> <div th:each="tableMap:${tableMap}"> <title th:each="table:${tableMap.value}" th:if="${table.title} != null" th:text="${table.title + '(1.0)詳情頁'}"></title> <title th:each="table:${tableMap.value}" th:if="${table.title} == null" th:text="${table.serviceResource.serviceName}"></title> </div> <style type="text/css"> .swaggerApi { border-radius: 15px; } .swaggerApi .bg { color: #000000; /*background-color: #69b869;*/ } .swaggerApi .trBgA { color: #000000; background-color: #d9edf7; } .swaggerApi .trBgA:hover { background-color: #d9edf7; } .swaggerApi .trBgB { color: #000000; background-color: #fcf8e3; } .swaggerApi .trBgB:hover { background-color: #fcf8e3; } .swaggerApi .titleTagA { color: #337ab7; background-color: #d9edf7; font-size: 18px; font-weight: 600; } .swaggerApi .titleTagB { color: #aa7408; background-color: #fcf8e3; font-size: 18px; font-weight: 600; } .swaggerApi .titleTagC { color: #5cb85c; background-color: #dff0d8; font-size: 18px; font-weight: 600; } .swaggerApi table { padding: 10px; border: 1px solid #dbe3e4; table-layout: fixed; color: #333333; background-color: #ffffff; } .swaggerApi tr { height: 36px; font-size: 16px; } .swaggerApi tr:hover{ background-color: #f5f5f5; } .swaggerApi td { padding: 8px; border: 1px solid #ddd; height: 36px; overflow: hidden; word-break: break-all; word-wrap: break-word; font-size: 16px; font-family: 宋體; } .swaggerApi .first_title { /*color: #eee;*/ height: 60px; line-height: 60px; margin: 0; font-weight: bold; font-size: 20px; font-family: 宋體; } .swaggerApi .second_title { /*color: #eee;*/ height: 40px; line-height: 40px; margin: 0; font-size: 16px; font-family: 宋體; } .swaggerApi .doc_title { color: #eee; font-size: 24px; text-align: center; font-weight: bold; border-bottom: 1px solid #eee; padding-bottom: 9px; margin: 34px 0 20px; font-family: 宋體; } .swaggerApi .download_btn_def { float: right; margin-left: 10px; display: inline-block; height: 38px; line-height: 38px; padding: 0 18px; background-color: #009688; color: #fff; white-space: nowrap; text-align: center; font-size: 14px; border: none; border-radius: 2px; cursor: pointer; } .swaggerApi .download_btn_def:hover { opacity: 0.8; } .swaggerApi .download_btn_blue { float: right; margin-left: 10px; display: inline-block; height: 38px; line-height: 38px; padding: 0 18px; background-color: #1E9FFF; color: #fff; white-space: nowrap; text-align: center; font-size: 14px; border: none; border-radius: 2px; cursor: pointer; } .swaggerApi .download_btn_blue:hover { opacity: 0.8; } .swaggerApi .alert { padding: 15px; margin-bottom: 5px; border: 1px solid transparent; border-radius: 4px; } .swaggerApi .alert-warning { color: #8a6d3b; background-color: #fcf8e3; border-color: #faebcc; } </style> </head> <body> <div class="swaggerApi" style="margin: 0 auto;padding:0 40px"> <div th:each="tableMap:${tableMap}"> <div th:each="table:${tableMap.value}"> <!-- <p class="doc_title" th:text="${tableMap.key+'('+ table.version +')'}"></p>--> <div class=" doc_title"> <div th:if="${table.title} != null" th:text="${table.title+'('+ table.version +')'}"></div> <div th:if="${table.title} == null" th:text="${table.serviceResource.serviceName} + '-詳情頁'"></div> </div> <!-- <a type="button" class="download_btn btn btn-danger glyphicon glyphicon-cloud-download" disabled="disabled" th:if="${download == 1}" href="#">下載(pdf)</a>--> <a type="button" class="download_btn_def" th:if="${download == 1}" th:href="${ipAndPort + '/beanToSwaggerHtml/downloadWordByBean?serviceId='+ serviceId +'&catalogId='+catalogId}+'&outputType=excel'">下載(excel)</a> <a type="button" class="download_btn_blue" th:if="${download == 1}" th:href="${ipAndPort + '/beanToSwaggerHtml/downloadWordByBean?serviceId='+ serviceId +'&catalogId='+catalogId}+'&outputType=word' ">下載(doc)</a> <br> </div> </div> <div th:each="tableMap:${tableMap}" style="margin-bottom:20px;margin-top: 40px"> <div th:each="table,tableStat:${tableMap.value}"> <div class="alert alert-warning"> <strong>提示:</strong><p>調用時需在請求頭添加憑證,格式以下</p> <strong>Request Headers:</strong> <p>Authorization : Basic Base64(ak:sk)</p> </div> <h4 class="first_title" th:if="${table.tag} != null" th:text="${table.tag}"></h4> <!--這個是每一個請求的說明,方便生成文檔後進行整理--> <br th:if="${tableStat.index != 0}"> <h5 class="second_title" th:text="${tableStat.count} + ')' + ${table.serviceResource.serviceName}"></h5> <table class="" border="1" cellspacing="0" cellpadding="0" width="100%"> <tr align="left"> <td class="titleTagC" colspan="5">ServiceInfo</td> </tr> <tbody class=""> <tr> <td width="25%">服務名稱</td> <td colspan="4" th:text="${table.serviceResource.serviceName}"></td> </tr> <tr> <td width="25%">服務描述</td> <td colspan="4" th:if="${table.serviceResource.serviceDesc} != '' " th:text="${table.serviceResource.serviceDesc} != 'null' ? ${table.serviceResource.serviceDesc} : '無'"></td> <td colspan="4" th:if="${table.serviceResource.serviceDesc} == '' " th:text="無"></td> </tr> <tr> <td>請求地址</td> <td colspan="4" th:text="${table.serviceResource.requestUrl}"></td> </tr> <tr> <td>請求方法</td> <td colspan="4" th:text="${table.serviceResource.requestMethod}"></td> </tr> <tr> <td>請求類型</td> <td colspan="4" th:if="${table.serviceResource.contentType} == '' " th:text="無"></td> <td colspan="4" th:if="${table.serviceResource.contentType} != '' " th:text="${table.serviceResource.contentType}"></td> </tr> <tr> <td>返回類型</td> <td colspan="4" th:if="${table.serviceResource.callContentType} == '' " th:text="無"></td> <td colspan="4" th:if="${table.serviceResource.callContentType} != '' " th:text="${table.serviceResource.callContentType}"></td> </tr> </tbody> <tr align="left"> <td class="titleTagA" colspan="5">Parameters</td> </tr> <tr class="trBgA" align="center"> <td>參數名稱</td> <td>參數類型</td> <td>參數來源</td> <td>是否必填</td> <td>說明</td> </tr> <tbody> <tr align="center" th:each="request:${table.requestList}"> <td th:text="${request.reqName}"></td> <td th:text="${request.reqType}"></td> <td th:text="${request.reqFrom}"></td> <td th:if="${request.isRequired} == 1" th:text="是"></td> <td th:if="${request.isRequired} == 0" th:text="否"></td> <td th:text="${request.reqDesc}"></td> </tr> </tbody> <tr align="left"> <td class="titleTagB" colspan="5">Responses</td> </tr> <tr class="trBgB" align="center"> <td>響應狀態碼</td> <td colspan="2">描述</td> <td colspan="2">返回說明</td> </tr> <tbody> <tr align="center" valign="middle !important" th:each="responseStatus:${table.responseStatusList}"> <td th:text="${responseStatus.statusCode}"></td> <td colspan="2" th:text="${responseStatus.statusDesc}"></td> <td colspan="2" th:if="${responseStatus.statusRemark} == null " th:text="無"></td> <td colspan="2" th:if="${responseStatus.statusRemark} != null " th:text="${responseStatus.statusRemark}"></td> </tr> <!-- </tbody>--> <!-- <tr class="bg tagHoverColor" align="center">--> <!-- <td>返回屬性名</td>--> <!-- <td colspan="2">類型</td>--> <!-- <td colspan="2">說明</td>--> <!-- </tr>--> <!-- <tbody>--> <!-- <tr align="center" th:each="response:${table.responseList}">--> <!-- <td th:text="${response.propName}"></td>--> <!-- <td colspan="2" th:text="${response.propType}"></td>--> <!-- <td colspan="2" th:text="${response.propDesc}"></td>--> <!-- </tr>--> <!-- </tbody>--> <!-- <tr>--> <!-- <td class="titleTagD" colspan="5">Example Value</td>--> <!-- </tr>--> <!-- <tr class="specialHeight">--> <!-- <td align="center">請求示例</td>--> <!-- <td colspan="4" ></td>--> <!-- </tr>--> <!-- <tr class="specialHeight">--> <!-- <td align="center">返回示例</td>--> <!-- <td colspan="4"></td>--> <!-- </tr>--> </table> </div> </div> </div> <script> /*<![CDATA[*/ /** * json美化 * jsonFormat2(json)這樣爲格式化代碼。 * jsonFormat2(json,true)爲開啓壓縮模式 * @param txt * @param compress * @returns {string} */ function jsonFormat(txt,compress){ debugger; txt = JSON.stringify(txt); //alert(txt); var indentChar = ' '; if(/^\s*$/.test(txt)){ alert('數據爲空,沒法格式化! '); return; } try{var data=eval('('+txt+')');} catch(e){ alert('數據源語法錯誤,格式化失敗! 錯誤信息: '+e.description,'err'); return; }; var draw=[],last=false,This=this,line=compress?'':'\n',nodeCount=0,maxDepth=0; var notify=function(name,value,isLast,indent/*縮進*/,formObj){ nodeCount++;/*節點計數*/ for (var i=0,tab='';i<indent;i++ )tab+=indentChar;/* 縮進HTML */ tab=compress?'':tab;/*壓縮模式忽略縮進*/ maxDepth=++indent;/*縮進遞增並記錄*/ if(value&&value.constructor==Array){/*處理數組*/ draw.push(tab+(formObj?('"'+name+'":'):'')+'['+line);/*縮進'[' 而後換行*/ for (var i=0;i<value.length;i++) notify(i,value[i],i==value.length-1,indent,false); draw.push(tab+']'+(isLast?line:(','+line)));/*縮進']'換行,若非尾元素則添加逗號*/ }else if(value&&typeof value=='object'){/*處理對象*/ draw.push(tab+(formObj?('"'+name+'":'):'')+'{'+line);/*縮進'{' 而後換行*/ var len=0,i=0; for(var key in value)len++; for(var key in value)notify(key,value[key],++i==len,indent,true); draw.push(tab+'}'+(isLast?line:(','+line)));/*縮進'}'換行,若非尾元素則添加逗號*/ }else{ if(typeof value=='string')value='"'+value+'"'; draw.push(tab+(formObj?('"'+name+'":'):'')+value+(isLast?'':',')+line); }; }; var isLast=true,indent=0; notify('',data,isLast,indent,false); var aaaa = darw; return draw.join(''); } /*]]>*/ </script> </body> </html>
首先經過swagger json解析爲實體類並存入數據庫中(對應上面的swagger解析代碼),在經過調用javabean轉html的接口來實現將存入的數據轉爲html頁面(對應上面的javabean轉爲html渲染頁面代碼)。
其實也能夠直接經過swagger json解析而後存入實體類直接渲染給頁面。就是不入庫直接將swaggerjson生成出html,這種方案我也實現了,可是在這篇文章中不作過多介紹,若是有須要之後我也會寫篇文章作一下記錄。
其實都是同樣的思路啦,寫代碼講究的是思路。
http://www.javashuo.com/article/p-rvhztith-gq.html
https://github.com/JMCuixy/swagger2word
https://www.aliyun.com/product/csb?spm=5176.10695662.784136.1.57b794ceX78G27