2009年5月15日 星期五

regex網頁版測試工具

regexpal
http://regexpal.com/

在下方貼上要測試的文字
在上方寫RegEx語法

2009年5月7日 星期四

apache commons httpclient 送出 multipart post 寫法

public byte[] uploadMessage(File fileToUpload, UPLOAD_FILE_TYPE type, int[] messageIds) {
byte[] response = null;
try {
// new method
PostMethod postHttpMethod = new PostMethod(webappUrl + uploadFileUrl);
// prepare
// key-value part
Part fileNamePart = new StringPart("fileName", fileToUpload.getName(), "UTF-8");
Part typePart = new StringPart("type", type.toString(), "UTF-8");
StringBuffer strbuf = new StringBuffer();
for (int i = 0; i < messageIds.length; i++) {
strbuf.append(messageIds[i]);
if (i != messageIds.length) {
strbuf.append(",");
}
}
Part messageIdsPart = new StringPart("messageIds", strbuf.toString(), "UTF-8");
// file part
Part filePart = new FilePart("content", fileToUpload);
// multipart
Part[] parts = new Part[] { fileNamePart, typePart, messageIdsPart, filePart };
MultipartRequestEntity multipartEntity = new MultipartRequestEntity(parts, postHttpMethod.getParams());
postHttpMethod.setRequestEntity(multipartEntity);
// execute
try {
httpclient.executeMethod(httpMethod);
response = httpMethod.getResponseBody();
} catch (HttpException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
httpMethod.releaseConnection();
}
return response;
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
}
return response;
}

JFrame的最小化與還原

使用JFrame的setState方法:
public void setState(int state)
state 的值可以是 Frame.NORMAL(還原) 或 Frame.ICONIFIED(最小化)

另外:
JFrame還有 toFront() 及 toBack() 方法可以調整前後,
但必須在 Frame.NORMAL 狀態下才有效。

toFront() 讓 JFrame 到最前面不被其他視窗擋住。

2009年5月4日 星期一

以vim進行檔案編碼轉換

首先必須確定vim有支援multi_byte
開啟vim後輸入
:echo has('multi_byte')
如果結果為1則表示有支援

在vim下要以指定的encoding開啟某一檔案
:e ++enc=

在vim下要以指定的encoding儲存某一檔案
:w ++enc=

例:以vim開啟一個ucs-2le編碼的檔案,並轉存成utf-8編碼。
:e ++enc=ucs-2le /tmp/file_ucs2le.csv
:w ++enc=utf-8 /tmp/file_utf8.csv

ps.ucs-2le為windows下用的unicode編碼

2009年4月22日 星期三

java 的 odt 轉換工具 JODConverter

官方網頁
http://www.artofsolving.com/opensource/jodconverter

首先啟動openoffice的服務模式,最簡單的方式是,到openoffice安裝目錄下的program,如:
C:\Program Files\OpenOffice.org 3\program執行
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

可以使用 netstat -a 檢查 8100 port 是否有在 LISTENING
下載 jodconverter-2.2.2.zip 並將裡面的 lib 下的 jar放到classpath下

轉換的程式碼:
public static void main(String[] args) throws Exception {
File inputFile = new File("test.odt");
File outputFile = new File("test.doc");

// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();

// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);

// close the connection
connection.disconnect();
}

jodconverter是透過輸入的副檔名來做為轉換的依據的。

2009年4月16日 星期四

Junit 4.5 的 TestAll寫法

Junit 4.5 的 TestAll寫法

@RunWith(Suite.class)
@SuiteClasses( { TestAllDao.class, TestAllController.class })
public class TestAllXdna {

}

2009年4月11日 星期六

hinet 中華電信 DNS 列表

DNS Server 中華電信的全區 168.95.1.1
中華電信分區如下
北區 DNS 139.175.55.244(主) 139.175.252.16(次) 適用地區範圍:台北, 桃園, 新竹, 宜蘭, 花蓮, 苗栗
中區 DNS 139.175.150.20(主) 139.175.55.244(次) 適用地區範圍:台中, 彰化, 南投, 雲林
南區 DNS 139.175.10.20(主) 139.175.55.244(次) 適用地區範圍:高雄, 台南, 嘉義, 屏東, 台東

2009年4月8日 星期三

spring 3.0.0.M2 整合 Apache Tiles 2 模版

一、
tiles相關的jar加到WEB-INF/lib,以3.0.0.M2的情型,必需下載tiles-2.0.7的版本,
tiles-2.1.x以上的版本,尚有問題,tiles本身也相依commons-beanutils 及 commons-digester,
都可以在Tiles-2.0.7-bin.tar.gz下載得到。固與Tiles相關的jar有:
commons-beanutils-1.7.0.jar
commons-digester-1.8.jar
commons-logging-1.1.1.jar
tiles-api-2.0.7.jar
tiles-core-2.0.7.jar
tiles-jsp-2.0.7.jar

二、
在spring的bean設定檔稍做修改,
a在viewResolver將InternalResourceViewResolver改用UrlBasedViewResolver
b並加入viewClass 設定為 org.springframework.web.servlet.view.tiles2.TilesView
c加入 TilesConfigurer
如下:
<!-- test jsp view -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<!-- Tiles 模版 -->
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/templates.xml</value>
</list>
</property>
</bean>

三、
在上面的TilesConfigurer bean中指定了/WEB-INF/defs/templates.xml這個模版定義檔
建立templates.xml內容為:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="/WEB-INF/jsp/test.jsp" template="/WEB-INF/jsp/templates/layout.jsp">
<put-attribute name="title" value="TPMA Tiles tutorial homepage" />
<put-attribute name="header" value="/WEB-INF/jsp/templates/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/jsp/templates/menu.jsp" />
<put-attribute name="body" value="/WEB-INF/jsp/body.jsp" />
<put-attribute name="footer" value="/WEB-INF/jsp/templates/footer.jsp" />
</definition>
</tiles-definitions>

四、
上面的定義了當Controller的return
return new ModelAndView("test", "test", model);
的時後,test會被UrlBasedViewResolver組合成/WEB-INF/jsp/test.jsp,而TilesView則會到,
templates.xml找到/WEB-INF/jsp/test.jsp的定義,並根據layout.jsp頁面組合title、header、
menu、body、footer等頁面,layout.jsp的內容如下:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:getAsString name="title" /></title>
</head>
<body>
<table border="0" width="100%" cellspacing="5">
<tr>
<td colspan="2"><tiles:insertAttribute name="header" /></td>
</tr>
<tr>
<td width="140" valign="top"><tiles:insertAttribute name="menu" /></td>
<td valign="top" align="left"><tiles:insertAttribute name="body" /></td>
</tr>
<tr>
<td colspan="2"><tiles:insertAttribute name="footer" /></td>
</tr>
</table>
</body>
</html>

以tiles:getAsString插入templates.xml定義的value為文字
以tiles:insertAttribute插入templates.xml定義的value的網頁

五、
準備templates.xml中定義的其他jsp頁面。

六、
每個網頁一樣可以使用EL取得model的值
${test.name } ${test.passwd }

2009年3月26日 星期四

wine 下好用的 winetricks script

在linux上裝wine可以模擬 windows 環境,並執行 *.exe程式。
然而windows上許多api/dll,官方的wine並不完全包含,必須另外安裝,如:
常用的DirectX、.net等,有一隻script可以幫忙快速安裝這些軟體,叫作winetricks:

winetricks主站:
http://wiki.winehq.org/winetricks

下載:
wget http://www.kegel.com/wine/winetricks

winetricks必須用到cabextract套件來解開*.CAB檔,所以必須安裝cabextract套件:
aptitude install cabextract

執行:
sh winetricks dotnet11 directx9 ie6 firefox3

即安裝 .net-1.1 directx9 ie6 firefox3

使用 apache mina 框架建立網路程式

server:
public class FlavorServer {

private int PORT = 6275;

public void startServer() {
try {
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
IoAcceptor acceptor = new SocketAcceptor();
SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.getFilterChain().addLast("logger", new LoggingFilter());
cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

acceptor.bind(new InetSocketAddress(PORT), new FlavorServerHandler(), cfg);
System.out.println("MINA Flavor server started.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

client:
public class FlavorClient {
private int PORT = 6275;

public void startClient() {
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
IoConnector connector = new SocketConnector();
SocketConnectorConfig cfg = new SocketConnectorConfig();
cfg.getFilterChain().addLast("logger", new LoggingFilter());
cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
connector.connect(new InetSocketAddress(PORT), new FlavorClientHandler(), cfg);
}
}

無論是 server 或 client 用到的 Handler 都是繼承 IoHandlerAdapter 物件的子類別:
public class FlavorServerHandler extends IoHandlerAdapter
public class FlavorClientHandler extends IoHandlerAdapter
並override IoHandlerAdapter所提供的方法,就可以進行網路的溝通,如:

@Override
public void messageReceived(IoSession session, Object message) throws Exception {
String msgStr = (String) message;
if (msgStr.trim().equalsIgnoreCase("bye")) {
session.close();
return;
}
if (count == 1000) {
session.write("quit");
} else {
session.write(count);
}
count++;
System.out.println(msgStr);

}

@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("client session created");
if (session.getTransportType() == TransportType.SOCKET) {
((SocketSessionConfig) session.getConfig()).setReceiveBufferSize(2048);
}

session.setIdleTime(IdleStatus.BOTH_IDLE, 10);
}

apache2 建立新的 Virtual Host site

#aptitude install apache2
安裝好apache2後,預設只有/var/www/做為default site,
可以在 /etc/apache2/site-available/default 進行設定,
如果想增加一個 site 並綁定到不同的 根目錄 位置及 Virtual Host domain,
首先必須先去擁有的domain設定 CNAME 一個要用 domain 如:
storage CNAME www.bennu.tw.
也就是增加一個 storage.bennu.tw 但storage 的ip和 www.bennu.tw 其實是一樣的。

再到/etc/apache2/site-available/ 建立一個storage.bennu.tw檔案
vim storage.bennu.tw 內容為:

<VirtualHost *:80>
ServerName storage.bennu.tw
ServerAdmin muchu1983@storage.bennu.tw
DocumentRoot /storage/
ErrorLog /var/log/apache2/storageError.log
CustomLog /var/log/apache2/storageAccess.log common
</VirtualHost>

再將這個檔案建立一個連結在 /etc/apache2/site-enabled/ 下
ln -s /etc/apache2/site-availiable/storage.bennu.tw /etc/apache2/site-enabled/storage.bennu.tw

再來要記得用a2ensite enable 這個新的 site
a2ensite storage.bennu.tw

最後重新啟動 apache2 服務即可
/etc/init.d/apache2 restart

重新啟動後,用網址連storage.bennu.tw所看到的網站的根目錄,
就是/storage/* 下的資料。

spring app context 的 event 通知

spring 的 ApplicationContext 或 WebApplicationContext 在啟動/關閉時,會發出許多事件,
這些事件都是org.springframework.context.ApplicationEvent的子類別

ContextClosedEvent -
在ApplicationContext關閉時發佈事件。
ContextRefreshedEvent -
在ApplicationContext初始或Refresh時發佈事件。
RequestHandledEvent -
在Web應用程式中,當請求被處理時,ApplicationContext會發佈此事件。

如果需要對這些事件做處理,必須實作org.springframework.context.ApplicationListener介面,
並在bean-config.xml定義實作ApplicationListener的bean,一但有事件發生,ApplicationContext
即會通知bean-config.xml中的所有ApplicationListener做處理。

2009年3月16日 星期一

lxde autostart 自動啟動設定

到/usr/share/applications/下找到需要的啟動檔案,
如pidgin的啟動檔案為pidgin.desktop
將pidgin.desktop copy 到 ~/config/autostart/pidgin.desktop 即可
如果沒有autostart資料夾就自行建立。

2009年3月10日 星期二

spring framework mvc 處理編碼的 filter

只要在web.xml加入下列的filter
就可以統一將get/post的url,textfield的內容都轉換為utf-8編碼。

<!-- encoding -->
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>

2009年3月8日 星期日

善用/etc/hosts及ipconfig 綁定多個ip

如果沒有經過任何設定,當使用 domain name 存取一個對方的主機時,等於是以外部ip傳遞封包
封包一定是經由網域的外部出去internet再到對方的主機,即使對方的主機是和自已主機同網域。
例如:
同一個hub的兩個孔的主機,各指定自己的domain name為ftp.bennu.tw和www.bennu.tw
ftp到www封包路徑 ftp -> hub -> internet -> hub -> www,速度會變得很慢。

這個情況下可以將ftp和www的網卡,假設都是eth0,各綁定第二個內部ip
ftp:
#ifconfig eth0:0 192.168.1.100
www:
#ifconfig eth0:0 192.168.1.101

然後再將各自的/etc/hosts加入:
ftp:
192.168.1.101 www.bennu.tw www
www:
192.168.1.100 ftp.bennu.tw ftp

這樣一來即使使用domain name傳遞封包,路徑就不會再繞到internet,
而是僅僅在內部的網域內傳遞,速度快得多了:
ftp -> hub -> www

2009年3月7日 星期六

python的中文註解

必須在#!/usr/bin/env python下加入:
#-*- coding: utf-8 -*-
否則當python直譯器遇到中文字時會抱怨非ANSI字元,顯示以下訊息:
SyntaxError: Non-ASCII character .....

2009年2月23日 星期一

掃描 XSANE-HP Deskjet

安裝 xsane
sudo aptitude install xsane
並加入 scanner group
sudo usermod -G scanner -a muchu1983
之後在X的功能選單下就可以使用XSane進行掃描。

2009年2月16日 星期一

使用 springframework 3.0.0 建立 RESTful 網路應用程式 Controller

RESTful是一種新的Webapp設計概念,可以減少很多傳統Webapp程式的code,
傳統Webapp以一個 url mapping 到一個 service ,如 java servlet 或 spring controller,
以操作資料庫的 CRUD 四個步驟來說,一張資料表至少就需要4個 service 命令來完成實作。
也就是要分別對四個 url 進行操作。

RESTful 則將資料當成一種資源,利用 http 原本就有的 Get、Post、Delete、Put…
等七個 method ,對同一個 url 進行操作,如下圖。
















spring 在 3.0版之後的 spring MVC 框架就有提供 RESTful 相關的支援,並使用 java 5.0 的
annotation 語法,用起非常簡單方便。

spring 3.0.0 相依的 jar有:
antlr-3.0.1.jar
asm-3.1.jar
asm-common-3.1.jar
commons-logging.jar
log4j-1.2.13.jar

簡單的 RESTful 範例 /rest/{i}/{n} : i、n 均為變數


web.xml 加入 DispatcherServlet 的servlet定義,並mapping到 /rest/*

<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/conf/spring-restful-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

需注意:
DispatcherServlet 因為被 mapping 到 /rest/* 所以在 DispatcherServlet 帶起來的WebApplicationContext 之下 做mapping時, "/"符號就等於 "/rest/"這一層 ,
也就是說 html form action 的 "/rest/1/2/3/4" mapping 要寫成 "/1/2/3/4"。

在 web.xml 指定了 /WEB-INF/conf/spring-restful-config.xml 這個檔為 spring bean config
內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

<!-- test jsp view -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<bean id="testController"
class="com.transtep.restful.server.framework.spring.controller.TestController">
</bean>
</beans>

spring-restful-config.xml 檔裡有 2 個 bean 負責 spring 2.5 開始有的 annotation MVC功能,
DefaultAnnotationHandlerMapping -> 處理 class level 的 annotation。
AnnotationMethodHandlerAdapter -> 處理 method level 的 annotation。
底下再定義 Controller 的 bean class,這些 bean 就可以用 annotation 的語法來定義了。
如這裡的 TestController :

@Controller
public class TestController {

@RequestMapping(value = "/1/{ii}/{nn}", method = RequestMethod.GET)
public ModelAndView getTest(@PathVariable(value = "ii") String id, @PathVariable(value = "nn") String number) {
System.out.println("run 1");
Map model = new HashMap();
model.put("message", "id " + id + "\n" + "number " + number);
return new ModelAndView("test", model);
}

@RequestMapping(value = "/1/{ii}/{nn}", method = RequestMethod.POST)
public ModelAndView postTest(@PathVariable(value = "ii") String id, @PathVariable(value = "nn") String number) {
Map model = new HashMap();
model.put("message", "id " + id + "\n" + "number " + number);
return new ModelAndView("test", model);
}
}

首先在 class 宣告上以 @Controller 定義這是一個 Controller (不需要再implements Controller)
再以
@RequestMapping 定義各別的 method 的 URI 、 method mapping,特別是 URI 可以{}
定義成變數的格式,再配合 @PathVariable 將變數的實際值綁到 method的參數上,同時根據
方法的參數型別不同,自動轉換成正確的型別。

上面的例子以 get /rest/1/123/456 則會執行 getTest() 方法,id=123,number=456
而如果以 post /rest/1/456/789 則會執行 postTest() 方法,id=456,number=789

2009年2月10日 星期二

在 xorg.conf 檔調整顯示器的水平垂直更新率

每個場商的每個螢幕的設定範圍都不同,即使設定不正確螢幕也不一定就沒畫面,
有可能是在執行某些需要特殊畫面更新率的軟體,例如640x480解析度的遊戲時,
會因為更新率不支援(其實是沒設定好),而造成畫面一片黑,出現 out of range 等等。

先查詢螢幕的正確水平,垂直更新率。
編輯 /etc/X11/xorg.conf
找到 Section "Monitor" 裡面有 HorizSync VertRefresh 兩項,
各自填入查到的 水平(HorizSync)、垂直(VertRefresh) 更新率,
有時可能填的範圍要比查詢到的還小一點,50.0 - 80.0 可以只填 30.0 - 70.0就好。
更新後 startx 進入X,切換一下解析度,看看能不能正常顯示。

2009年2月8日 星期日

lenny中使用wine設定執行魔獸爭霸3

首先安裝wine就不多說了,我使用的是1.0.1-1

安裝好wine後,先執行winecfg設定一下
1.windows版本的地方選windows 2000
2.函式庫->已有的函式庫頂替 維持空的
3.顯示 -> 模擬一個虛擬桌面 打勾 800x600
4.儲存槽 -> 按一下自動偵測 讓wine對應linux的路徑到磁碟機代號

開始安裝Warcraft3,如果已經有安裝好的則直接copy過來linux下,跳過這一步
mount主程式的光碟,並在光碟的掛載點下執行wine install.exe
mount資料片的光碟,並在光碟的掛載點下執行wine install.exe

更新patch
下載 http://todian.myweb.hinet.net/ 提供的傻瓜包來更新
更新完成後也會變成免光碟版,一樣以 wine 執行更新程式,
wine warcraft_patch_upgrade_122a_v3.exe
選擇Warcraft III的安裝(或copy)資料夾,由於傻包完成後會自動執行遊戲,
但wine的Directx3D還不夠完整,現在執行畫面可能一片黑,先想辦法關掉遊戲
大絕招是ctrl-alt-←關掉整個X再startx

透過安裝步驟 wine的register表也會自動加入Warcraft資料,
但如果是從別的地方copy的,就要手動去新增wine register裡的資料
執行 regedit
找到下列的key,如果沒有就按右鍵新增key(一個key就是一層資料夾)
HKEY_CURRENT_USER\Software\Blizzard Entertainment\Warcraft III
在右側建立名為Gfx OpenGL的DWORD值,Value data設置為1
(這個regedit主要設定War3以opengl執行遊戲)

現在回到 Warcraft III 資料夾下,執行
wine War3.exe -opengl或wine War3.exe -x11
順利的話會在wine虛擬桌面下看到開場動畫,等動畫播完,遊戲畫面會一片黑
滑鼠點一下黑色的遊戲畫面,則遊戲界面就會出來。先離開遊戲

再次執行 winecfg
將 顯示 -> 模擬一個虛擬桌面 打勾取消掉
重新回到Warcraft III 資料夾下,執行
wine War3.exe -opengl或wine War3.exe -x11
就可以以全螢幕進行遊戲了。
(因為開場動畫沒有用虛擬桌面的話就不能播)