SpringMVC 攔截 controller並解析接口平臺

@Controller
@RequestMapping(value = "/document")
public class DocumentController{
    
    private static Pattern CHANGE_LOG_PATTERN = Pattern.compile("(\\d(.\\d+)+)(\\|(.*))?");
    
    //配置文件中配置注入包名的值,
    @Value("${onlinedoc.scan.package}")
    String packageName;
    
    //攔截/document/data請求,並處理
    @RequestMapping(value = "/data", method = RequestMethod.GET)
    @ResponseBody
    public Map<String ,Object> getInterface(HttpServletRequest req) throws Exception{
         /**
         *獲取要處理的controller類所在的文件夾的class以前的部分
         *例如"/E:/eclipsePage/workspace_/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/w         *tpwebapps/nowglobal-app-jobnow-appgateway/WEB-INF/classes/"
         */
         String path = this.getClass().getClassLoader().getResource("").getPath();
         
         /**
         *獲取要處理的controler所在的包名全路徑
         *例如:/E:/eclipsePage/workspace_/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/w         *tpwebapps/nowglobal-app-jobnow-appgateway/WEB-INF/classes/com\nowglobal\app\jobnow\ap         *pgateway\web\controller\
         */
         String filePath = path + packageName.replace(".", File.separator);
         
         //獲取包路徑下面全部controller類的類全路徑名稱
             List<String> classNames = FindPackageClass.getClassName(filePath);
         
         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
         Collections.sort(classNames);
         
         //循環遍歷classNames,獲取方法上的註解等信息
         for (String name : classNames) {
             Map<String, Object> clazzMap = new HashMap<String, Object>();
             String className = name.substring(name.lastIndexOf(".") + 1);
             clazzMap.put("className", className);
             Class<?> clazz;
             
             try {
                 clazz = Class.forName(name);
             } catch (ClassNotFoundException e) {
                 logger.error("找不到指定的類:" + name, e);
                 throw new Exception(e);
             }
             
             RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
             if (requestMapping == null) {
                 logger.warn(clazz.getName() + " has no @RequestMapping");
                 continue;
             }
             
             //獲取類上面全部的方法
             Method[] methods = clazz.getMethods();
             List<Map<String, String>> methodList = new ArrayList<Map<String, String>>();
             
             //遍歷類上的方法methods 
             for (Method method : methods) {
                 Description description = method.getAnnotation(Description.class);
                 ChangeLog changeLog = method.getAnnotation(ChangeLog.class);
                 String version = "";
                 if (changeLog != null) {
                	List<String> versions = new ArrayList<String>();
                	String[] values = changeLog.value();
                	if (values != null && values.length > 0) {
                		for (String v : values) {
                			Matcher m = CHANGE_LOG_PATTERN.matcher(v);
                			if (m.matches()) {
                				versions.add(m.group(1));
                			}
                		}
                	}
                	if (CollectionUtils.isNotEmpty(versions)) {
	                    Collections.sort(versions);
	                    version = versions.get(versions.size() - 1);
                	}
                   }

               
                  RequestMapping mapping = method.getAnnotation(RequestMapping.class);
                  if (description != null && mapping != null) {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("route", requestMapping.value()[0] + mapping.value()[0]);
                        map.put("method", method.getName());
                        map.put("name", description.value());
                        map.put("description", description.description());
                        map.put("author", description.author());
                        map.put("flag", description.flag().name());
                        map.put("version", version);
                        methodList.add(map);
                   }
             }
             
             
            Collections.sort(methodList, new Comparator<Map<String, String>>() {
		@Override
		public int compare(Map<String, String> o1,Map<String, String> o2) {
			int comp = o2.get("version").compareTo(o1.get("version"));
			return comp!=0?comp:o1.get("route").compareTo(o2.get("route"));
		}
            });
            clazzMap.put("methodList", methodList);
            list.add(clazzMap);
         }
         
         //請求訪問的路徑
         String requestPath = req.getRequestURL().toString();
         
         //對路徑進行處理
         requestPath = requestPath.substring(0, requestPath.indexOf("api") + 3);
         
         Map<String ,Object> data = new HashMap<>();
        data.put("path", requestPath);
        data.put("list", list);
        return data;
    }
}



public class FindPackageClass {
    public static List<String> getClassName(String filePath) {
        List<String> fileNames = getClassName(filePath, null);
        return fileNames;
    }

    public static List<String> getClassName(String filePath, List<String> className) {
        List<String> myClassName = new ArrayList<String>();
        File file = new File(filePath);
        File[] childFiles = file.listFiles();
        for (File childFile : childFiles) {
            if (childFile.isDirectory()) {
                myClassName.addAll(getClassName(childFile.getPath(), myClassName));
            } else {
                String childFilePath = childFile.getPath();
                childFilePath = childFilePath.substring(childFilePath.indexOf(File.separator + "classes") + 9, childFilePath.lastIndexOf("."));
                childFilePath = childFilePath.replace(File.separator, ".");
                myClassName.add(childFilePath);
            }
        }

        return myClassName;
    }
}
相關文章
相關標籤/搜索