2009年6月19日 星期五

hibernate 關聯 hbm.xml 設定 範例

many-to-one範例 -
<many-to-one name="targetGroup" column="group_id" class="com.transtep.green.servlet.framework.hibernate.GreenGroup" insert="false" update="false" cascade="save-update" outer-join="true" />

one-to-many範例 -
<set name="relAccExtSet" cascade="all" inverse="true" lazy="true">
<key>
<column name="account_id" />
</key>
<one-to-many class="com.transtep.green.servlet.framework.hibernate.GreenAccountExt" />
</set>

one-to-one範例 -
<one-to-one name="relSauth" class="com.transtep.green.servlet.framework.hibernate.GreenSimpleAuth" cascade="all" property-ref="relAccount" />

<many-to-one name="relAccount" column="account_id" class="com.transtep.green.servlet.framework.hibernate.GreenAccount" insert="false" update="false" cascade="save-update" outer-join="true" unique="true"/>

2009年6月8日 星期一

Spring PropertyPlaceholderConfigurer

PropertyPlaceholderConfigurer 的作用是可以將 spring 的 bean-config.xml 裡的某些資料
抽離出來,放到另外一個 key-value 的 property file 裡,方便統一設定。
先在bean-config.xml裡加入:

<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:green-setting.properties</value>
</property>
</bean>

再建立對應的 green-setting.properties 檔:
com.transtep.green.db.jdbcurl=jdbc:postgresql://db.transtep.com:5432/MARK_GREEN?charSet=utf8
com.transtep.green.db.user=postgres
com.transtep.green.db.password=admin

如此一來就可以在bean-config.xml裡使用${key}變數來設定資料,如:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>org.postgresql.Driver</value>
</property>
<property name="jdbcUrl">
<value>${com.transtep.green.db.jdbcurl}</value>
</property>
<property name="user">
<value>${com.transtep.green.db.user}</value>
</property>
<property name="password">
<value>${com.transtep.green.db.password}</value>
</property>
略....

2009年6月7日 星期日

debian 下的啟動服務設定 script update-rc.d

在 /etc/init.d 中建立一個叫作 zope 的 script , 然後

update-rc.d zope defaults

就會產生以下連結::

Adding system startup for /etc/init.d/zope ...
/etc/rc0.d/K20zope -> ../init.d/zope
/etc/rc1.d/K20zope -> ../init.d/zope
/etc/rc6.d/K20zope -> ../init.d/zope
/etc/rc2.d/S20zope -> ../init.d/zope
/etc/rc3.d/S20zope -> ../init.d/zope
/etc/rc4.d/S20zope -> ../init.d/zope
/etc/rc5.d/S20zope -> ../init.d/zope

2009年6月6日 星期六

hql 的left outter join轉換成sql的結果

hql:
from TpmaAccount as a
left join a.relTpmaStaff as staff with staff.projectId = 1

sql:
select
tpmaaccoun0_.username as username0_0_,
tpmastaff1_.staff_id as staff1_10_1_,
tpmaaccoun0_.password as password0_0_,
tpmaaccoun0_.role as role0_0_,
tpmaaccoun0_.enabled as enabled0_0_,
tpmaaccoun0_.valid_bdate as valid5_0_0_,
tpmaaccoun0_.valid_edate as valid6_0_0_,
tpmaaccoun0_.staff_id as staff7_0_0_,
tpmaaccoun0_.login_date as login8_0_0_,
tpmaaccoun0_.login_cnt as login9_0_0_,
tpmaaccoun0_.login_ip as login10_0_0_,
tpmastaff1_.project_id as project2_10_1_,
tpmastaff1_.first_name as first3_10_1_,
tpmastaff1_.last_name as last4_10_1_,
tpmastaff1_.sex as sex10_1_,
tpmastaff1_.org as org10_1_,
tpmastaff1_.cellphone as cellphone10_1_,
tpmastaff1_.telephone as telephone10_1_,
tpmastaff1_.address as address10_1_,
tpmastaff1_.skype as skype10_1_,
tpmastaff1_.msn as msn10_1_,
tpmastaff1_.email as email10_1_,
tpmastaff1_.remark as remark10_1_
from
public.tpma_account tpmaaccoun0_
left outer join
public.tpma_staff tpmastaff1_
on tpmaaccoun0_.staff_id=tpmastaff1_.staff_id
and (
tpmastaff1_.project_id=1
)

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 .....