2013年9月18日 星期三

JAVA Socket

SocketSever

import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer extends java.lang.Thread{
   private boolean OutServer = false;
   private ServerSocket server ;
   private final int ServerPort = 8765;//要監控的port

   public SocketServer(){
      try{
         server = new ServerSocket(ServerPort);
      }catch(java.io.IOException e){
         System.out.println("Socket啟動有問題 !" );
         System.out.println("IOException :" + e.toString());
      }
   }

  public void run(){
    Socket socket ;
    java.io.BufferedInputStream in ;

    System.out.println("伺服器已啟動 !"  );
    while(!OutServer){
      socket = null;
      try{
        synchronized(server) {
           socket = server.accept();
        }
        System.out.println("取得連線 : InetAddress = " + socket.getInetAddress() );
        //TimeOut時間
        socket.setSoTimeout(15000);

        in = new java.io.BufferedInputStream(socket.getInputStream());
        byte[] b = new byte[1024];
        String data ="";
        int length;
        while((length = in.read(b))>0)//<=0的話就是結束了
        {
        data += new String(b, 0, length);
        }
     
         System.out.println("我取得的值:"+data);
         in.close();
         in = null ;
         socket.close();
      }catch(java.io.IOException e){
          System.out.println("Socket連線有問題 !" );
          System.out.println("IOException :" + e.toString());
      }
    }
  }

  public static void main(String args[]){
       (new SocketServer()).start();
  }
}

SocketClient

import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.BufferedOutputStream;

public class SocketClient {
private String address = "127.0.0.1";// 連線的ip
private int port = 8765;// 連線的port

public SocketClient() {

Socket client = new Socket();
InetSocketAddress isa = new InetSocketAddress(this.address, this.port);
try {
client.connect(isa, 10000);
BufferedOutputStream out = new BufferedOutputStream(client
.getOutputStream());
// 送出字串
out.write("Send From Client ".getBytes());
out.flush();
out.close();
out = null;
client.close();
client = null;

} catch (java.io.IOException e) {
System.out.println("Socket連線有問題 !");
System.out.println("IOException :" + e.toString());
}
}

public static void main(String args[]) {
new SocketClient();
}
}

EWS API


  private ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

  public EWService(String email, String userPwd) throws Exception {
ExchangeCredentials credentials = new WebCredentials(email, userPwd);

service.setCredentials(credentials);
service.setUrl(new URI("https://XXX/ews/Exchange.asmx"));
}

  /*
* 寄信測試
*/
public void sendmailTest() throws Exception {
EmailMessage msg = new EmailMessage(service);
msg.setSubject("Hello world! 哈囉 ~ 世界");
msg.setBody(MessageBody.getMessageBodyFromText("Sent using the EWS Managed API. 由 微軟提供 java api 測試發送"));
msg.getToRecipients().add("test@test.test");
msg.send();
}

完整 EWS API 說明和 sample at http://msdn.microsoft.com/en-us/library/exchange/dd633696(v=exchg.80)

2012年11月27日 星期二

[ ExtJS ] 頁面佈局 Layout 介紹




以下會分別簡單介紹一下這十種由 ExtJS 所提供的佈局方式:
Absolute
Accordion
Anchor
Border
Card
Column
Fit
Form
HBox / VBox
Table

官網Layout範例:http://docs.sencha.com/ext-js/4-1/#!/example/layout-browser/layout-browser.html


★ Layout : 'absolute'

API:Ext.layout.container.Absolute

元件佈局不隨視窗大小變動,十分固定
其子元件必須明確指派 x / y 的位置
若有元件overlay情形,後加的元素會往上疊



★ Layout : 'accordion'

API:Ext.layout.container.Accordion

可將元件 / 容器使用手風琴般的方式摺疊
預設將失去焦點的元件摺疊,並依元件加入順序疊放,只留下標題列
其他需要調整的細部則用 layoutConfig 設定



★ Layout : 'anchor'

API:Ext.layout.container.Anchor

可讓元件大小隨容器改變
兩種表示法:百分比 / 絕對尺寸
只寫一數值則代表寬,高度則由元件自行計算
數值 0 與 100% 同義
絕對尺寸為負值,表偏移量,其寬高指的是該容器內的context寬高



★ Layout : 'border'

API:Ext.layout.container.Border

子元件必須明確指定region

其中,north/south只能設height,west/east只能設width,center不能設寬高,為扣除所有region後的大小
除了center為必要外,其他region為選擇性而非必要



★ Layout : 'card'

API:Ext.layout.container.Card

將元件採用card方式擺放,一次只有顯示一張
若要提升效能,而在載入時只繪製被啟動的子元件,則需加入:layoutConfig:{ deferredRender:true}

可使用getLayout().setActiveItem()來切換子元件



★ Layout : 'column'

API:Ext.layout.container.Column

用於將欄位水平排放
寬度設定:百分比 / 固定數值,可混用,會優先計算固定數值,剩的再以其百分比分配
columnWidth 的百分比表示法為小數,總合應為1
若指派元件設後會過寬,該元件會被擠到下一行



★ Layout : 'fit'

API:Ext.layout.container.Fit

讓容器與子元件無縫銜接
即便有多個子元件,也只會顯示一個子元件



★ Layout : 'form'

API:Ext.layout.container.Form

產生類似表單的外觀,用於管理表單布局
直接使用的話,一行內只能有一個item



★ Layout : 'hbox' / Layout : 'vbox'

API:Ext.layout.container.HBox / Ext.layout.container.VBox

HBox將元件水平擺放,其 align 提供 top , middle , stretch , strechmax 的水平對齊方式
VBox將元件垂直推疊,其 align 提供 left , center , stretch , strechmax 的水平對齊方式
HBox無bottom對齊方式,而VBox無right對齊方式,是因為受限於各瀏覽器實作方式不一所致



★ Layout : 'table'

API:Ext.layout.container.Table

必須設定layoutConfig中的columns
再透過 colspan / rowspan 設定所佔的欄數 / 列數使用時,colspan需設定寬度,rowspan則需設定高度








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