Index: forgon-tools/src/main/java/com/forgon/tools/util/PathUtils.java =================================================================== diff -u -r17002 -r17035 --- forgon-tools/src/main/java/com/forgon/tools/util/PathUtils.java (.../PathUtils.java) (revision 17002) +++ forgon-tools/src/main/java/com/forgon/tools/util/PathUtils.java (.../PathUtils.java) (revision 17035) @@ -3,9 +3,15 @@ */ package com.forgon.tools.util; +import java.io.IOException; +import java.net.URL; +import java.net.URLDecoder; +import java.util.Enumeration; + import javax.servlet.ServletContext; import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; import com.forgon.servlet.ForgonServletContextListener; @@ -14,11 +20,13 @@ * */ public class PathUtils { + private static Logger loger = Logger.getLogger(PathUtils.class); + public static String getWebAppRootPath() { ServletContext servletContext = ForgonServletContextListener .getServletContext(); // 下面的地址为持续集成服务器获取代码到本地后存放的地址 - String realPath = "D:/ForgonData/Jenkins_Home/workspace/FORGON 消毒追溯系统V4.1/ssts-web/src/main/webapp"; + String realPath = ""; /** * 项目部署到Tomcat容器时,能取到servletContext,用取到的值。否则用本地硬编码的值,便于本地运行测试用例。 @@ -28,7 +36,68 @@ realPath = servletContext.getRealPath(""); } + // 取不到Servlet容器,说明没部署到Tomcat,是在运行测试用例 + else{ + realPath = getWebProjectRoot(); + } return realPath; } + + /** + * 获取Web项目的webapp文件夹路径,根据项目的相对路径查找。用于测试用例运行时确定路径。 + * @return + */ + private static String getWebProjectRoot() { + String webAppRoot = ""; + + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + + if (loader == null) { + loader = PathUtils.class.getClassLoader(); + } + String path = PathUtils.class.getName().replace('.', '/') + ".class"; + + try { + Enumeration e = loader.getResources(path); + + if (!e.hasMoreElements()) { + loger.error(path + " file not found"); + try { + throw new Exception(path + " file not found"); + } catch (Exception e1) { + e1.printStackTrace(); + } + } else { + if (e.hasMoreElements()) { + URL myClassURL = (URL) e.nextElement(); + String myClassPath = URLDecoder.decode( + myClassURL.getPath(), "UTF-8"); + + int webInfPosistion = myClassPath + .lastIndexOf("/forgon-tools"); + + if (webInfPosistion > 0) { + webAppRoot = myClassPath.substring(0, webInfPosistion) + + "/ssts-web/src/main/webapp"; + } else { + loger.error("web项目的路径查找错误,请检查!"); + } + } + } + + } catch (IOException e2) { + e2.printStackTrace(); + } + + // 去掉路径中的"file:/"或者"/"前缀 + if (webAppRoot.startsWith("file:/")){ + webAppRoot = webAppRoot.substring("file:/".length()); + } + else if (webAppRoot.startsWith("/")){ + webAppRoot = webAppRoot.substring("/".length()); + } + + return webAppRoot; + } }