001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.support.swagger; 017 018import com.alibaba.fastjson.JSON; 019import com.alibaba.fastjson.serializer.SerializeConfig; 020import com.google.common.collect.Maps; 021import com.jfinal.ext.cors.EnableCORS; 022import io.jboot.Jboot; 023import io.jboot.web.controller.JbootController; 024import io.swagger.models.Swagger; 025import io.swagger.models.properties.RefProperty; 026 027/** 028 * @author Michael Yang 杨福海 (fuhai999@gmail.com) 029 * @version V1.0 030 */ 031public class JbootSwaggerController extends JbootController { 032 033 JbootSwaggerConfig config = Jboot.config(JbootSwaggerConfig.class); 034 035 public void index() { 036 String html; 037 try { 038 String viewPath = config.getPath().endsWith("/") ? config.getPath() : config.getPath() + "/"; 039 html = renderToString(viewPath + "index.html", Maps.newHashMap()); 040 } catch (Exception ex) { 041 renderHtml("error,please put <a href=\"https://github.com/swagger-api/swagger-ui\" target=\"_blank\">swagger-ui</a> " + 042 "into your project path : " + config.getPath() + " <br />" + 043 "or click <a href=\"" + config.getPath() + "/json\">here</a> show swagger json."); 044 return; 045 } 046 047 String basePath = getRequest().getRequestURL().toString(); 048 String jsonUrl = basePath.endsWith("/") ? basePath + "json" : basePath + "/json"; 049 050 html = html.replace("http://petstore.swagger.io/v2/swagger.json", jsonUrl); 051 // 可能是 https ,看下载的 swagger 版本 052 html = html.replace("https://petstore.swagger.io/v2/swagger.json", jsonUrl); 053 html = html.replace("src=\"./", "src=\"" + basePath); 054 html = html.replace("href=\"./", "href=\"" + basePath); 055 056 renderHtml(html); 057 } 058 059 /** 060 * 渲染json 061 * 参考:http://petstore.swagger.io/ 及json信息 http://petstore.swagger.io/v2/swagger.json 062 */ 063 @EnableCORS 064 public void json() { 065 Swagger swagger = JbootSwaggerManager.me().getSwagger(); 066 if (swagger == null) { 067 renderText("swagger config error."); 068 return; 069 } 070 071 // 适配swaggerUI, 解决页面"Unknown Type : ref"问题。 072 SerializeConfig serializeConfig = new SerializeConfig(); 073 serializeConfig.put(RefProperty.class, new RefPropertySerializer()); 074 renderJson(JSON.toJSONString(swagger, serializeConfig)); 075 } 076 077}