Merge remote-tracking branch 'zhb/master'

This commit is contained in:
zhouhaibin
2012-08-12 22:29:02 +08:00
20 changed files with 950 additions and 221 deletions
@@ -234,7 +234,7 @@ public class DruidDataSourceStatManager implements DruidDataSourceStatManagerMBe
public CompositeDataSupport getCompositeData(Object dataSource) throws JMException {
CompositeType rowType = getDruidDataSourceCompositeType();
Map<String, Object> map = DruidDataSourceUtils.getStatData(dataSource);
Map<String, Object> map = DruidDataSourceUtils.getStatDataForMBean(dataSource);
return new CompositeDataSupport(rowType, map);
}
@@ -176,7 +176,7 @@ public class JSONDruidStatService {
Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
dataMap.put("ResultCode", resultCode);
dataMap.put("Content", content);
return JSON.toJSONString(dataMap);
return JSON.toJSONStringWithDateFormat(dataMap, "yyyy-MM-dd hh:mm:ss");
}
}
@@ -1,6 +1,9 @@
package com.alibaba.druid.support.http;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@@ -18,14 +21,29 @@ import com.alibaba.druid.support.http.stat.WebAppStatManager;
import com.alibaba.druid.support.http.stat.WebRequestStat;
import com.alibaba.druid.support.http.stat.WebSessionStat;
import com.alibaba.druid.support.http.stat.WebURIStat;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.druid.util.DruidWebUtils;
import com.alibaba.druid.util.PatternMatcher;
import com.alibaba.druid.util.ServletPathMatcher;
public class WebStatFilter implements Filter {
private final static Log LOG = LogFactory.getLog(WebStatFilter.class);
private WebAppStat webAppStat = null;
private WebStatFilterContextListener statFilterContextListener = new WebStatFilterContextListener();
/**
* PatternMatcher used in determining which paths to react to for a given request.
*/
protected PatternMatcher pathMatcher = new ServletPathMatcher();
private final String EXCLUSIONS = "exclusions";
private Set<String> excludesPattern;
private boolean createSession = false;
private String contextPath;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
@@ -39,6 +57,7 @@ public class WebStatFilter implements Filter {
}
long startNano = System.nanoTime();
long startMillis = System.currentTimeMillis();
WebRequestStat requestStat = new WebRequestStat(startNano);
WebRequestStat.set(requestStat);
@@ -48,6 +67,7 @@ public class WebStatFilter implements Filter {
// 第一次访问时,sessionId为null,如果缺省sessionCreate=false,sessionStat就为null。
if (sessionStat != null) {
sessionStat.beforeInvoke();
sessionStat.setLastAccessTimeMillis(startMillis);
}
try {
@@ -64,6 +84,7 @@ public class WebStatFilter implements Filter {
} else {
sessionStat = getSessionStat(httpRequest);
if (sessionStat != null) {
sessionStat.setLastAccessTimeMillis(startMillis);
sessionStat.reacord(nanoSpan);
}
}
@@ -72,13 +93,35 @@ public class WebStatFilter implements Filter {
}
}
public WebSessionStat getSessionStat(HttpServletRequest httpRequest) {
public WebSessionStat getSessionStat(HttpServletRequest request) {
WebSessionStat sessionStat = null;
String sessionId = getSessionId(httpRequest);
String sessionId = getSessionId(request);
if (sessionId != null) {
sessionStat = webAppStat.getSessionStat(sessionId);
}
if (sessionStat != null) {
if (sessionStat.getCreateTimeMillis() == -1L) {
HttpSession session = request.getSession(false);
if (session != null) {
sessionStat.setCreateTimeMillis(session.getCreationTime());
} else {
sessionStat.setCreateTimeMillis(System.currentTimeMillis());
}
}
String ip = DruidWebUtils.getRemoteAddr(request);
int addressCount = sessionStat.getRemoteAddresses().size();
if (addressCount < 10) {
sessionStat.addRemoteAddress(ip);
} else {
if (!sessionStat.getRemoteAddress().contains(ip)) {
LOG.error("sessoin ip change too many");
}
}
}
return sessionStat;
}
@@ -93,7 +136,24 @@ public class WebStatFilter implements Filter {
return sessionId;
}
public boolean isExclusion(String uri) {
public boolean isExclusion(String requestURI) {
if (excludesPattern == null) {
return false;
}
if (contextPath != null && requestURI.startsWith(contextPath)) {
requestURI = requestURI.substring(contextPath.length());
if(!requestURI.startsWith("/")) {
requestURI = "/" + requestURI;
}
}
for (String pattern : excludesPattern) {
if (pathMatcher.matches(pattern, requestURI)) {
return true;
}
}
return false;
}
@@ -103,11 +163,16 @@ public class WebStatFilter implements Filter {
@Override
public void init(FilterConfig config) throws ServletException {
String exclusions = config.getInitParameter(EXCLUSIONS);
if (exclusions != null && exclusions.trim().length() != 0) {
excludesPattern = new HashSet<String>(Arrays.asList(exclusions.split("\\s*,\\s*")));
}
config.getServletContext().getContextPath();
StatFilterContext.getInstance().addContextListener(statFilterContextListener);
webAppStat = new WebAppStat();
this.contextPath = DruidWebUtils.getContextPath(config.getServletContext());
webAppStat = new WebAppStat(contextPath);
WebAppStatManager.getInstance().addWebAppStatSet(webAppStat);
}
@@ -174,6 +239,10 @@ public class WebStatFilter implements Filter {
@Override
public void executeAfter(String sql, long nanoSpan, Throwable error) {
WebRequestStat localStat = WebRequestStat.current();
if (localStat != null) {
localStat.addJdbcExecuteNano(nanoSpan);
}
}
@Override
@@ -114,7 +114,9 @@ public class WebAppStat {
WebSessionStat uriStat = sessionStatMap.get(sessionId);
if (uriStat == null) {
sessionStatMap.putIfAbsent(sessionId, new WebSessionStat(sessionId));
WebSessionStat newStat = new WebSessionStat(sessionId);
sessionStatMap.putIfAbsent(sessionId, newStat);
uriStat = sessionStatMap.get(sessionId);
}
@@ -13,6 +13,10 @@ public class WebAppStatUtils {
@SuppressWarnings("unchecked")
public static Map<String, Object> getStatData(Object webStat) {
if (webStat.getClass() == WebAppStat.class) {
return ((WebAppStat) webStat).getStatData();
}
try {
Method method = webStat.getClass().getMethod("getStatData");
Object obj = method.invoke(webStat);
@@ -22,9 +26,13 @@ public class WebAppStatUtils {
return null;
}
}
@SuppressWarnings("unchecked")
public static List<Map<String, Object>> getURIStatDataList(Object webStat) {
if (webStat.getClass() == WebAppStat.class) {
return ((WebAppStat) webStat).getURIStatDataList();
}
try {
Method method = webStat.getClass().getMethod("getURIStatDataList");
Object obj = method.invoke(webStat);
@@ -34,9 +42,13 @@ public class WebAppStatUtils {
return null;
}
}
@SuppressWarnings("unchecked")
public static List<Map<String, Object>> getSessionStatDataList(Object webStat) {
if (webStat.getClass() == WebAppStat.class) {
return ((WebAppStat) webStat).getSessionStatDataList();
}
try {
Method method = webStat.getClass().getMethod("getSessionStatDataList");
Object obj = method.invoke(webStat);
@@ -9,6 +9,7 @@ public class WebRequestStat {
private long jdbcExecuteCount;
private long jdbcUpdateCount;
private long jdbcFetchRowCount;
private long jdbcExecuteNano;
public WebRequestStat(){
@@ -60,6 +61,14 @@ public class WebRequestStat {
return jdbcExecuteCount;
}
public long getJdbcExecuteNano() {
return jdbcExecuteNano;
}
public void addJdbcExecuteNano(long nano) {
jdbcExecuteNano += nano;
}
public long getJdbcUpdateCount() {
return jdbcUpdateCount;
}
@@ -1,7 +1,10 @@
package com.alibaba.druid.support.http.stat;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -9,18 +12,24 @@ public class WebSessionStat {
private final String sessionId;
private final AtomicInteger runningCount = new AtomicInteger();
private final AtomicInteger concurrentMax = new AtomicInteger();
private final AtomicLong requestCount = new AtomicLong(0);
private final AtomicInteger runningCount = new AtomicInteger();
private final AtomicInteger concurrentMax = new AtomicInteger();
private final AtomicLong requestCount = new AtomicLong(0);
private final AtomicLong jdbcFetchRowCount = new AtomicLong();
private final AtomicLong jdbcUpdateCount = new AtomicLong();
private final AtomicLong jdbcExecuteCount = new AtomicLong();
private final AtomicLong jdbcFetchRowCount = new AtomicLong();
private final AtomicLong jdbcUpdateCount = new AtomicLong();
private final AtomicLong jdbcExecuteCount = new AtomicLong();
private final AtomicLong jdbcExecuteTimeNano = new AtomicLong();
private final AtomicLong jdbcCommitCount = new AtomicLong();
private final AtomicLong jdbcRollbackCount = new AtomicLong();
private final AtomicLong jdbcCommitCount = new AtomicLong();
private final AtomicLong jdbcRollbackCount = new AtomicLong();
private final AtomicLong requestTimeNano = new AtomicLong();
private final AtomicLong requestTimeNano = new AtomicLong();
private long createTimeMillis = -1L;
private long lastAccessTimeMillis = -1L;
private Set<String> remoteAddresses = new HashSet<String>();
public WebSessionStat(String sessionId){
super();
@@ -31,6 +40,62 @@ public class WebSessionStat {
return sessionId;
}
public long getCreateTimeMillis() {
return createTimeMillis;
}
public Date getCreateTime() {
if (createTimeMillis == -1L) {
return null;
}
return new Date(createTimeMillis);
}
public void setCreateTimeMillis(long createTimeMillis) {
this.createTimeMillis = createTimeMillis;
}
public long getLastAccessTimeMillis() {
return lastAccessTimeMillis;
}
public Date getLastAccessTime() {
if (lastAccessTimeMillis == -1L) {
return null;
}
return new Date(lastAccessTimeMillis);
}
public Set<String> getRemoteAddresses() {
return remoteAddresses;
}
public String getRemoteAddress() {
if (remoteAddresses.size() == 0) {
return null;
}
if (remoteAddresses.size() == 1) {
return remoteAddresses.iterator().next();
}
StringBuilder buf = new StringBuilder();
for (String item : remoteAddresses) {
if (buf.length() != 0) {
buf.append(",");
}
buf.append(item);
}
return buf.toString();
}
public void setLastAccessTimeMillis(long lastAccessTimeMillis) {
this.lastAccessTimeMillis = lastAccessTimeMillis;
}
public void beforeInvoke() {
int running = runningCount.incrementAndGet();
@@ -66,9 +131,14 @@ public class WebSessionStat {
this.addJdbcUpdateCount(requestStat.getJdbcUpdateCount());
this.addJdbcCommitCount(requestStat.getJdbcCommitCount());
this.addJdbcRollbackCount(requestStat.getJdbcRollbackCount());
this.addJdbcExecuteTimeNano(requestStat.getJdbcExecuteNano());
}
}
public void addRemoteAddress(String ip) {
this.remoteAddresses.add(ip);
}
public int getRunningCount() {
return this.runningCount.get();
}
@@ -81,6 +151,14 @@ public class WebSessionStat {
return requestCount.get();
}
public long getRequestTimeNano() {
return requestTimeNano.get();
}
public long getRequestTimeMillis() {
return getRequestTimeNano() / (1000 * 1000);
}
public void addJdbcFetchRowCount(long delta) {
this.jdbcFetchRowCount.addAndGet(delta);
}
@@ -109,6 +187,18 @@ public class WebSessionStat {
return jdbcExecuteCount.get();
}
public long getJdbcExecuteTimeMillis() {
return getJdbcExecuteTimeNano() / (1000 * 1000);
}
public long getJdbcExecuteTimeNano() {
return jdbcExecuteTimeNano.get();
}
public void addJdbcExecuteTimeNano(long nano) {
jdbcExecuteTimeNano.addAndGet(nano);
}
public void incrementJdbcCommitCount() {
jdbcCommitCount.incrementAndGet();
}
@@ -128,11 +218,11 @@ public class WebSessionStat {
public long getJdbcRollbackCount() {
return jdbcRollbackCount.get();
}
public void addJdbcRollbackCount(long rollbackCount) {
this.jdbcRollbackCount.addAndGet(rollbackCount);
}
public Map<String, Object> getStatData() {
Map<String, Object> data = new LinkedHashMap<String, Object>();
@@ -140,11 +230,16 @@ public class WebSessionStat {
data.put("RunningCount", this.getRunningCount());
data.put("ConcurrentMax", this.getConcurrentMax());
data.put("RequestCount", this.getRequestCount());
data.put("RequestTimeMillisTotal", this.getRequestTimeMillis());
data.put("CreateTime", this.getCreateTime());
data.put("LastAccessTime", this.getLastAccessTime());
data.put("RemoteAddress", this.getRemoteAddress());
data.put("JdbcCommitCount", this.getJdbcCommitCount());
data.put("JdbcRollbackCount", this.getJdbcRollbackCount());
data.put("JdbcExecuteCount", this.getJdbcExecuteCount());
data.put("JdbcExecuteTimeMillis", this.getJdbcExecuteTimeMillis());
data.put("JdbcFetchRowCount", this.getJdbcFetchRowCount());
data.put("JdbcUpdateCount", this.getJdbcUpdateCount());
@@ -0,0 +1,394 @@
package com.alibaba.druid.util;
/**
* <p>
* PathMatcher implementation for Ant-style path patterns. Examples are provided below.
* </p>
* <p>
* Part of this mapping code has been kindly borrowed from <a href="http://ant.apache.org">Apache Ant</a>.
* <p>
* The mapping matches URLs using the following rules:<br>
* <ul>
* <li>? matches one character</li>
* <li>* matches zero or more characters</li>
* <li>** matches zero or more 'directories' in a path</li>
* </ul>
* <p>
* Some examples:<br>
* <ul>
* <li><code>com/t?st.jsp</code> - matches <code>com/test.jsp</code> but also <code>com/tast.jsp</code> or
* <code>com/txst.jsp</code></li>
* <li><code>com/*.jsp</code> - matches all <code>.jsp</code> files in the <code>com</code> directory</li>
* <li><code>com/&#42;&#42;/test.jsp</code> - matches all <code>test.jsp</code> files underneath the <code>com</code>
* path</li>
* <li><code>com/alibaba/druid/&#42;&#42;/*.jsp</code> - matches all <code>.jsp</code> files underneath the
* <code>org/apache/shiro</code> path</li>
* <li><code>com/&#42;&#42;/servlet/bla.jsp</code> - matches <code>com/alibaba/druid/servlet/bla.jsp</code> but also
* <code>com/alibaba/druid/testing/servlet/bla.jsp</code> and <code>com/servlet/bla.jsp</code></li>
* </ul>
* <p>
* <b>N.B.</b>: This class was borrowed (with much appreciation) from the <a href="http://shiro.apache.org">Shiro</a>
* and the <a href="http://www.springframework.org">Spring Framework</a> with modifications. We didn't want to reinvent
* the wheel of great work they've done, but also didn't want to force every Shiro user to depend on Spring
* </p>
* <p>
* As per the Apache 2.0 license, the original copyright notice and all author and copyright information have remained
* in tact.
* </p>
*
* @since 16.07.2003
*/
public class AntPathMatcher implements PatternMatcher {
// TODO - complete JavaDoc
/**
* Default path separator: "/"
*/
public static final String DEFAULT_PATH_SEPARATOR = "/";
private String pathSeparator = DEFAULT_PATH_SEPARATOR;
/**
* Set the path separator to use for pattern parsing. Default is "/", as in Ant.
*/
public void setPathSeparator(String pathSeparator) {
this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR);
}
public boolean isPattern(String path) {
return (path.indexOf('*') != -1 || path.indexOf('?') != -1);
}
public boolean matches(String pattern, String source) {
return match(pattern, source);
}
public boolean match(String pattern, String path) {
return doMatch(pattern, path, true);
}
public boolean matchStart(String pattern, String path) {
return doMatch(pattern, path, false);
}
/**
* Actually match the given <code>path</code> against the given <code>pattern</code>.
*
* @param pattern the pattern to match against
* @param path the path String to test
* @param fullMatch whether a full pattern match is required (else a pattern match as far as the given base path
* goes is sufficient)
* @return <code>true</code> if the supplied <code>path</code> matched, <code>false</code> if it didn't
*/
protected boolean doMatch(String pattern, String path, boolean fullMatch) {
if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) {
return false;
}
String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);
String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator);
int pattIdxStart = 0;
int pattIdxEnd = pattDirs.length - 1;
int pathIdxStart = 0;
int pathIdxEnd = pathDirs.length - 1;
// Match all elements up to the first **
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxStart];
if ("**".equals(patDir)) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxStart])) {
return false;
}
pattIdxStart++;
pathIdxStart++;
}
if (pathIdxStart > pathIdxEnd) {
// Path is exhausted, only match if rest of pattern is * or **'s
if (pattIdxStart > pattIdxEnd) {
return (pattern.endsWith(this.pathSeparator) ? path.endsWith(this.pathSeparator) : !path.endsWith(this.pathSeparator));
}
if (!fullMatch) {
return true;
}
if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) {
return true;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
} else if (pattIdxStart > pattIdxEnd) {
// String not exhausted, but pattern is. Failure.
return false;
} else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
// up to last '**'
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxEnd];
if (patDir.equals("**")) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxEnd])) {
return false;
}
pattIdxEnd--;
pathIdxEnd--;
}
if (pathIdxStart > pathIdxEnd) {
// String is exhausted
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {
int patIdxTmp = -1;
for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {
if (pattDirs[i].equals("**")) {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == pattIdxStart + 1) {
// '**/**' situation, so skip one
pattIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - pattIdxStart - 1);
int strLength = (pathIdxEnd - pathIdxStart + 1);
int foundIdx = -1;
strLoop: for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
String subPat = (String) pattDirs[pattIdxStart + j + 1];
String subStr = (String) pathDirs[pathIdxStart + i + j];
if (!matchStrings(subPat, subStr)) {
continue strLoop;
}
}
foundIdx = pathIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
pattIdxStart = patIdxTmp;
pathIdxStart = foundIdx + patLength;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
/**
* Tests whether or not a string matches against a pattern. The pattern may contain two special characters:<br>
* '*' means zero or more characters<br>
* '?' means one and only one character
*
* @param pattern pattern to match against. Must not be <code>null</code>.
* @param str string which must be matched against the pattern. Must not be <code>null</code>.
* @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise.
*/
private boolean matchStrings(String pattern, String str) {
char[] patArr = pattern.toCharArray();
char[] strArr = str.toCharArray();
int patIdxStart = 0;
int patIdxEnd = patArr.length - 1;
int strIdxStart = 0;
int strIdxEnd = strArr.length - 1;
char ch;
boolean containsStar = false;
for (char aPatArr : patArr) {
if (aPatArr == '*') {
containsStar = true;
break;
}
}
if (!containsStar) {
// No '*'s, so we make a shortcut
if (patIdxEnd != strIdxEnd) {
return false; // Pattern and string do not have the same size
}
for (int i = 0; i <= patIdxEnd; i++) {
ch = patArr[i];
if (ch != '?') {
if (ch != strArr[i]) {
return false;// Character mismatch
}
}
}
return true; // String matches against pattern
}
if (patIdxEnd == 0) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != strArr[strIdxStart]) {
return false;// Character mismatch
}
}
patIdxStart++;
strIdxStart++;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// Process characters after last star
while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != strArr[strIdxEnd]) {
return false;// Character mismatch
}
}
patIdxEnd--;
strIdxEnd--;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
int patIdxTmp = -1;
for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
if (patArr[i] == '*') {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patIdxStart + 1) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - patIdxStart - 1);
int strLength = (strIdxEnd - strIdxStart + 1);
int foundIdx = -1;
strLoop: for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
ch = patArr[patIdxStart + j + 1];
if (ch != '?') {
if (ch != strArr[strIdxStart + i + j]) {
continue strLoop;
}
}
}
foundIdx = strIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx + patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
/**
* Given a pattern and a full path, determine the pattern-mapped part.
* <p>
* For example:
* <ul>
* <li>'<code>/docs/cvs/commit.html</code>' and '<code>/docs/cvs/commit.html</code> -> ''</li>
* <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>
* <li>'<code>/docs/cvs/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li>
* <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>
* <li>'<code>/docs/**\/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li>
* <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>docs/cvs/commit.html</code>'</li>
* <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>
* <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>
* </ul>
* <p>
* Assumes that {@link #match} returns <code>true</code> for '<code>pattern</code>' and '<code>path</code>', but
* does <strong>not</strong> enforce this.
*/
public String extractPathWithinPattern(String pattern, String path) {
String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);
String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator);
StringBuilder buffer = new StringBuilder();
// Add any path parts that have a wildcarded pattern part.
int puts = 0;
for (int i = 0; i < patternParts.length; i++) {
String patternPart = patternParts[i];
if ((patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) && pathParts.length >= i + 1) {
if (puts > 0 || (i == 0 && !pattern.startsWith(this.pathSeparator))) {
buffer.append(this.pathSeparator);
}
buffer.append(pathParts[i]);
puts++;
}
}
// Append any trailing path parts.
for (int i = patternParts.length; i < pathParts.length; i++) {
if (puts > 0 || i > 0) {
buffer.append(this.pathSeparator);
}
buffer.append(pathParts[i]);
}
return buffer.toString();
}
}
@@ -6,6 +6,7 @@ import java.util.Map;
import javax.management.ObjectName;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
@@ -14,6 +15,10 @@ public class DruidDataSourceUtils {
private final static Log LOG = LogFactory.getLog(DruidDataSourceUtils.class);
public static String getUrl(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getUrl();
}
try {
Method method = druidDatasource.getClass().getMethod("getUrl");
Object obj = method.invoke(druidDatasource);
@@ -25,6 +30,10 @@ public class DruidDataSourceUtils {
}
public static ObjectName getObjectName(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getObjectName();
}
try {
Method method = druidDatasource.getClass().getMethod("getObjectName");
Object obj = method.invoke(druidDatasource);
@@ -36,6 +45,10 @@ public class DruidDataSourceUtils {
}
public static Object getSqlStat(Object druidDatasource, int sqlId) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getSqlStat(sqlId);
}
try {
Method method = druidDatasource.getClass().getMethod("getSqlStat", int.class);
Object obj = method.invoke(druidDatasource, sqlId);
@@ -47,6 +60,10 @@ public class DruidDataSourceUtils {
}
public static boolean isRemoveAbandoned(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).isRemoveAbandoned();
}
try {
Method method = druidDatasource.getClass().getMethod("isRemoveAbandoned");
Object obj = method.invoke(druidDatasource);
@@ -59,6 +76,10 @@ public class DruidDataSourceUtils {
@SuppressWarnings("unchecked")
public static Map<String, Object> getStatDataForMBean(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getStatDataForMBean();
}
try {
Method method = druidDatasource.getClass().getMethod("getStatDataForMBean");
Object obj = method.invoke(druidDatasource);
@@ -71,6 +92,10 @@ public class DruidDataSourceUtils {
@SuppressWarnings("unchecked")
public static Map<String, Object> getStatData(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getStatData();
}
try {
Method method = druidDatasource.getClass().getMethod("getStatData");
Object obj = method.invoke(druidDatasource);
@@ -83,6 +108,10 @@ public class DruidDataSourceUtils {
@SuppressWarnings({ "rawtypes" })
public static Map getSqlStatMap(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getSqlStatMap();
}
try {
Method method = druidDatasource.getClass().getMethod("getSqlStatMap");
Object obj = method.invoke(druidDatasource);
@@ -95,6 +124,10 @@ public class DruidDataSourceUtils {
@SuppressWarnings("unchecked")
public static List<Map<String, Object>> getPoolingConnectionInfo(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getPoolingConnectionInfo();
}
try {
Method method = druidDatasource.getClass().getMethod("getPoolingConnectionInfo");
Object obj = method.invoke(druidDatasource);
@@ -107,6 +140,10 @@ public class DruidDataSourceUtils {
@SuppressWarnings("unchecked")
public static List<String> getActiveConnectionStackTrace(Object druidDatasource) {
if (druidDatasource.getClass() == DruidDataSource.class) {
return ((DruidDataSource) druidDatasource).getActiveConnectionStackTrace();
}
try {
Method method = druidDatasource.getClass().getMethod("getActiveConnectionStackTrace");
Object obj = method.invoke(druidDatasource);
@@ -0,0 +1,44 @@
package com.alibaba.druid.util;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
public class DruidWebUtils {
public static String getRemoteAddr(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.getRemoteAddr();
}
return ip;
}
private static String getContextPath_2_5(ServletContext context) {
String contextPath = context.getContextPath();
if (contextPath == null || contextPath.length() == 0) {
contextPath = "/";
}
return contextPath;
}
public static String getContextPath(ServletContext context) {
if (context.getMajorVersion() == 2 && context.getMinorVersion() < 5) {
return null;
}
try {
return getContextPath_2_5(context);
} catch (NoSuchMethodError error) {
return null;
}
}
}
@@ -3,6 +3,7 @@ package com.alibaba.druid.util;
import java.lang.reflect.Method;
import java.util.Map;
import com.alibaba.druid.stat.JdbcSqlStat;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
@@ -13,6 +14,10 @@ public class JdbcSqlStatUtils {
@SuppressWarnings("unchecked")
public static Map<String, Object> getData(Object jdbcSqlStat) {
try {
if (jdbcSqlStat.getClass() == JdbcSqlStat.class) {
return ((JdbcSqlStat) jdbcSqlStat).getData();
}
Method method = jdbcSqlStat.getClass().getMethod("getData");
Object obj = method.invoke(jdbcSqlStat);
return (Map<String, Object>) obj;
@@ -0,0 +1,24 @@
package com.alibaba.druid.util;
/**
* Interface for components that can match source strings against a specified pattern string.
* <p/>
* Different implementations can support different pattern types, for example, Ant style path expressions, or regular
* expressions, or other types of text based patterns.
*
* @see com.alibaba.druid.util.AntPathMatcher AntPathMatcher
* @since 0.2.6
*/
public interface PatternMatcher {
/**
* Returns <code>true</code> if the given <code>source</code> matches the specified <code>pattern</code>,
* <code>false</code> otherwise.
*
* @param pattern the pattern to match against
* @param source the source to match
* @return <code>true</code> if the given <code>source</code> matches the specified <code>pattern</code>,
* <code>false</code> otherwise.
*/
boolean matches(String pattern, String source);
}
@@ -0,0 +1,41 @@
package com.alibaba.druid.util;
public class ServletPathMatcher implements PatternMatcher {
/**
* <p>
* three type: endsWithMatch(eg. /xxx*=/xxx/xyz), startsWithMatch(eg. *.xxx=abc.xxx), equals(eg. /xxx=/xxx)。
* </p>
* <b>Notice</b>: *xxx* will match *xxxyyyy. endsWithMatch first.
*/
@Override
public boolean matches(String pattern, String source) {
if (pattern == null || source == null) {
return false;
}
pattern = pattern.trim();
source = source.trim();
if (pattern.endsWith("*")) {
// pattern: /druid* source:/druid/index.html
int length = pattern.length() - 1;
if (source.length() >= length) {
if (pattern.substring(0, length).equals(source.substring(0, length))) {
return true;
}
}
} else if (pattern.startsWith("*")) {
// pattern: *.html source:/xx/xx.html
int length = pattern.length() - 1;
if (source.length() >= length && source.endsWith(pattern.substring(1))) {
return true;
}
} else {
// pattern: /druid/index.html source:/druid/index.html
if (pattern.equals(source)) {
return true;
}
}
return false;
}
}
@@ -1,7 +1,11 @@
package com.alibaba.druid.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
@@ -97,6 +101,85 @@ public class StringUtils {
return parameters;
}
/**
* Tokenize the given String into a String array via a StringTokenizer. Trims tokens and omits empty tokens.
* <p>
* The given delimiters string is supposed to consist of any number of delimiter characters. Each of those
* characters can be used to separate tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
* <p/>
* <p>
* Copied from the Spring Framework while retaining all license, copyright and author information.
*
* @param str the String to tokenize
* @param delimiters the delimiter characters, assembled as String (each of those characters is individually
* considered as delimiter).
* @return an array of the tokens
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
*/
public static String[] tokenizeToStringArray(String str, String delimiters) {
return tokenizeToStringArray(str, delimiters, true, true);
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
* <p>
* The given delimiters string is supposed to consist of any number of delimiter characters. Each of those
* characters can be used to separate tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
* <p/>
* <p>
* Copied from the Spring Framework while retaining all license, copyright and author information.
*
* @param str the String to tokenize
* @param delimiters the delimiter characters, assembled as String (each of those characters is individually
* considered as delimiter)
* @param trimTokens trim the tokens via String's <code>trim</code>
* @param ignoreEmptyTokens omit empty tokens from the result array (only applies to tokens that are empty after
* trimming; StringTokenizer will not consider subsequent delimiters as token in the first place).
* @return an array of the tokens (<code>null</code> if the input String was <code>null</code>)
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
boolean ignoreEmptyTokens) {
if (str == null) {
return null;
}
StringTokenizer st = new StringTokenizer(str, delimiters);
List tokens = new ArrayList();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
if (!ignoreEmptyTokens || token.length() > 0) {
tokens.add(token);
}
}
return toStringArray(tokens);
}
/**
* Copy the given Collection into a String array. The Collection must contain String elements only.
* <p/>
* <p>
* Copied from the Spring Framework while retaining all license, copyright and author information.
*
* @param collection the Collection to copy
* @return the String array (<code>null</code> if the passed-in Collection was <code>null</code>)
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String[] toStringArray(Collection collection) {
if (collection == null) {
return null;
}
return (String[]) collection.toArray(new String[collection.size()]);
}
public static void main(String args[]) {
System.out.println(JSON.toJSONString(getParameters("test?t=1&f=").get("t")));
}