??xml version="1.0" encoding="utf-8" standalone="yes"?> p6spy是一个开源YӞ它可以跟tQ何用jdbc的应用生的数据库操作。特别适合于监控ejb服务器生的 sql statements?br />
官方|址Q?a >http://www.p6spy.com/ 下面我介l一下p6spy在tomcat应用E序上安装的步骤Q?br />
Q?Q?a >http://www.p6spy.com/download.htmlQ下载zip?br />
Q?Q解压出p6spy.jar spy.properties两个文g realdriver =com.mysql.jdbc.Driver 这行前面的#L
ServletContext servletContext, ApplicationContext parent)
throws BeansException {}Q方法;
codeQ?br />
public class ContextLoaderListener implements ServletContextListener {
private ContextLoader contextLoader;
/**
* Initialize the root web application context.
*/
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
/**
* Create the ContextLoader to use. Can be overridden in subclasses.
* @return the new ContextLoader
*/
protected ContextLoader createContextLoader() {
return new CasContextLoader();
}
/**
* Return the ContextLoader used by this listener.
* @return the current ContextLoader
*/
public ContextLoader getContextLoader() {
return this.contextLoader;
}
/**
* Close the root web application context.
*/
public void contextDestroyed(ServletContextEvent event) {
if (this.contextLoader != null) {
this.contextLoader.closeWebApplicationContext(event.getServletContext());
}
}
}
public class CasContextLoader extends ContextLoader {
protected WebApplicationContext createWebApplicationContext(
ServletContext servletContext, ApplicationContext parent)
throws BeansException {
// return super.createWebApplicationContext(servletContext, parent);
Class contextClass = determineContextClass(servletContext);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setParent(parent);
wac.setServletContext(servletContext);
String configLocation = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
String flag=CasConstants.IS_USE_MEMCACHED;
if (configLocation != null) {
String[] xml=StringUtils.tokenizeToStringArray(configLocation,ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
if(flag!=null && flag.equalsIgnoreCase("true")){
String[] new_xml=StringUtils.addStringToArray(xml, "/WEB-INF/cas_memcached.xml");
wac.setConfigLocations(new_xml);
}else{
wac.setConfigLocations(xml);
}
}
wac.refresh();
return wac;
}
}
]]>
2、查N中的下一?Ctr+kQ反?Ctr+Shift+k
3、大写转化QCtr+Shift+X Ctr+Shift+Y
4、ctrl+tQctrl+t+tQ?查看cLҎ(gu)的承结?
5、ctrl+shift+u 查看变量在哪里被引用?
6、ctrl+shift+gQalt+shift+hQ?查看Ҏ(gu)在哪里被调用?
7、ctrl+l 定位行号
8、选中cd 点击Edit 选择 Copy qualified Name 可以把类的完整\径copy下来 同样Ҏ(gu)法名也适用
9、Go to Next/Last Member Ctrl+Shift+Down/Up
10、Copy Lines Ctrl+Alt+Down/Up
11、ctrl+r,查找资源文g
12、ctrl+t 查看cd?br />
13、ctrl+shift+f 代码格式?
]]>
但是有时候我们需要得到完整的SQL语句Q怎么办呢Q用P6SPY可以完成这个Q?
目前p6spy 适用的应用服务器包括jboss, atg, orion, jonas, iplanet, weblogic, websphere, resin and tomcat.
Q?Q将p6spy.jar 攑օ应用E序的WEB-INF/lib目录Q将spy.properties攑օWEB-INF/classes目录
Q?Q修改spy.properties
logfile = c:/spy.log 修改一个你需要的日志文g?br />
Q?Q修改hibernate.xmlQ修改connection.driver_class的gؓcom.p6spy.engine.spy.P6SpyDriver
Q?Q重启tomcat
Q?Q这样在c:/下的spy.log记录了数据库的访问情c?/p>
select agent_id agentId ,count(service_type) counts, sum(time_to_sec(end_time)-time_to_sec
(start_time)) seconds from et_service_log where service_type=? and site_id=? and agent_id in (?, ?,
?, ?, ?, ?, ?, ?, ?, ?) group by agent_id
SQLQuery sqlQuery = this.getSession().createSQLQuery(conditionSql);
sqlQuery.setParameterList("agentId", agentIdList);
2.M明细表关pL询优?br />
普遍Ҏ(gu)?先查询主表IDLIST,再通过每个ID,获取一l明l表中的数据
优化Ҏ(gu)?M?LEFT JOIN 一ơ执行就可以把相x据RESRARCH
CODE Q?br />
Criteria criteria = createCriteria(MessageCategory.class)
.add(Restrictions.eq("entityPk.siteId", siteId))
.add(Restrictions.eq("deleted", false));
criteria.createAlias("messageContentSet",
"messageContentSet",JoinFragment.LEFT_OUTER_JOIN).setFetchMode("messageContentSet",
FetchMode.JOIN).add(
Restrictions.eq("messageContentSet.deleted", false)).addOrder
(Order.desc("entityPk.id"));
List listData=criteria.list();
Set set =new HashSet(listData); (* qo重复数据)
在web.xml配置文g?.
dwr的配|?br />
加入corssDomainSessionSecurityq个配置选项..q个参数是在dwr版本2.0才有?默认gؓtrue,也就?/p>
止其他域发送请?
corssDomainSessionSecurity:讄成false能够从其他域q行h.注意q样做会在安全性上有一些冒?
package com.infowarelab.cem.easytouch.web.interceptor;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import com.infowarelab.cem.easytouch.service.cache.JbossCache;
import com.infowarelab.common.log.Log;
import com.infowarelab.common.log.LogFactory;
public class FlushGroupCacheInterceptor implements MethodInterceptor,
InitializingBean {
protected Log log = LogFactory.getLog(FlushGroupCacheInterceptor.class);
private static final long serialVersionUID = 2366041803410037545L;
private JbossCache cache;
private Integer siteId;
public void setCache(JbossCache cache) {
this.cache = cache;
}
public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = invocation.proceed();
flushGroupCache(invocation);
return result;
}
private void flushGroupCache(MethodInvocation invocation)
throws NoSuchMethodException {
// extends ActionSupport
// HttpSession session = ServletActionContext.getRequest().getSession();
// String
// siteId=(String)session.getAttribute(CEMConstants.SESSION_KEY_SITE_ID);
siteId = Context.getCurrentSiteId();
if (siteId == null) {
return;
}
String methodName = invocation.getMethod().getName();
log.info("--------------------");
log.info("methodName:" + methodName);
log.info("--------------------");
Class[] paramsType = invocation.getMethod().getParameterTypes();
Class methodNameClass = invocation.getThis().getClass();
Method m = methodNameClass.getMethod(methodName, paramsType);
boolean flag = m.isAnnotationPresent(OsCacheFlushGroupName.class);
if (flag) {
OsCacheFlushGroupName groupName = m
.getAnnotation(OsCacheFlushGroupName.class);
log.info("--------------------");
log.info("groupName:" + "" + siteId + groupName.value());
log.info("--------------------");
cache.flushGroup("" + siteId + groupName.value());
}
}
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
}
}
W?部分:web层数据传?br />
package com.infowarelab.cem.easytouch.web.interceptor;
public class Context {
private static ThreadLocal<Integer> currentSiteId = new ThreadLocal<Integer>();
private Context(){}
//q个Ҏ(gu)由Filter在请求达到时Ҏ(gu)会话(e.g HttpSessionQ但不限于HttpSession)情况调用讄
public static void setCurrentSiteId(Integer siteId) {
currentSiteId.set(siteId);
}
//q个Ҏ(gu)Q可被同一JVM中的M其他Ҏ(gu)调用?nbsp;
//q回当前h者的IdQ没有登录,则返回null
public static Integer getCurrentSiteId() {
return currentSiteId.get();
}
}
W?部分:web层数据传递通过filter,或web层Interceptor实现
package com.infowarelab.cem.easytouch.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.infowarelab.cem.common.util.CEMConstants;
import com.infowarelab.cem.easytouch.web.interceptor.Context;
public class SiteIdFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
// TODO Auto-generated method stub
setSiteIdToContext(request);
filterChain.doFilter(request, response);
}
private void setSiteIdToContext(ServletRequest request) {
String siteId = "";
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session.getAttribute(CEMConstants.SESSION_KEY_SITE_ID) != null) {
siteId = (String) session
.getAttribute(CEMConstants.SESSION_KEY_SITE_ID);
Context.setCurrentSiteId(new Integer(siteId));
return;
}
siteId = req.getParameter("siteId");
if (siteId != null && siteId.trim().length() > 0) {
Context.setCurrentSiteId(new Integer(siteId));
return;
}
}
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
}
}
Java中用的路径Q分ZU:l对路径和相对\径。具体而言Q又分ؓ四种Q?/p>
一、URI形式的绝对资源\?/p>
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b
URL是URI的特例。URL的前~/协议Q必LJava认识的。URL可以打开资源Q而URI则不行?/p>
URL和URI对象可以互相转换Q用各自的toURI(),toURL()Ҏ(gu)卛_Q?/p>
二、本地系l的l对路径
D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b
Java.io包中的类Q需要用这UŞ式的参数?/p>
但是Q它们一般也提供了URIcd的参敎ͼ而URIcd的参敎ͼ接受的是URI样式的String。因此,通过URI转换Q还是可以把URI样式的绝对\径用在java.io包中的类中?/p>
三、相对于classpath的相对\?/p>
如:相对?/p>
file:/D:/java/eclipse32/workspace/jbpmtest3/bin/q个路径的相对\径。其中,bin是本目的classpath。所有的Java源文件编译后?class文g复制到这个目录中?/p>
四、相对于当前用户目录的相对\?/p>
是相对于System.getProperty("user.dir")q回的\径?/p>
对于一般项目,q是目的根路径。对于JavaEE服务器,q可能是服务器的某个路径。这个ƈ没有l一的规范!
所以,l对不要使用“相对于当前用L录的相对路径”。然而:
默认情况下,java.io 包中的类LҎ(gu)当前用户目录来分析相对\径名。此目录ql属?user.dir 指定Q通常?Java 虚拟机的调用目录?/p>
q就是说Q在使用java.io包中的类Ӟ最好不要用相对\径。否则,虽然在J2SE应用E序中可能还正常,但是CJ2EEE序中,一定会出问题!而且q个路径Q在不同的服务器中都是不同的Q?/p>
Java路径的最l解x案:相对路径d(2)
|
相对路径最佛_?/p> 推荐使用相对于当前classpath的相对\?/p> 因此Q我们在使用相对路径Ӟ应当使用相对于当前classpath的相对\径?/p> ClassLoadercȝgetResource(String name),getResourceAsStream(String name){方法,使用相对于当前项目的classpath的相对\径来查找资源?/p> d属性文件常用到的ResourceBundlecȝgetBundle(String path)也是如此?/p> 通过查看ClassLoadercd其相关类的源代码Q我发现Q它实际上还是用了URI形式的绝对\径。通过得到当前classpath的URI形式的绝对\径,构徏了相对\径的URI形式的绝对\径。(q个实际上是猜想Q因为JDK内部调用了SUN的源代码Q而这些代码不属于JDKQ不是开源的。) 相对路径本质上还是绝对\?/p> 因此Q归根结底,Java本质上只能用绝对\径来L资源。所有的相对路径L资源的方法,都不q是一些便利方法。不q是API在底层帮助我们构Zl对路径Q从而找到资源的Q?/p> 得到classpath和当前类的绝对\径的一些方?/p> 下面是一些得到classpath和当前类的绝对\径的一些方法。你可能需要用其中的一些方法来得到你需要的资源的绝对\径?/p> 1QFileTest.class.getResource("") 得到的是当前cFileTest.class文g的URI目录。不包括自己Q?/p> 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/ 2QFileTest.class.getResource("/") 得到的是当前的classpath的绝对URI路径?/p> 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 3QThread.currentThread().getContextClassLoader().getResource("") 得到的也是当前ClassPath的绝对URI路径?/p> |
Java路径的最l解x案:相对路径d(3)
|
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 4QFileTest.class.getClassLoader().getResource("") 得到的也是当前ClassPath的绝对URI路径?/p> 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 5QClassLoader.getSystemResource("") 得到的也是当前ClassPath的绝对URI路径?/p> 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 推荐使用Thread.currentThread().getContextClassLoader().getResource("")来得到当前的classpath的绝对\径的URI表示法?/p> Web应用E序中资源的d 上文中说q,当前用户目录Q即相对于System.getProperty("user.dir")q回的\径?/p> 对于JavaEE服务器,q可能是服务器的某个路径Q这个ƈ没有l一的规范! 而不是我们发布的Web应用E序的根目录Q?/p> q样Q在Web应用E序中,我们l对不能使用相对于当前用L录的相对路径?/p> 在Web应用E序中,我们一般通过ServletContext.getRealPath("/")Ҏ(gu)得到Web应用E序的根目录的绝对\径?/p> q样Q我们只需要提供相对于Web应用E序根目录的路径Q就可以构徏出定位资源的l对路径?/p> q是我们开发Web应用E序时一般所采取的策略?/p> 通用的相对\径解军_?/p> Java中各U相对\径非常多Q不Ҏ(gu)使用Q非常容易出错。因此,我编写了一个便利方法,帮助更容易的解决相对路径问题?/p> Web应用E序中用JavaSEq行的资源寻址问题 在JavaSEE序中,我们一般用classpath来作为存放资源的目的地。但是,在Web应用E序中,我们一般用classpath外面的WEB-INF及其子目录作源文件的存放地?/p> |
Java路径的最l解x案:相对路径d(4)
|
在Web应用E序中,我们一般通过ServletContext.getRealPath("/")Ҏ(gu)得到Web应用E序的根目录的绝对\径。这P我们只需要提供相对于Web应用E序根目录的路径Q就可以构徏出定位资源的l对路径?/p> Web应用E序Q可以作为Web应用E序q行发布和运行。但是,我们也常怼以JavaSE的方式来q行Web应用E序的某个类的mainҎ(gu)。或者,使用JUnit试。这都需要用JavaSE的方式来q行?/p> q样Q我们就无法使用ServletContext.getRealPath("/")Ҏ(gu)得到Web应用E序的根目录的绝对\径?/p> 而JDK提供的ClassLoaderc, 它的getResource(String name),getResourceAsStream(String name){方法,使用相对于当前项目的classpath的相对\径来查找资源?/p> d属性文件常用到的ResourceBundlecȝgetBundle(String path)也是如此?/p> 它们都只能用相对\径来dclasspath下的资源Q无法定位到classpath外面的资源?/p> Classpath外配|文件读取问?/p> 如,我们使用试驱动开发的Ҏ(gu)Q开发Spring、Hibernate、iBatis{用配|文件的Web应用E序Q就会遇到问题?/p> 管Spring自己提供了FileSystemQ也是相对于user,dir目录Q来dWeb配置文g的方法,但是l究不是很方ѝ而且与WebE序中的代码使用方式不一_ 至于HibernateQiBatis更ȝ了!只有把配|文件移到classpath下,否则Ҏ(gu)不可能用测试驱动开发! 怎么办? 通用的相对\径解军_?/p> 面对q个问题Q我军_~写一个助手类ClassLoaderUtilQ提供一个便利方法[public static URL getExtendResource(String relativePath)]。在Web应用E序{一切JavaE序中,需要定位classpath外的资源Ӟ都用这个助手类的便利方法,而不使用 Web应用E序Ҏ(gu)的ServletContext.getRealPath("/")Ҏ(gu)来定位资源?/p> |
Java路径的最l解x案:相对路径d(5)
|
利用classpath的绝对\径,定位所有资?/p> q个便利Ҏ(gu)的实现原理,是“利用classpath的绝对\径,定位所有资?#8221;?/p> ClassLoadercȝgetResource("")Ҏ(gu)能够得到当前classpath的绝对\径,q是所有JavaE序都拥有的能力Q具有最大的适应性! 而目前的JDK提供的ClassLoadercȝgetResource(String 相对路径)Ҏ(gu)Q只能接受一般的相对路径。这P使用ClassLoadercȝgetResource(String 相对路径)Ҏ(gu)只能定位到classpath下的资源?/p> 如果Q它能够接受“../”q样的参敎ͼ允许我们用相对\径来定位classpath外面的资源,那么我们可以定位位|的资源Q?/p> 当然Q我无法修改ClassLoadercȝq个Ҏ(gu)Q于是,我编写了一个助手类ClassLoaderUtilc,提供了[public static URL getExtendResource(String relativePath)]q个Ҏ(gu)。它能够接受带有“../”W号的相对\径,实现了自由寻找资源的功能?/p> 通过相对classpath路径实现自由L资源的助手类的源代码Q?/p>
后记 ClassLoaderUtilcȝpublic static URL getExtendResource(String relativePath)Q虽然很单,但是实可以解决大问题?/p> 不过q个Ҏ(gu)q是比较陋的。我q想在未来有I时Q进一步增强它的能力。比如,增加Ant风格的匹配符。用**代表多个目录Q?代表多个字符Q?代表一个字W。达到Spring那样的能力,一ơ返回多个资源的URLQ进一步方便大家开发?/p> ȝQ?/p> 1.量不要使用相对于System.getProperty("user.dir")当前用户目录的相对\径。这是一颗定时炸弹,随时可能要你的命?/p> 2.量使用URI形式的绝对\径资源。它可以很容易的转变为URI,URLQFile对象?/p> 3.量使用相对classpath的相对\径。不要用绝对\径。用上面ClassLoaderUtilcȝpublic static URL getExtendResource(String relativePath)Ҏ(gu)已经能够使用相对于classpath的相对\径定位所有位|的资源?/p> 4.l对不要使用编码的l对路径。因为,我们完全可以使用ClassLoadercȝgetResource("")Ҏ(gu)得到当前classpath的绝对\径?/p> 使用编码的l对路径是完全没有必要的Q它一定会让你ȝ很难看!E序无法移植! 如果你一定要指定一个绝对\径,那么使用配置文gQ也比硬~码要好得多Q?/p> 当然Q我q是推荐你用程序得到classpath的绝对\径来D源的l对路径Q?/p> |
<div id="Float21789" style="position: absolute; z-index: 9; width: 190px; top: 200px;
right: 3px;">
<center>
<div id="AD21789" style="width: 190px; height: 90px; text-align: center; float: none;">
<a target="_blank">
<img src="http://community.csdn.net/ui/homepage/images/questions.gif" alt="提问" style="width: 180px;
height: 50px; padding-right: 3px;" /></a>
</div>
</center>
</div>
<script type="text/javascript" language="JavaScript">
var csdnScrollTop=function(){
return document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;
};
function mymove21789(){
document.getElementById("Float21789").style.top=csdnScrollTop()+300+'px';document.getElementById("Float21789").style.right=3+'px';setTimeout("mymove21789();",50);
}
mymove21789();
</script>
对于资源文g中包含参敎ͼ可以嵌套参数TagQ?/p>
׃webwork的view讉K资源的方式,实际上是通过调用ognlStack堆栈栈顶的action对象的getText(...)Ҏ(gu)实现的,所以我们可以直接运用这U方式,例如Q?/p>
׃JSP Tag不能嵌套Q因此当遇到上面q种情况Q需要在Tag里面讉K资源的时候,我们必采用这U直接通过ognlStack讉Kaction的方?/p>
当我们用FreeMakrer作ؓview的时候,两种方式都可以采?br /> 采用Tag方式Q?/p>
采用ognlStack方式Q?/p>
Ҏ(gu)两种方式Q?/p>
(1) 下蝲开源项?POM.XML) d:\untils
(2) q入 d:\untils 然后 mvn eclipse:eclipse
(3) 导入工程 (建立包依赖关p?
(4) 如果部分插g下蝲不了,可以直接靠到相应目录(m2仓库),POM.XMLd相应的插仉?br />
(5)dCLASSPATH 变量
可以看出静?span class="hilite1">代理cL一个很不爽的缺点:当如果接口加一个方法(把上面所有的代码的注释给LQ,所有的实现cd代理c里都需要做个实现。这增加了代码的复杂度。动?span class="hilite1">代理可以避免这个缺炏V?/p>
3 。动?span class="hilite1">代理
动?span class="hilite1">代理与普通的代理相比较,最大的好处是接口中声明的所有方法都被{Ud一个集中的Ҏ(gu)中处理(invokeQ,q样Q在接口Ҏ(gu)数量比较多的时候,我们可以q行灉|处理Q而不需要像静?span class="hilite1">代理那样每一个方法进行中转?/font>
动?span class="hilite1">代理c?font color="#ff0000">只能代理接口Q?span class="hilite1">代理c都需要实现InvocationHandlerc,实现invokeҎ(gu)。该invokeҎ(gu)是调用?span class="hilite1">代理接口的所有方法时需要调用的Q该invokeҎ(gu)q回的值是?span class="hilite1">代理接口的一个实现类
代码实例:
试c:
/**
* Describes the Request-For-Enhancement(RFE) that led
* to the presence of the annotated API element.
*/
public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
}
@RequestForEnhancement(
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
/**
* Indicates that the specification of the annotated API element
* is preliminary and subject to change.
*/
public @interface Preliminary { }
@Preliminary public class TimeTravel { ... }
/**
* Associates a copyright notice with the annotated API element.
*/
public @interface Copyright {
String value();
}
@Copyright("2002 Yoyodyne Propulsion Systems")
public class OscillationOverthruster { ... }
import java.lang.annotation.*;
/**
* Indicates that the annotated method is a test method.
* This annotation should be used only on parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
public class Foo {
@Test public static void m1() { }
public static void m2() { }
@Test public static void m3() {
throw new RuntimeException("Boom");
}
public static void m4() { }
@Test public static void m5() { }
public static void m6() { }
@Test public static void m7() {
throw new RuntimeException("Crash");
}
public static void m8() { }
}
Here is the testing tool:
import java.lang.reflect.*;
public class RunTests {
public static void main(String[] args) throws Exception {
int passed = 0, failed = 0;
for (Method m : Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(Test.class)) {
try {
m.invoke(null);
passed++;
} catch (Throwable ex) {
System.out.printf("Test %s failed: %s %n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("Passed: %d, Failed %d%n", passed, failed);
}
}
$ java RunTests Foo
Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom
Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash
Passed: 2, Failed 2
package com.bjinfotech.practice.annotation;
/**
* 演示如何使用java5内徏的annotation
* 参考资料:
* http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html
* http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html
* http://mindprod.com/jgloss/annotations.html
* @author cleverpig
*
*/
import java.util.List;
public class UsingBuiltInAnnotation {
//食物c?br /> class Food{}
//q草c?br /> class Hay extends Food{}
//动物c?br /> class Animal{
Food getFood(){
return null;
}
//使用Annotation声明DeprecatedҎ(gu)
@Deprecated
void deprecatedMethod(){
}
}
//马类-l承动物c?br /> class Horse extends Animal{
//使用Annotation声明覆盖Ҏ(gu)
@Override
Hay getFood(){
return new Hay();
}
//使用Annotation声明止警告
@SuppressWarnings({"deprecation","unchecked"})
void callDeprecatedMethod(List horseGroup){
Animal an=new Animal();
an.deprecatedMethod();
horseGroup.add(an);
}
}
}
package com.bjinfotech.practice.annotation;
import java.lang.annotation.*;
/**
* 定义annotation
* @author cleverpig
*
*/
//加蝲在VM中,在运行时q行映射
@Retention(RetentionPolicy.RUNTIME)
//限定此annotation只能标示Ҏ(gu)
@Target(ElementType.METHOD)
public @interface AnnotationDefineForTestFunction{}
package com.bjinfotech.practice.annotation;
import java.lang.reflect.*;
/**
* 一个实例程序应用前面定义的AnnotationQAnnotationDefineForTestFunction
* @author cleverpig
*
*/
public class UsingAnnotation {
@AnnotationDefineForTestFunction public static void method01(){}
public static void method02(){}
@AnnotationDefineForTestFunction public static void method03(){
throw new RuntimeException("method03");
}
public static void method04(){
throw new RuntimeException("method04");
}
public static void main(String[] argv) throws Exception{
int passed = 0, failed = 0;
//被检的cd
String className="com.bjinfotech.practice.annotation.UsingAnnotation";
//逐个查此cȝҎ(gu)Q当其方法用annotation声明时调用此Ҏ(gu)
for (Method m : Class.forName(className).getMethods()) {
if (m.isAnnotationPresent(AnnotationDefineForTestFunction.class)) {
try {
m.invoke(null);
passed++;
} catch (Throwable ex) {
System.out.printf("试 %s p|: %s %n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("试l果Q?通过: %d, p|Q?%d%n", passed, failed);
}
}
@Override
public String toSting() { // 注意Ҏ(gu)名拼写错?br /> return "[" + super.toString() + "]";
}
下面是一D用@Deprecated的代码:
/**
* q里是javadoc的@deprecated声明.
* @deprecated No one has players for this format any more. Use VHS instead.
*/
@Deprecated public class Betamax { ... }
@SuppressWarnings(value={"unchecked","fallthrough"})
public void lintTrap() { /* sloppy method body omitted */ }
@SuppressWarnings({"unchecked","fallthrough"})
@SuppressWarnings("unchecked")
@Reviews({ // Single-value annotation, so "value=" is omitted here
@Review(grade=Review.Grade.EXCELLENT,
reviewer="df"),
@Review(grade=Review.Grade.UNSATISFACTORY,
reviewer="eg",
comment="This method needs an @Override annotation")
})
@UncheckedExceptions({
IllegalArgumentException.class, StringIndexOutOfBoundsException.class
})
/**
* This package holds my custom annotation types.
*/
@com.davidflanagan.annotations.Author("David Flanagan")
package com.davidflanagan.annotations;
import java.lang.reflect.*;
Class c = WhizzBangClass.class;
Method m = c.getMethod("whizzy", int.class, int.class);
boolean unstable = m.isAnnotationPresent(Unstable.class);
AnnotatedElement target = WhizzBangClass.class; //获得被查询的AnnotatedElement
// 查询AnnotatedElement的@Reviews annotation信息
Reviews annotation = target.getAnnotation(Reviews.class);
// 因ؓ@Reviews annotationcd的成员ؓ@Review annotationcd的数l,
// 所以下面声明了Review[] reviews保存@Reviews annotationcd的value成员倹{?br /> Review[] reviews = annotation.value();
// 查询每个@Review annotation的成员信?br /> for(Review r : reviews) {
Review.Grade grade = r.grade();
String reviewer = r.reviewer();
String comment = r.comment();
System.out.printf("%s assigned a grade of %s and comment '%s'%n",
reviewer, grade, comment);
}
package com.davidflanagan.annotations;
import java.lang.annotation.*;
/**
* 使用annotation来描q那些被标注的成员是不稳定的Q需要更?br /> */
@Retention(RetentionPolicy.RUNTIME)
public @interface Unstable {}
/**
* 使用Authorq个annotation定义在程序中指出代码的作?br /> */
public @interface Author {
/** q回作者名 */
String value();
}
import java.lang.annotation.*;
/**
* Reviews annotationcd只有一个成员,
* 但是q个成员的类型是复杂的:由Review annotationl成的数l?br /> */
@Retention(RetentionPolicy.RUNTIME)
public @interface Reviews {
Review[] value();
}
/**
* Review annotationcd?个成员:
* 枚Dcd成员grade?br /> * 表示Review名称的字W串cd成员Reviewer?br /> * h默认值的字符串类型成员Comment?br /> */
public @interface Review {
// 内嵌的枚丄?br /> public static enum Grade { EXCELLENT, SATISFACTORY, UNSATISFACTORY };
// 下面的方法定义了annotation的成?br /> Grade grade();
String reviewer();
String comment() default "";
}
public @interface UncheckedExceptions {
Class<? extends RuntimeException>[] value();
}
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="org.taha.cache.METHOD_CACHE"
maxElementsInMemory="300"
eternal="false"
timeToIdleSeconds="60"
timeToLiveSeconds="60"
overflowToDisk="true"
/>
</ehcache>
//defaultCache 一定要有不然解析报?/p>
2. spring-ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-autowire="byName">
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<bean id="methodCache"
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="cacheManager" />
</property>
<property name="cacheName">
<value>org.taha.cache.METHOD_CACHE</value>
</property>
</bean>
<bean id="methodCacheInterceptor"
class="com.infowarelab.cem.easytouch.web.interceptor.MethodCacheInterceptor">
<property name="cache">
<ref local="methodCache" />
</property>
</bean>
<bean id="methodCachePointCut"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="methodCacheInterceptor" />
</property>
<property name="patterns">
<list>
<value>.*methodOne</value>
<value>.*methodTwo</value> //匚wmethodTwo的方?nbsp;
<value>.*cache.*</value> //匚w?cache开头的Ҏ(gu)
</list>
</property>
</bean>
<bean id="myBean"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="com.infowarelab.cem.easytouch.web.interceptor.MyBean" />
</property>
<property name="interceptorNames">
<list>
<value>methodCachePointCut</value>
</list>
</property>
</bean>
</beans>
package com.infowarelab.cem.easytouch.web.interceptor;
import java.io.Serializable;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
public class MethodCacheInterceptor implements MethodInterceptor,
InitializingBean {
private Cache cache;
/**
*
* sets cache name to be used
*
*/
public void setCache(Cache cache) {
this.cache = cache;
}
/*
*
* (non-Javadoc)
*
*
*
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*
*/
public Object invoke(MethodInvocation invocation) throws Throwable {
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
Object result;
String cacheKey = getCacheKey(targetName, methodName, arguments);
Element element = cache.get(cacheKey);
if (element == null) {
// call target/sub-interceptor
result = invocation.proceed();
// cache method result
element = new Element(cacheKey, (Serializable) result);
cache.put(element);
}
return element.getValue();
}
/**
*
* creates cache key: targetName.methodName.argument0.argument1...
*
*/
private String getCacheKey(String targetName, String methodName,
Object[] arguments) {
StringBuffer sb = new StringBuffer();
sb.append(targetName).append(".").append(methodName);
if ((arguments != null) && (arguments.length != 0)) {
for (int i = 0; i < arguments.length; i++) {
sb.append(".").append(arguments[i]);
}
}
return sb.toString();
}
/*
*
* (non-Javadoc)
*
*
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*
*/
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
}
}
package com.infowarelab.cem.easytouch.web.interceptor;
import com.infowarelab.cem.easytouch.service.ConfigdbInfoService;
public class MyBean {
private ConfigdbInfoService configdbInfoService;
public String methodOne(String siteId,String name){
String cityName=configdbInfoService.getCityNameByIp("192.168.1.92");
return ""+siteId+name+cityName;
}
public String methodTwo(String siteId,String name,String pwd){
String cityName=configdbInfoService.getCountryNameByIp("192.168.1.92");
return ""+siteId+name+cityName;
}
public void setConfigdbInfoService(ConfigdbInfoService configdbInfoService) {
this.configdbInfoService = configdbInfoService;
}
}
package com.infowarelab.cem.easytouch.web.action.api;
import com.infowarelab.cem.easytouch.web.interceptor.MyBean;
/**
*
* @author hummer.hu
* @date:2008-4-24
*
*/
public class CopyOfLogin extends ApiBaseAction {
private MyBean myBean;
public String execute() {
myBean.methodOne("5555555", "aaaa");
myBean.methodTwo("6666666", "aaaa", "bbbb");
return "login";
}
public void setMyBean(MyBean myBean) {
this.myBean = myBean;
}
}
public static String IntToIP(int ipAddress)
{
long ui1 = ipAddress & 0xFF000000;
ui1 = ui1 >> 24;
long ui2 = ipAddress & 0x00FF0000;
ui2 = ui2 >> 16;
long ui3 = ipAddress & 0x0000FF00;
ui3 = ui3 >> 8;
long ui4 = ipAddress & 0x000000FF;
String IPstr = "";
IPstr = String.valueOf(ui1) + "." + String.valueOf(ui2) + "."
+ String.valueOf(ui3) + "." + String.valueOf(ui4);
return IPstr;
}
public static void main(String args[]){
String ipAddress="58.17.128.0";
int ipInt=IPUtil.IPToInt(ipAddress);
System.out.println("String to int :"+ipInt);
System.out.println("int to String :"+IPUtil.IntToIP(ipInt));
}
}
private String getBillingForEasytouch(String urlParam){
String result="";
try{
URL url = new URL(urlParam);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
Integer easytouchServiceId = easyTouchConfig
.getInteger(Constants.CEM_EASYTOUCH_SERVICE_ID);
String pwd = easyTouchConfig
.getString(Constants.BILLING_FOR_EASYTOUCH_PWD);
out.write("c=siteId:"+siteId+",pwd:"+pwd+",serviceId:"+easytouchServiceId+"&s=0");
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
}
catch(Exception e){
}
return result;
}
?实际操作q程:
1.数据库环?192.168.0.70 cem_vcc
2.需要优化的SQL语句
基本SQL A: select vl.* from vccrawlog vl,
cem_cc_operator op,
cem_cc_operator_acd_group ag
where op.user_id=ag.user_id and ag.site_id=op.site_id
and ag.site_id=2010010
and auto_rec_name is not null and is_rec_deleted=0 and endtime is not null
and vl.site_id=2010010
and acd_group_id in
(542,632,622,862,752,692,702,822,552,722,532,662,812,562,642,782,832,732,872,802,792,742,712,652) and ( (callee_id =op.site_extension and call_type=0 ) or( caller_id =op.site_extension and call_type=1 ))
order by sequence desc;
要求 1.A语句需要进?COUNT(*) 操作
2.A语句需要进?分页
业务要说? 查询VCCRAWLOG满所有acd_group_id in
(542,632,622,862,752,692,702,822,552,722,532,662,812,562,642,782,832,732,872,802,792,742,712,652) 里面座席数据.
http://localhost:8080/vcc10/page/listRecords.action?&site=8ins
mysql 命o
show create table vccrawlog;
show index from vccrawlog;
SQL_NO_CACHE 不用~存
select DISTINCT
*************************************************
1.COUNT语句
select sum(cnt) from
(
select count(*) cnt from vccrawlog vl, cem_cc_operator op, cem_cc_operator_acd_group ag
where op.user_id=ag.user_id and ag.site_id=op.site_id
and vl.site_id=op.site_id and vl.caller_id =op.site_extension and vl.call_type=1
and ag.site_id=2010010 and vl.auto_rec_name is not null and vl.is_rec_deleted=0 and vl.endtime is not null
and ag.acd_group_id in (542,632,622,862,752,692,702,822,552,722,532,662,812,562,642,782,832,732,872,802,792,742,712,652)
union all
select count(*) cnt from vccrawlog vl, cem_cc_operator op, cem_cc_operator_acd_group ag
where op.user_id=ag.user_id and ag.site_id=op.site_id
and vl.site_id=op.site_id and vl.callee_id =op.site_extension and vl.call_type=0
and ag.site_id=2010010 and vl.auto_rec_name is not null and vl.is_rec_deleted=0 and vl.endtime is not null
and ag.acd_group_id in (542,632,622,862,752,692,702,822,552,722,532,662,812,562,642,782,832,732,872,802,792,742,712,652)
) a;
说明 通过union all 可以分别利用 caller_id ?callee_id索引
****************************************************
2 .countSql:
select sum(cnt) from
(
select count(*) cnt from vccrawlog vl, ( select op.site_id,op.site_extension from cem_cc_operator op, cem_cc_operator_acd_group ag
where op.user_id=ag.user_id and ag.site_id=op.site_id
and ag.site_id=2010010
and ag.acd_group_id in (542,632,622,862,752,692,702,822,552,722,532,662,812,562,642,782,832,732,872,802,792,742,712,652)
union select 2010010,20100108888 ) operators
where vl.site_id=operators.site_id and vl.caller_id =operators.site_extension and vl.call_type=1
and vl.auto_rec_name is not null and vl.is_rec_deleted=0 and vl.endtime is not null
union all
select count(*) cnt from vccrawlog vl, ( select op.site_id,op.site_extension from cem_cc_operator op, cem_cc_operator_acd_group ag
where op.user_id=ag.user_id and ag.site_id=op.site_id
and ag.site_id=2010010
and ag.acd_group_id in (542,632,622,862,752,692,702,822,552,722,532,662,812,562,642,782,832,732,872,802,792,742,712,652)
union select 2010010,20100108888 ) operators
where vl.site_id=operators.site_id and vl.callee_id =operators.site_extension and vl.call_type=0
and vl.auto_rec_name is not null and vl.is_rec_deleted=0 and vl.endtime is not null
) a;
说明:
select op.site_id,op.site_extension from cem_cc_operator op, cem_cc_operator_acd_group ag
where op.user_id=ag.user_id and ag.site_id=op.site_id and ag.site_id=2010010
and ag.acd_group_id in (542,632,622,862,752,692,702,822,552,722,532,662,812,562,642,782,832,732,872,802,792,742,712,652)
union select 2010010,20100108888
可以L大量的重复数?/p>
******************************************************************************
面性能排查:
1.逐步执行
<script language="javascript">
alert('aaaaaaa');
</script>
2.暂时删除觉得没有问题的部?/p>
~省圎ͼhibernate已经使用Z每个事务?/span>first-level cache?/span> Hibernate?/span>first-level cache主要是减在一个事务内?/span>sql查询数量。例如,如果一个对象在同一个事务内被修改多ơ,hibernate只生成一个包括所有修改的 UPDATE SQL语句。ؓ了减数据流动,second-level cache?/span>Session FactoryU的不同事务之间保持load的对象,q些对象Ҏ(gu)个应用可用,不只是对当前用户正在q行的查询。这P每次查询返回已l?/span>load在缓?/span>里的对象Q避免一个或更多潜在的数据库事务?/span>
下蝲ehcacheQhibernate3.2必须要ehcache1.2以上才能支持。可以修改log4j配置文glog4j.logger.net.sf.hibernate.cache=debug查看日志
1.在类路径?span style="font-family: Arial">ehcache.xmlQ?/p>
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
</ehcache>
2.applicationContext-hibernate.xml?/span>Hibernate SessionFactory配置Q?/span>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">@HIBERNATE-DIALECT@</prop>
<!--<prop key="hibernate.show_sql">true</prop>-->
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.hibernate.use_outer_join">true</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</bean>
说明Q如果不讄“查询~存”Q那?/span>hibernate只会~存使用load()Ҏ(gu)获得的单个持久化对象Q如果想~存使用findall()?/span> list()?/span>Iterator()?/span>createCriteria()?/span>createQuery(){方法获得的数据l果集的话,需要设|?/span> hibernate.cache.use_query_cache true 才行
.对于"query cache"Q需要在E序里编码:
getHibernateTemplate().setCacheQueries(true);
return getHibernateTemplate().find(hql);
下蝲ehcacheQhibernate3.2必须要ehcache1.2以上才能支持。可以修改log4j配置文glog4j.logger.net.sf.hibernate.cache=debug查看日志
配置的元素说明:
元素或属?描述
< diskStore> 讄~存数据文g的存攄?
< defaultCache> 讄~存的默认数据过期策?
< cache> 讑֮具体的命名缓存的数据q期{略
每个命名~存代表一个缓存区域,每个~存区域有各自的数据q期{略。命名缓存机制得用戯够在每个cM及类的每个集合的_度上设|数据过期策略?
cache元素的属?nbsp;
name 讄~存的名?它的取gؓcȝ全限定名或类的集合的名字
maxInMemory 讄Z内存的缓存中可存攄对象最大数?
eternal 讄对象是否为永久的,true表示怸q期,此时忽略timeToIdleSeconds和timeToLiveSeconds属?
默认值是false
timeToIdleSeconds 讄对象I闲最长时?过q个旉,对象q期。当对象q期?EHCache会把它从~存中清除?br />
如果此gؓ0,表示对象可以无限期地处于I闲状态?
timeToLiveSeconds 讄对象生存最长时?过q个旉,对象q期?br />
如果此gؓ0,表示对象可以无限期地存在于缓存中?
overflowToDisk 讄Z内在的缓存中的对象数目达C限后,是否把溢出的对象写到Z盘的缓存中
1. http://webtest.canoo.com/webtest/manual/Downloads.html 下蝲webTest相关?/span> build.zip
q?/span>unzip?/span> d:"dev"webtest目录
2. 安装 ant 下蝲ant的网址Q?/span>http://ant.apache.org/ (version 1.7.0)
ANT_HOME=d:"dev"ant
PATH=…%ANT_HOME%"bin
3. 使用 ANT 创徏webtest工程先进?/span>命oH口
d:"dev>ant –f webtest"webtest.xml wt.createProject
创徏成功默认myWebTestProject 工程
4. RUN demo tests
d:"dev"myWebTestProject>ant
5. test report à览器自动会打开试报告
6. 把工E导?/span>eclipse
googleWebTest.xml 文g如下
具体的资?/span> http://webtest.canoo.com/webtest/manual/stepIndex.html
WebtestҎ(gu)ȝ如下:
1. webtest模拟Firefox?/span> Internet Explorer方式执行JavaScript.
2. 不接收格式不正确?/span>HTML
3. Ҏ(gu)扩展和整?/span>
4. webtest是纯java~写?/span>,可以q行在有JDK的Q何机器上.
5. 完美的结果报?/span>,特别列出出错case的原?/span>
Windows
如果你用的是Windows XP 或者是Windows2003Q你可以使用IE 览器,或者安装Mozilla Firefox 或者Opera览器?
如果你是用的是Windows2000Q如果想使用IE览器,你就需要安装reg.exeQ但是如果用Firefox不需要。我们徏议(但不是必)你的浏览器执行路径加到你的PATH环境变量中(如果你不知道如何你的浏览器安装目录加到PATH中,那么你就必须你的浏览器安装到标准\径下QFirefox的标准\径:"c:\Program Files\Mozilla Firefox\firefox.exe"QIE览器的标准路径Q?c:\Program Files\Internet Explorer\iexplore.exe"Q?/p>
1. 先去 http://selenium-rc.openqa.org/download.jsp 下蝲selenium包。解压?
2. 用命令行来到解压的文件夹下: \selenium-remote-control-0.9.2\selenium-server-0.9.2
3. q行Q?java -jar selenium-server.jar 启动selenium server
4. 在Eclipse创徏一个项目,在项目的build path里面加上junit.jar和selenium-java-client-driver.jarQ这个在刚解压的包里面)
5. 然后在Eclipse里运?“Run As -> unit Test”卛_看到自动化的范例
最后粘贴一下那个测试程?/p>
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import junit.framework.TestCase;
public class GoogleTest extends TestCase {
private Selenium selenium;
public void setUp() throws Exception {
String url = "http://www.google.com";
selenium = new DefaultSelenium("localhost", 4444, "*firefox", url); //4444 is default server port
selenium.start();
}
protected void tearDown() throws Exception {
selenium.stop();
}
public void testGoogle() throws Throwable {
selenium.open("http://www.google.com/webhp?hl=en");
assertEquals("Google", selenium.getTitle());
selenium.type("q", "Selenium OpenQA");
assertEquals("Selenium OpenQA", selenium.getValue("q"));
selenium.click("btnG");
selenium.waitForPageToLoad("5000");
assertEquals("Selenium OpenQA - Google Search", selenium.getTitle());
}
}
相关资料Q?nbsp;
http://www.tkk7.com/becky/archive/2008/03/06/184267.html
http://www.javaeye.com/topic/160592