Thursday, June 10, 2010

一些常用的正则表达式

正则表达式用于字符串处理,表单验证等场合,实用高效,但用到时总是不太把握,以致往往要上网查一番。我将一些常用的表达式收藏在这里,作备忘之用。本贴随时会更新。

匹配中文字符的正则表达式: [\u4e00-\u9fa5]

匹配双字节字符(包括汉字在内):[^\x00-\xff]

应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)

String.prototype.len=function(){return this.replace([^\x00-\xff]/g,”aa”).length;}

匹配空行的正则表达式:\n[\s ]*\r

匹配HTML标记的正则表达式:/<(.*)>.*<\/\1><(.*) \/>/

匹配首尾空格的正则表达式:(^\s*)(\s*$)

应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现,如下:

String.prototype.trim = function()
{
return this.replace(/(^\s*)(\s*$)/g, “”);
}

利用正则表达式分解和转换IP地址:

下面是利用正则表达式匹配IP地址,并将IP地址转换成对应数值的Javascript程序:

function IP2V(ip)
{
re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
}
else
{
throw new Error(“Not a valid IP address!”)
}
}

不过上面的程序如果不用正则表达式,而直接用split函数来分解可能更简单,程序如下:

var ip=”10.100.20.168″
ip=ip.split(“.”)
alert(“IP值是:”+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))

匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

利用正则表达式去除字串中重复的字符的算法程序:[注:此程序不正确,原因见本贴回复]

var s=”abacabefgeeii”
var s1=s.replace(/(.).*\1/g,”$1″)
var re=new RegExp(“["+s1+"]“,”g”)
var s2=s.replace(re,”")
alert(s1+s2) //结果为:abcefgi

我原来在CSDN上发贴寻求一个表达式来实现去除重复字符的方法,最终没有找到,这是我能想到的最简单的实现方法。思路是使用后向引用取出包括重复的字符,再以重复的字符建立第二个表达式,取到不重复的字符,两者串连。这个方法对于字符顺序有要求的字符串可能不适用。

得用正则表达式从URL地址中提取文件名的javascript程序,如下结果为page1

s=”http://www.9499.net/page1.htm”
s=s.replace(/(.*\/){0,}([^\.]+).*/ig,”$2″)
alert(s)

利用正则表达式限制网页表单里的文本框输入内容:

用正则表达式限制只能输入中文:onkeyup=”value=value.replace(/[^\u4E00-\u9FA5]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\u4E00-\u9FA5]/g,”))”

用正则表达式限制只能输入全角字符: onkeyup=”value=value.replace(/[^\uFF00-\uFFFF]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\uFF00-\uFFFF]/g,”))”

用正则表达式限制只能输入数字:onkeyup=”value=value.replace(/[^\d]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,”))”

用正则表达式限制只能输入数字和英文:onkeyup=”value=value.replace(/[\W]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,”))”

正则表达式,相关链接
http://blog.csdn.net/laily/category/19548.aspx
http://blog.csdn.net/laily/archive/2004/06/30/30525.aspx 微软的正则表达式教程(五):选择/编组和后向引用

http://blog.csdn.net/laily/archive/2004/06/30/30522.aspx 微软的正则表达式教程(四):限定符和定位符

http://blog.csdn.net/laily/archive/2004/06/30/30517.aspx 微软的正则表达式教程(三):字符匹配

http://blog.csdn.net/laily/archive/2004/06/30/30514.aspx 微软的正则表达式教程(二):正则表达式语法和优先权顺序

http://blog.csdn.net/laily/archive/2004/06/30/30511.aspx 微软的正则表达式教程(一):正则表达式简介

http://blog.csdn.net/laily/archive/2004/06/30/30360.aspx 小程序大作为:高级查找/替换、正则表达式练习器、Javascript脚本程序调试器

http://blog.csdn.net/laily/archive/2004/06/24/25872.aspx 经典正则表达式

正则表达式,正规表达式,正则表达式匹配,正则表达式语法,模式匹配,正规表达式匹配 javascript正则表达式 ASP正则表达式 ASP.NET正则表达式 C#正则表达式 JSP正则表达式 PHP正则表达式 VB.NET正则表达式 VBSCript正则表达式编程 delphi正则表达式 jscript

补充:
^\d+$  //匹配非负整数(正整数 + 0)
^[0-9]*[1-9][0-9]*$  //匹配正整数
^((-\d+)(0+))$  //匹配非正整数(负整数 + 0)
^-[0-9]*[1-9][0-9]*$  //匹配负整数
^-?\d+$    //匹配整数
^\d+(\.\d+)?$  //匹配非负浮点数(正浮点数 + 0)
^(([0-9]+\.[0-9]*[1-9][0-9]*)([0-9]*[1-9][0-9]*\.[0-9]+)([0-9]*[1-9][0-9]*))$  //匹配正浮点数
^((-\d+(\.\d+)?)(0+(\.0+)?))$  //匹配非正浮点数(负浮点数 + 0)
^(-(([0-9]+\.[0-9]*[1-9][0-9]*)([0-9]*[1-9][0-9]*\.[0-9]+)([0-9]*[1-9][0-9]*)))$  //匹配负浮点数
^(-?\d+)(\.\d+)?$  //匹配浮点数
^[A-Za-z]+$  //匹配由26个英文字母组成的字符串
^[A-Z]+$  //匹配由26个英文字母的大写组成的字符串
^[a-z]+$  //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$  //匹配由数字和26个英文字母组成的字符串
^\w+$  //匹配由数字、26个英文字母或者下划线组成的字符串
^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$    //匹配email地址
^[a-zA-z]+://匹配(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$  //匹配url
利用正则表达式去除字串中重复的字符的算法程序:

var s=”abacabefgeeii”
var s1=s.replace(/(.).*\1/g,”$1″)
var re=new RegExp(“["+s1+"]“,”g”)
var s2=s.replace(re,”")
alert(s1+s2) //结果为:abcefgi
===============================
如果var s = “abacabefggeeii”
结果就不对了,结果为:abeicfgg
正则表达式的能力有限
1.确认有效电子邮件格式
下面的代码示例使用静态 Regex.IsMatch 方法验证一个字符串是否为有效电子邮件格式。如果字符串包含一个有效的电子邮件地址,则 IsValidEmail 方法返回 true,否则返回 false,但不采取其他任何操作。您可以使用 IsValidEmail,在应用程序将地址存储在数据库中或显示在 ASP.NET 页中之前,筛选出包含无效字符的电子邮件地址。

[Visual Basic]
Function IsValidEmail(strIn As String) As Boolean
‘ Return true if strIn is in valid e-mail format.
Return Regex.IsMatch(strIn, (“^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)(([\w-]+\.)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$”)
End Function
[C#]
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @”^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)(([\w-]+\.)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$”);
}

2.清理输入字符串
下面的代码示例使用静态 Regex.Replace 方法从字符串中抽出无效字符。您可以使用这里定义的 CleanInput 方法,清除掉在接受用户输入的窗体的文本字段中输入的可能有害的字符。CleanInput 在清除掉除 @、-(连字符)和 .(句点)以外的所有非字母数字字符后返回一个字符串。

[Visual Basic]
Function CleanInput(strIn As String) As String
‘ Replace invalid characters with empty strings.
Return Regex.Replace(strIn, “[^\w\.@-]“, “”)
End Function
[C#]
String CleanInput(string strIn)
{
// Replace invalid characters with empty strings.
return Regex.Replace(strIn, @”[^\w\.@-]“, “”);
}

3.更改日期格式
以下代码示例使用 Regex.Replace 方法来用 dd-mm-yy 的日期形式代替 mm/dd/yy 的日期形式。

[Visual Basic]
Function MDYToDMY(input As String) As String
Return Regex.Replace(input, _
“\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b”, _
“${day}-${month}-${year}”)
End Function
[C#]
String MDYToDMY(String input)
{
return Regex.Replace(input,
“\\b(?\\d{1,2})/(?\\d{1,2})/(?\\d{2,4})\\b”,
“${day}-${month}-${year}”);
}
Regex 替换模式
本示例说明如何在 Regex.Replace 的替换模式中使用命名的反向引用。其中,替换表达式 ${day} 插入由 (?…) 组捕获的子字符串。

有几种静态函数使您可以在使用正则表达式操作时无需创建显式正则表达式对象,而 Regex.Replace 函数正是其中之一。如果您不想保留编译的正则表达式,这将给您带来方便

4.提取 URL 信息
以下代码示例使用 Match.Result 来从 URL 提取协议和端口号。例如,“http://www.contoso.com:8080/letters/readme.html”将返回“http:8080”。

[Visual Basic]
Function Extension(url As String) As String
Dim r As New Regex(“^(?\w+)://[^/]+?(?:\d+)?/”, _
RegexOptions.Compiled)
Return r.Match(url).Result(“${proto}${port}”)
End Function
[C#]
String Extension(String url)
{
Regex r = new Regex(@”^(?\w+)://[^/]+?(?:\d+)?/”,
RegexOptions.Compiled);
return r.Match(url).Result(“${proto}${port}”);
}

Wednesday, January 20, 2010

disable Axis2 soapAction

Sometimes we want to disable soapAction of Axis2 to communicate .Net WCF webservice.

Add below in NetworkNode2Stub.java


//adding SOAP soap_headers
_serviceClient.addHeadersToEnvelope(env);
// set the message context with that soap envelope
_messageContext.setEnvelope(env);

// add the message contxt to the operation client
_operationClient.addMessageContext(_messageContext);

// Disable SOAP_ACTION to fix .Net endpoint without soapAction
_operationClient.getOptions().setProperty(

org.apache.axis2.Constants.Configuration.DISABLE_SOAP_ACTION,
org.apache.axis2.Constants.VALUE_TRUE);

//execute the operation client
_operationClient.execute(true);

Friday, January 8, 2010

Tomcat 5.X setup jndi

1. Copy jdbc driver to Tomcat 5.X\common\lib
2. Romove all commons-dbcp-x.x.x,commons-pool-x.x and jdbc driver from application/WEB-INF/lib

3. Add Context and jndi parameters in server.xml file as below:

Tomcat 5.0.xx:
(the entity way) was the only way that worked.

[server.xml]:
<Service...>
<Engine...>
<Host...>
...
<Context crossContext="true" docBase="/opt/tomcat5/webapps/oracleTest" path="/oracleTest" reloadable="true">
<Resource name="jdbc/myoracle" auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/myoracle">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>oracle.jdbc.OracleDriver</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:oracle:thin:@15.1.1.40:1521:dbastra</value>
</parameter>
<parameter>
<name>username</name>
<value>uuuuuu</value>
</parameter>
<parameter>
<name>password</name>
<value>xxxxxxxx</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>20</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>10</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>-1</value>
</parameter>
</ResourceParams>
<Resource name="jdbc/myoracle5" auth="Container"
type="javax.sql.DataSource" />
</Context>
</Host>
</Engine>
</Service>

Tomcat 5.5.xx:
(the attributes way) was the only way that worked.

[server.xml]:
<Service...>
<Engine...>
<Host...>
...
<Context path="/oracleTest" reloadable="true"
docBase="/opt/tomcat5/webapps/oracleTest">

<Logger className="org.apache.catalina.logger.SystemOutLogger"
verbosity="4" timestamp="true" />

<Resource name="jdbc/myoracle5" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@15.1.1.40:1521:dbastra" username="aradmin"
password="ar#admin#" maxActive="20" maxIdle="10" maxWait="-1" />

</Context>
</Host>
</Engine>
</Service>

for BOTH versions:

Here there are some points we should take a look:

<Context> in [server.xml] !!
"Please note that for tomcat 5, unlike tomcat 4.x, it is NOT recommended to place <Context> elements directly in the server.xml file. Instead, put them in the META-INF/context.xml directory of your WAR file or the conf directory as described above."
http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

And if we cut the <Context>..</Context> body we described above from the server.xml and paste it into [META-INF/context.xml] or into [conf/Catalina/localhost/oracleTest.xml], it works...


<?xml version='1.0' encoding='utf-8'?>
<Context crossContext="true" docBase="/forge/oracleTest" path="/oracleTest" reloadable="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt" timestamp="true" />

<Resource ... (the one that applies to your version)>

</Context>

GlobalNamingResources:
"GlobalNamingResources element defines the global JNDI resources for the Server. These resources are listed in the server's global JNDI resource context. This context is distinct from the per-web-application JNDI contexts described in the JNDI Resources HOW-TO. The resources defined in this element are not visible in the per-web-application contexts unless you explicitly link them with <ResourceLink> elements."
http://tomcat.apache.org/tomcat-5.5-doc/config/globalresources.html
http://tomcat.apache.org/tomcat-5.5-doc/config/context.html#Resource%20Links


Article From http://forums.sun.com/thread.jspa?threadID=567630&start=15

Tuesday, January 5, 2010

Parse Large xml using dom4j

dom4j提供了基于事件的模型来操作xml文档。利用该模型开发人员可以一部分、一部分的处理XML文档,而不需要将整个XML文档都加载到内存中。例如:假想你要处理一个非常大的XML文档,它可能是由数据库的某张数据表而来的。如下所示:
<ROWSET>
<ROW ID="1">
...
</ROW>
<ROW ID="2">
...
</ROW>
...
<ROW ID="N">
...
</ROW>
</ROWSET>
我们可以在某一时间只处理一个ROW节点,而不必立刻将文档的所有内容加载到内存中。dom4j提供一个基于事件的模型来实现它。我们可以注册一个事件处理器来处理一个或多个路径表达式。事件处理器会在注册路径的开始和结束时被调用执行。当注册路径的开始标签找到时执行事件处理器的 onStart()方法,当注册路径的结束标签被找到时执行事件处理器的onEnd()方法。
­
onStart()和onEnd()方法传递一个ElementPath实例参数,这个实例既为根据注册路径遍历xml文档时的当前节点(Element)。如果想对遍历的当前节点进行操作,可以在onEnd()方法中对当前节点调用detach()方法保存改。
下面是示例代码:

SAXReader reader = new SAXReader();
reader.addHandler( "/ROWSET/ROW",
new ElementHandler() {
public void onStart(ElementPath path) {
// do nothing here...
}
public void onEnd(ElementPath path) {
// process a ROW element
Element row = path.getCurrent();
Element rowSet = row.getParent();
Document document = row.getDocument();
...
// prune the tree
row.detach();
}
}
);

Document document = reader.read(url);
上面的办法解决了读的问题可是写的问题还没有解决。我命由我不由天(吹牛皮),畅游dom4j的doc文档找到如下几个方法
startDocument()
writeOpen();
writeClose();
endDocument()
动手一试,问题搞定,看来牛皮没白吹。下面是示例代码:

/**
* 数据写入xml文件
* @param filePath 目标xml文件的存放路径
* @return
*/
public boolean writeXML(String filePath){
XMLWriter out;
try {

/*
* 创建XMLWriter对象,设置XML编码,解决中文问题。
*/
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("GBK");
out = new XMLWriter(new FileWriter(filePath),outputFormat);


out.startDocument();
Element rootElement = DocumentHelper.createElement("mans");
out.writeOpen(rootElement);

/*
* 向mans节点写入子节点
*/
for(int i=0 ; i<1000000 ; i++){
Element man = createManElement(new Long(i), "shuhang"+i);//用于创建节点的方法
out.write(man);
System.out.println(" the loop index is : " + i);
}

out.writeClose(rootElement);
out.endDocument();

out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (SAXException e) {
e.printStackTrace();
return false;
}
}

­
新问题出现。对于读取数据的方法,在onEnd()方法中只是进行对Element的简单操作而已,若要对Element进行复杂的处理怎么办,如将Element节点的数据写入数据库,无法在onEnd()方法中加入过多的代码,因为无法通过编译。仔细想了一下dom4j的注册事件处理器应该用的是模板方法,通过钩子将用户的操作加入到模板中去。何不自己写一个事件处理器来完成我们自己的定制操作,代码如下:


public class ManElementHandler implements ElementHandler {
public String mdbName;
­
public ManElementHandler(){

}
­
public ManElementHandler(String mdbName){
this.mdbName = mdbName;
}
­
public boolean saveMan(Element element, String mdbName){
return true;
}
­
public void onEnd(ElementPath arg0) {
Element row = arg0.getCurrent();
Element rowSet = row.getParent();
Document document = row.getDocument();
Element root = document.getRootElement();
Iterator it = root.elementIterator();
while(it.hasNext()){
Element element = (Element)it.next();
System.out.println(" id : " + element.elementText("id") + " name : " + element.elementText("name"));
saveMan(element, this.mdbName);
}
row.detach();
}
public void onStart(ElementPath path) {

}
}

下面给出完整的实例代码。该实例首先创建一个xml文档,然后读取xml文档中的数据并将数据写入Access数据库中。测试时使用的文件大小为125M未发生内存溢出。

//*****************************************************************************************************************
package com;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* 获取Access数据库的连接
* @author 佛山无影脚
* @version 1.0
* Jul 7, 2008 4:35:49 PM
*/
public class AccessMDBUtil {
public static Connection connectMdb(String mdbName) {
if(mdbName == null mdbName.equals("")){
return null;
}
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dburl ="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+mdbName;
Connection conn=DriverManager.getConnection(dburl);
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
//*******************************************************************************************************************
//*******************************************************************************************************************
package com;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.ElementHandler;
import org.dom4j.ElementPath;
/**
* 定制的事件处理器
* @author 佛山无影脚
* @version 1.0
* Jul 7, 2008 4:35:49 PM
*/
public class ManElementHandler implements ElementHandler {
public String mdbName;//数据库名称 含路径
­
public ManElementHandler(){

}
­
public ManElementHandler(String mdbName){
this.mdbName = mdbName;
}
­
/**
*将Element节点数据保存到数据库
*@param element 遍历XML文档时的当前节点
*@param mdbName 数据库名称 含路径
*@return
*/
public boolean saveMan(Element element, String mdbName){
System.out.println(" the method saveMan in ManElementHandler is execute!");
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
conn= AccessMDBUtil.connectMdb(mdbName);
stmt=conn.createStatement();
String sql = "insert into mans(id,name) values(" + element.elementText("id") + ",'" + element.elementText("name") + "')";
stmt.executeUpdate(sql);

} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

return true;
}
­
public void onEnd(ElementPath arg0) {
Element row = arg0.getCurrent();
Element rowSet = row.getParent();
Document document = row.getDocument();
Element root = document.getRootElement();
Iterator it = root.elementIterator();
while(it.hasNext()){
Element element = (Element)it.next();
System.out.println(" id : " + element.elementText("id") + " name : " + element.elementText("name"));
saveMan(element, this.mdbName);
}
row.detach();
}
public void onStart(ElementPath path) {

}
}
//*************************************************************************************************************************
//*************************************************************************************************************************
package com;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* 测试
* @author 佛山无影脚
* @version 1.0
* Jul 7, 2008 4:35:49 PM
*/
public class ManTest {
/**
* 创建man节点
* <man><id>1</id><name>佛山无影脚</name></man>
* @param id
* @param name
* @return
*/
public Element createManElement(Long id,String name){
Element manElement = DocumentHelper.createElement("man");
manElement.addElement("id").addText(id.toString());
manElement.addElement("name").addText(name);
return manElement;
}
­
/**
* 数据写入xml文件
* @param filePath 目标xml文件的存放路径
* @return
*/
public boolean writeXML(String filePath){
XMLWriter out;
try {

/*
* 创建XMLWriter对象,设置XML编码,解决中文问题。
*/
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("GBK");
out = new XMLWriter(new FileWriter(filePath),outputFormat);


out.startDocument();
Element rootElement = DocumentHelper.createElement("mans");
out.writeOpen(rootElement);

/*
* 向mans节点写入子节点
*/
for(int i=0 ; i<1000000 ; i++){
Element man = this.createManElement(new Long(i), "shuhang"+i);
out.write(man);
System.out.println(" the loop index is : " + i);
}

out.writeClose(rootElement);
out.endDocument();

out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (SAXException e) {
e.printStackTrace();
return false;
}
}
­
/**
* 从xml文件中读取数据,并将数据写入Access数据
* @param filePath xml文件的存放路径
* @return
*/
public boolean readXML(String filePath){

ManElementHandler manElementHandler = new ManElementHandler("F:\\dom4j\\xmlTest.mdb");
SAXReader reader = new SAXReader();
reader.addHandler( "/mans/man", manElementHandler);
Document document = null;
try {
File file = new File(filePath);
document = reader.read(file);
} catch (DocumentException e) {
e.printStackTrace();
return false;
}
return true;
}
­
­
public static void main(String[] args){
XMLReader reader = null;
long startTime = System.currentTimeMillis();
ManTest mantest = new ManTest();

mantest.writeXML("f:\\dom4j\\mans.xml");
mantest.readXML("f:\\dom4j\\mans.xml");

long endTime = System.currentTimeMillis();
System.out.println(" is end! the millis is : " + (endTime - startTime));

}
}
//*************************************************************************************************************************


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/shuhang1106/archive/2008/07/09/2627581.aspx

Monday, December 7, 2009

Access jboss from other servers

While starting the server pass the IP address using the -b option. For eg: if you want to access the page using IP address, start the servers using the following command.

run.bat -b 192.168.66.1

Where 192.168.66.1 is your IP address or if you want it to be for all the IPs instead of one, use

run.bat -b 0.0.0.0

Wednesday, December 2, 2009

JAVA实现SFTP实例

首先需要下载第三方jar包:jsch-0.1.42.jar

下面是具体的实现类,很简单的:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

/**
* @author YangHua
* 转载请注明出处:http://www.xfok.net/2009/10/124485.html
*/
public class MySFTP {

/**
* 连接sftp服务器
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
System.out.println(”Session created.”);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put(”StrictHostKeyChecking”, “no”);
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println(”Session connected.”);
System.out.println(”Opening Channel.”);
Channel channel = sshSession.openChannel(”sftp”);
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println(”Connected to ” + host + “.”);
} catch (Exception e) {

}
return sftp;
}

/**
* 上传文件
* @param directory 上传的目录
* @param uploadFile 要上传的文件
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file=new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
* @param sftp
*/
public void download(String directory, String downloadFile,String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file=new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 删除文件
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 列出目录下的文件
* @param directory 要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException{
return sftp.ls(directory);
}

public static void main(String[] args) {
MySFTP sf = new MySFTP();
String host = “192.168.0.1″;
int port = 22;
String username = “root”;
String password = “root”;
String directory = “/home/httpd/test/”;
String uploadFile = “D:\\tmp\\upload.txt”;
String downloadFile = “upload.txt”;
String saveFile = “D:\\tmp\\download.txt”;
String deleteFile = “delete.txt”;
ChannelSftp sftp=sf.connect(host, port, username, password);
sf.upload(directory, uploadFile, sftp);
sf.download(directory, downloadFile, saveFile, sftp);
sf.delete(directory, deleteFile, sftp);
try{
sftp.cd(directory);
sftp.mkdir(”ss”);
System.out.println(”finished”);
}catch(Exception e){
e.printStackTrace();
}
}
}

Tuesday, December 1, 2009

Get ApplicationContext from everywhere

Create a static ApplicationContextProvider class to hold the ApplicationContext:

package com.abc;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;

public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// Assign the ApplicationContext into a static variable
this.applicationContext = applicationContext;
}
}

Initialize the new bean in applicationContext.xml:
<bean id=”applicationContextProvider” class=”com.abc.ApplicationContextProvider”></bean”>

Get applicationContext:

ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
this.setDispatchManager((DispatchManager)ctx.getBean("dispatchManager"));