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();
}