2011年12月26日 星期一

[轉貼] Java Lists: Group by element property (as Ruby group_by method)


This is a very funny function, similar to group_by from Ruby.
It takes a collection and it transforms to a hash, having keys the property *groupBy*, and values the objects having that property.
A usage example:
collectionToHash(users, "name"); //returns a hash where the keys are the distinct user names, and the values are lists of users having that property.

public static SortedMap<String, ArrayList<Object>> collectionToHash(Collection list, String groupBy){
 TreeMap<String, ArrayList<Object>> hash = new TreeMap<String, ArrayList<Object>>();
 for(Object obj : list){
 Class<?> klass = obj.getClass();
 String groupByGetter = groupBy;
 try { // dynamic method invocation
   Method m = klass.getMethod(groupByGetter);
   Object result = m.invoke(obj);
   String resultAsKey = result.toString();
   ArrayList<Object> arrayList;
   if(hash.containsKey(resultAsKey)){
     arrayList = hash.get(resultAsKey);
   } else{
     arrayList = new ArrayList<Object>();
     hash.put(resultAsKey, arrayList);
   }
   arrayList.add(obj);
 }catch (SecurityException e){
   .....
 }catch (NoSuchMethodException e){
   ....
 }
 return hash;
}
轉貼自
http://vladzloteanu.wordpress.com/2009/05/20/java-lists-group-by-element-property-as-ruby-group_by-method/

2011年11月15日 星期二

迴圈取得Map(Key,Value)


JDK1.5

Map m = new HashMap();

for (Object o : map.keySet()) {

map.get(o);

}



JDK1.4
Map map = new HashMap() ;

Iterator it = map.entrySet().iterator() ;

while (it.hasNext())

{

Map.Entry entry = (Map.Entry) it.next() ;

Object key = entry.getKey() ;

Object value = entry.getValue() ;

}



2011年11月7日 星期一

ConversionException: No value specified for 'Date'

轉載自 http://www.mail-archive.com/user@commons.apache.org/msg02246.html





原因:當JavaBean用到了Date等非內建型態時,如果Object為NULL則會出現此異常。

解決方法:
You have a choice of two flavours for copying properties in BeanUtils:


1) Usng PropertyUtils copyProperties() method[1] - this just copies

any properties unchanged

2) Using BeanUtils copyProperties() method[2] - copies AND converts

properties - so for example, if theres a property called "foo" of type

String in the source and a property called "foo" of type Integer in

the destination then it tries to convert the String to an Integer

using the Converter registered for Integers.



If you don't need conversion then you can switch to using

PropertyUtils. If however you have some conversion needs, but you

don't want it to throw an exception when a value is "null" (which is

the default behaviour) - then you can configure a converter for Date

which has a default value. So for example, if you wanted a default of

"null" for Dates, then something like the following:



java.util.Date defaultValue = null;

DateConverter converter = new DateConverter(defaultValue);

ConvertUtils.register(converter, java.util.Date.class);



Then when you call BeanUtils.copyProperties() it should no longer

throw an exception.



[1] http://tinyurl.com/4rc5ho

[2] http://tinyurl.com/44csva

2011年11月3日 星期四

檔案下載時檔名在ie和firefox下面表現不一致問題

String agent = request.getHeader("USER-AGENT");
String fileName = desc+".xls";
 if (null != agent && -1 != agent.indexOf("MSIE")){
    fileName = java.net.URLEncoder.encode(fileName, "UTF8");
 }else if (null != agent && -1 != agent.indexOf("Mozilla")){
    fileName = MimeUtility.encodeText(fileName, "UTF8", "B");
 }
 response.setContentType("application/vnd.ms-excel;charset=UTF-8");
 //response.setHeader("Cache-Control", "no-cache");
 response.setHeader("Pragma", "no-cache");
 response.setDateHeader("Expires", 0);
 response.setHeader("Content-disposition" , "attachment; filename=" + fileName);

2011年8月22日 星期一

JNLP JAR 簽署製作步驟

1。用keytool來創建一個密匙(同時指定時效,多久會過期,默認只給6個月)

2。用JARSigner用此密匙為JAR簽名。

可以用同一個密匙來為多個JAR簽名。


P.S. keytool、JARSigner必須設定好環境變數將Path加入java bin path ex:C:\Program Files\Java\jdk1.6.0_20\bin 才可在command mode呼叫



注意:大小寫,簽名一致,數字簽名過期

為什麼JAR要被簽名?當用戶啟動一個Java Network Launching Protocol (JNLP,Java網絡加載協議)文件或使用一個applet時,這個JNLP或applet可能請求系統提供一些非一般的訪問。比如“文件打開”等進行這樣的請求,就需要簽名的JAR。

如果它是匿名的,系統會詢問用戶是否打算信任JAR的簽署者。

1.首先生成簽名文件,執行完成後,會在使用者目錄內生成一個.keystore的密鑰文件,2kByte大小。

yourProj是別名keypass後面是密文密碼,keystore密碼是存儲密碼(要改變此文時需要輸入確認此密碼)

在dos command mode(cmd)提示狀態下輸入

>keytool -genkey -alias yourProj -keypas

s yourCompany:Kouling


Java Web Start and JNLP

JWS介紹請看 WIKI
http://en.wikipedia.org/wiki/Java_Web_Start


An example JNLP file

Example 1

The JNLP file obtains and locates files in a manner similar to a Web browser, using only URLs and not specific file names. Listing 2 shows an example JNLP file.




<?xml version="1.0" encoding="UTF-8"?>
<jnlp codebase="http://www.companySite.com/javaApp">
<href="clientapp.jnlp">
<information>

<vendor>Company name</vendor>
<icon href="companyLogo.gif">
<homepage ref="reference/tips.html">
<offline-allowed>
</information>
<resources>
<j2se version="1.3/">
<jar href="companySong.jar" part="music" download="lazy">
</resources>
<resources os="Windows">
<nativelib="windowiconsforwindowos.jar" part="windowIcons" download="eager">
<application-desc class="com.company.ui.Client">
<security>
<all-permissions>
</security>
</jnlp>




Example 2


<xml version="1.0" encoding="UTF-8">
<jnlp codebase="http://localhost/webstart/" href="piao.jnlp" spec="1.0+">
<information>

<vendor>piao無所不在</vendor>
<homepage href="http://localhost">
<icon href="piao.jpg">
<description>web start test</description>
</information>
<offline-allowed>

<security>
<all-permissions>
</security>
<resources>
<j2se version="1.4+">
<jar href="flowsheet.jar">
</resources>
<application-desc class="piao.fs.test.Main">
</APPLICATION-DESC>
</jnlp>


web server 的 mime type mapping 裡也記得要加入 .jnlp file mapping。

<mime-mapping>
<extension>jnlp</extension>
<mime-type>application/x-java-jnlp-file</MIME-TYPE>
</mime-mapping>



Reference:
http://www.ibm.com/developerworks/java/library/j-webstart/
http://www.mkyong.com/java/java-web-start-jnlp-tutorial-unofficial-guide/
http://www.javaworld.com.tw/roller/piaoyi/entry/java_web_start_and_jnlp



2011年6月14日 星期二

[引用] JACOB操作WORD

import java.util.HashMap;
import java.util.Iterator;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class Java2word
{
private boolean saveOnExit;
/**
* word文檔
*/
Dispatch doc = null;
/**
* word運行程式物件
*/
final static ActiveXComponent word;
/**
* 所有word文檔
*/
final static Dispatch documents;
static
{
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false));
documents = word.getProperty("Documents").toDispatch();
}
/**
* 構造函數
*/
public Java2word()
{
saveOnExit = true;
}
/**
* 打開文件
*
* @param inputDoc
* String 要打開的檔,全路徑
* @return Dispatch 打開的文件
*/
public Dispatch open(String inputDoc)
{
return Dispatch.call(documents, "Open", inputDoc).toDispatch();
}

2011年4月28日 星期四

informix for linux安裝

第一步:下載
ids 9.4 for linux:
ftp://ftp.youngcow.net/Special/Database/DatabaseServer/Informix/InformixDynamicServerVersion9.4/IIUG-IDS-9.4-linux.zip
這個線程有限制
http://202.96.110.133/informix/ids9.4/IIUG-IDS-9.4-linux.zip
這個更快,視網絡定吧;

csdk for linux:
ftp://ftp.software.ibm.com/software/data/informix/downloads/clientsdk.2.81.UC2.LINUX.tar

第二步:linux搭建安裝informix的環境

建立informix組:groupadd -g 20000 informix

建立informix用戶:useradd -u 20000 -g 20000 -d /home/informix -m informix

修改informix用戶環境變量:
修改.bash_profile文件增加以下環境變量

INFORMIXDIR=/home/informix
INFORMIXSERVER=cs_dbs
ONCONFIG=onconfig.cs
DBDATE=MDY4*
LD_LIBRARY_PATH=$INFORMIXDIR/lib:$INFORMIXDIR/lib/esql:$LD_LIBRARY_PATH
export INFORMIXDIR INFORMIXSERVER ONCONFIG LD_LIBRARY_PATH
PATH=$PATH:$INFORMIXDIR/bin
export PATH
這個就不用偶解釋了吧;

第三步:準備安裝文件

2011年4月27日 星期三

Tar 備份筆記

Tar 備份且排除不想備份的目錄或檔案

要備份的目錄是 aaa
不想要備份的是 aaa 裡面的 bbb 子目錄

於是我們加上參數 --exclude=不想要備份的目錄名稱,如果某個檔案不想備份也可以在此加入完整路徑及檔名

最後的 tar 指令如下

tar cvf aaa.tar --exclude=aaa/bbb aaa/

這樣就不會將 bbb 目錄備份進來了

-----------------------------------------

Tar 備份特定檔案

tar cvf aaa.tar aaa/*.jpg

2011年4月8日 星期五

在Java中操作XML - JAXB使用教學

JAXB簡介
JAXB的全名是Java Architecture for XML Binding,是Sun官方發展的技術,提供Java物件和XML文件自動mapping的機制,使我們能夠很容易的操作XML而不用去爬樹 (parse DOM tree)或是免除為了哪個節點之後要新增哪個節點又應該是哪一種內容的苦惱。
目前JAXB是屬於Java Web Services Developer Pack的實做套件之一,Sun官方預計在即將釋出的Java SE 6將其包裝在裡頭,因此到時候我們就不必再特地下載JAXB的實做套件了。



2011年2月24日 星期四

java錯誤:java.util.Calendar輸出月份不對的問題

使用java.util.Calendar類的方法get方法時,傳入Calendar的靜態變量Calendar.MONTH作為參數。

我們希望得到的結果是當前日曆的月份。

但是我得到的月份數值跟正常月份不符,調試結論:

java.util.Calendar輸出的年份和日期都是和現實一樣的。

唯獨月份的計數是從0開始的,比如當前的8月,會輸出數值7。

所以在計算時,需要+1處理。

(tC.get(Calendar.MONTH)+1),輸出即為正常月份

在做tC.set(Calendar.MONTH,2)時,月份的計數也是從零開始的,即當前月為3月,即寫入2。

2011年1月27日 星期四

port 用途說明 (轉載)

port 用途說明


按埠號可分為3大類:
(1)公認埠(Well Known Ports):從0到1023,它們緊密綁定(binding)於一些服務。通常這些埠的通訊明確表明了某種服務的協議。例如:80埠實際上總是HTTP通訊。
(2)註冊埠(Registered Ports):從1024到49151。它們鬆散地綁定於一些服務。也就是說有許多服務綁定於這些埠,這些埠同樣用於許多其他目的。例如:許多系統處理動態埠從1024左右開始。
(3)動態和/或私有埠(Dynamic and/or Private Ports):從49152到65535。理論上,不應為服務分配這些埠。實際上,機器通常從1024起分配動態埠。但也有例外:SUN的RPC埠從32768開始。
0 通常用於分析作業系統。這一方法能夠工作是因為在一些系統中“0”是無效埠,當你試圖使用一種通常的閉合埠連接它時將產生不同的結果。一種典型的掃描:使用IP位址為0.0.0.0,設置ACK位元並在乙太網層廣播。
1 tcpmux TCP Port Service Multiplexer 傳輸控制協定埠服務多路開關選擇器
2 compressnet Management Utility   compressnet 管理實用程式
3 compressnet Compression Process   壓縮進程
5 rje Remote Job Entry     遠端作業登錄
7 echo Echo       回顯
9 discard Discard     丟棄
11 systat Active Users     線上用戶
13 daytime Daytime      時間
17 qotd Quote of the Day    每日引用
18 msp Message Send Protocol    消息發送協定
19 chargen Character Generator   字元發生器
20 ftp-data File Transfer[Default Data]  檔傳輸協定(默認資料口) 
21 ftp File Transfer[Control]    檔傳輸協議(控制)
22 ssh SSH Remote Login Protocol   SSH遠端登錄協定
23 telnet Telnet     終端仿真協定