2011年10月30日 星期日

[Android] A glance at Android 4.0 features.

* 在 android 4.0 主要是整合了手機與平板上的開發,因此在 4.0 中,在 UI 上可以看融合了 3.0 的設計。


* 在幾篇文章介紹中,認為主要改變可分為:
  • UI: 加入了 tablet 上的元素
    • Lasted Recently Used - LRU 的顯示方與 3.0 相同,是縮圖。
    • Resize widget - 可直接改變桌面上 widget 的大小。(Supported in Android 3.1)
    • Quick Unlock/incoming Call - 有螢幕鎖時來電,可直接選擇接/不接/以簡訊回覆。
    • Action Bar - Home 底下新增個常用 app 的 action bar。(Supported in Android 3.0)
  • User behaviour and new functions: 對於 user 使用習慣加強與新增功能
    • New
      • App Management - 可直接從 app 選擇要對它的操作,ex: 捷徑、解安裝...。
      • Folder in Home - 在桌面上,可直接拉 app 疊在一起,即是變成是在同一個資料中。
      • Face detection - 臉部偵測,可用於解鎖。
      • Data Usage - (new) 可看到手機網路資訊傳輸量統計;可設定 threshold 通知。
      • Blue Health Devices - for 健康管理功能。
      • Accessibility - 輔助視障用戶操作。
    • Enhance
      • Notification - 可在不解鎖的狀況下查看; 用 swipe 方式關閉通知...。
      • Browser - 可開 16 個 tab、Sync bookmarks with Chrome...
      • Input - 在輸入時可做拼字檢查。
      • Calendar(read/write) - 可對 google calendar 做更多操作。
      • Camera - 快速拍照、全景拍攝、編輯圖片....。
      • Photo(Gallery)
  • Share(Social Activities): 結合社群功能
    • Contact(ME, status update...) - 新增 "ME" profile;與 facebook 等社群訊息整合。
    • Android Beam(NFC) - 利用 NFC 新增此功能,讓兩台 device 能更容易的分享。


以上不是所有功能,詳細內容可參考以下 references。


* Reference
- Android4.0 SDK新功能详解 ****
- Galaxy Nexus 和 Android Ice Cream Sandwich 報導大集合
- Android 4.0 Ice Cream Sandwich 正式發表!
- Android 4.0 發表 新功能、新介面搶先看 ***
- Android 4.0 (Ice Cream Sandwich)正式發表, 主要新功能簡介 - 小丰子俱樂部 - Yahoo!奇摩部落格 **
- Samsung Galaxy Nexus / Google Android ICS 發表會重點整理
- Android 4.0的那些新玩意們 **
- Android 4.0 Platform  ****

[Android] Unable to find a 'userdata.img' file for ABI armeabi to copy into the AVD folder

Error Message

Unable to find a 'userdata.img' file for ABI armeabi to copy into the AVD folder

發生在當想要啟動 android 4.0 的 AVD


Solution

Android 4.0 必須要安裝 ARM EABI v7a System Image 才能啟動



* Reference
- Android 4.0:Unable to find a 'userdata.img' file for ABI armeabi to copy into the AVD folder. - 懒人工作室 - 博客频道 - CSDN.NET
- How to create a AVD for android 4.0 - Stack Overflow

[Android] Application does not specify an API level requirement

Error Message

WARNING: Application does not specify an API level requirement!

會發生在 Run Android Application on eclipse
是否在 project 中少指定了什麼?

[Android] SyncException: Too many open files

Error Message

com.android.ddmlib.SyncException: Too many open files

Switch DEBUG USB off and on again. It works for me. It seems to be some sort of problem with USB sync when debuggin in my device.

Essentially, that means you have a memory problem. More than likely it is a leak.

First restart your phone and verify you are still getting the error. If so you are going to need to start digging in your code and find out where you are leaking!

Need more help? Post some code!


尚不知道在什麼情況下會發生


[AndroidDev] Live Wallpaper

  • Very similar to a Service.
  • The only difference is the addition of a new method, onCreateEngine(), whose goal is to create a WallpaperService.Engine.

WallpaperService.Engine
  • The engine is responsible for handling the lifecycle and drawing of a wallpaper.
  • The system provides a surface on which you can draw, just like you would with a SurfaceView.
  • The engine can also implement several methods to interact with the user or the home application.

Performance
  • The most important part of the lifecycle of a wallpaper is when it becomes visible, as indicated by a call to onVisibilityChanged().
  • When invisible, such as when the user launches an application that covers the home screen, a wallpaper must stop all activity.
  • 所以必須優化繪圖的內容及管理好 wallpaper 的 lifecycle,以達到以下改善:
    • To avoid using too much CPU.
    • Survive the battery life.
    • To avoid slowing down the rest of the system.

Configurations
  • <uses-sdk android:minSdkVersion="7" />
    • which indicates to Android Market and the platform that your application requires Android 2.1 or higher.
  • <uses-feature android:name="android.software.live_wallpaper" />


Pending Study
  • Draw content for wallpaper. 


* Reference 
- Live Wallpapers | Android Developers

[Encode] UTF-8 = 65001

UTF-8's codepage is 65001


Brief decription
在非Unicode環境下,由於不同國家和地區採用的字符集不一致,很可能出現無法正常顯示所有字元的情況。微軟公司使用了內碼表(Codepage)轉換表的技術來過渡性的部分解決這一問題,即透過指定的轉換表將非Unicode的字元編碼轉換為同一字元對應的系統內部使用的Unicode編碼。



* Reference
- Unicode

[Android] conversion to dalvik format to error 1

Error Message

conversion to dalvik format to error 1

Occurred when export apk file


Solution

proguard.bat

android 提供 proguard.bat 這個工具 讓你在 export apk 時 能對你的 code 做混淆的步驟

但在 SDK Tool, r12 會出現此問題,在 r11 還並不會有這問題。

在推出 android 4.0 後的 r14 仍然沒有修復此問題。

解決此問題的方法是修改以下這個檔案:

(#Android SDK Path)\tools\proguard\bin\proguard.bat, 將

call %java_exe% -jar "%PROGUARD_HOME%"\lib\proguard.jar %*

改為

call %java_exe% -jar "%PROGUARD_HOME%"\lib\proguard.jar %1 %2 %3 %4 %5 %6 %7 %8 %9

import jar

import JAR 檔時 有可能 reference 了兩次 JAR 檔

可確認 Java Build Path > LibrariesAndroid > Library


* Reference
- 在android中使用proguard混淆代码出现“Conversion to Dalvik format failed with error 1”错误的解决方法 - Naivesoft - 博客频道 - CSDN.NET
android - "Conversion to Dalvik format failed with error 1" on external Jar - Stack Overflow

[Android] NotFoundException: String resource ID

Error Message
Uncaught handler: thread main exiting due to uncaught exception
android.content.res.Resources$NotFoundException: String resource ID #0x0
 at android.content.res.Resources.getText(Resources.java:200)
 at android.widget.TextView.setText(TextView.java:2822)



Solution

因為 TextView.setText() 中可傳入 CharSequence text or int resId

因此若想顯示數字 而直接這樣寫 TextView.setText(121)

那麼會被識為要對應的是 string resource id 為 121 的字串內容

而跑出這個 exception

[Android] CalledFromWrongThreadException

Error Message
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at java.lang.Thread.run(Thread.java:1102)
Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRoot.checkThread(ViewRoot.java:2705)
at android.view.ViewRoot.invalidateChild(ViewRoot.java:574)
at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:600)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:2450)
at android.view.View.invalidate(View.java:4945)
at android.widget.TextView.checkForRelayout(TextView.java:5442)
at android.widget.TextView.setText(TextView.java:2693)
at android.widget.TextView.setText(TextView.java:2561)
at android.widget.TextView.setText(TextView.java:2536)
at com.yellow.android.TextActivity$1.onProgressUpdate(TextActivity.java:40)
at com.yellow.android.TextActivity$1.doInBackground(TextActivity.java:32)
at com.yellow.android.TextActivity$1.doInBackground(TextActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
 ... 4 more



Solution

Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

一般是因為沒有在 UI thread 執行關於 UI 上的操作 所以會利用 AsyncTask

原以為是因為在 AsyncTask 中使用 Thread.sleep() 而發生的 exception

但重寫後並不是

所以目前不確定發生的情況與真正原因


2011年10月29日 星期六

[Android] No active admin owned by uid

Error Message

java.lang.SecurityException: No active admin owned by uid 10028 for policy #3

Occurred when using DevicePolicyManager


Solution

Need to register a DeviceAdminReceiver before you can use the device policy manager


* Reference
- Implementing screen lock in Android 2.0 - Stack Overflow
- Android Developer Device Admin Guide
- 请问如何调用锁屏? - Android 问题&解答 - eoe·Android开发者门户 - Powered by Discuz!

[Android] 螢幕保護

Want To

就像電腦的螢幕保護程式,當手機閒置一段時間,不會鎖螢幕或是螢幕暗下來

而是顯示我們想要的內容,例如輪播照片之類的


Try To

[Lock Screen/Keyguard]
  • 取代系統原有的 Lock Screen/Keyguard
    • May Relative API
      • DevicePolicyManager
      • KeyguardManager
      • WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED, WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
    • Issues:
      • What is the different between Lock Screen and Keyguard means?
      • Keyguard includes 螢幕鎖和圖案解鎖等。(refer. 1)
      • Many events should be considered, ex:
        • Screen off/on, Incoming call/SMS, Alert Message.....
      • 是否可以在原有的 Lock Screen/Keyguard 上再執行自己的 application?
  • Disable Lock Screen/Keyguard and using Service or Thread to record touch event. 如果事件間隔超過設定,則啟動 Activity。
    • Events handler problems.
    • Start Activity in Service is allowed?
// Using KeyguardManager can disable/re-enable keyguard
KeyguardManager mKeyguardManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); 
KeyguardLock mKeyguardLock = mKeyguardManager.newKeyguardLock("Activity1"); 
mKeyguardLock.disableKeyguard(); 



[Live Wallpaper]
  • Live wallpaper still showing when screen is locked,所以若是僅顯示在螢幕鎖之下即可...
    • 動態設定 live wallpaper,也就是當螢幕鎖了,才設定(因為應該要不影響 user 原有的桌步設定),取消後恢復 user 原有設定。
    • 但沒有正式官方的相官 method。


* Reference
  1. android的KeyGuard_谢彦_新浪博客
  2. [Android]替换系统的Lock Screen - sunny09290的专栏 - 博客频道 - CSDN.NET
  3. Handling Screen OFF and Screen ON Intents

2011年10月20日 星期四

[Android] Is network available?

Error Message

Occurred on Desire API 2.2

當關閉行動網路時,透過以下的方法判斷是否有網路,卻回傳 true?!

public static boolean isNetworkAvailable(Context context) {  
    ConnectivityManager connectivity = (ConnectivityManager) context  
        .getSystemService(Context.CONNECTIVITY_SERVICE);  
        if (connectivity == null) {  
        } else {  
            NetworkInfo[] info = connectivity.getAllNetworkInfo();  
            if (info != null) {  
                for (int i = 0; i < info.length; i++) {  
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {  
                        return true;  
                    }  
                }  
            }  
        }  
        return false;  
    }  

若使用飛安模式則是回傳 false,但此情況僅出現幾次, 之後則模擬不出來,所以是否有疑漏其他操作行為?


Solution

在 API 2.1, 2.2, 2.3.3 的手機上測以下三種模式下所對應的結果:

飛安模式
  • NetworkInfo: [Landroid.net.NetworkInfo;@xxxxx, 
  • activeInfo: null 
  • type: MOBILE, state: DISCONNECTED, detailed state: DISCONNECTED, isAvailable: false, isConnected: false 
  • 其他 type 的 values 皆為以下 
    • state: UNKNOWN, detailed state: IDLE, isAvailable: false, isConnected: false 


開啟行動網路 
  • NetworkInfo: [Landroid.net.NetworkInfo;@xxxx, 
  •  activeInfo: NetworkInfo: type: MOBILE[UMTS], state: CONNECTED/CONNECTED, reason: dataEnabled, extra: internet, roaming: false, failover: false, isAvailable: true 
  • type: MOBILE, state: CONNECTED, detailed state: CONNECTED, isAvailable: true 
  • 其他 type 的 values 則為以下 
    • state: UNKNOWN or DISCONNECTED, detailed state: IDLE/DISCONNECTED/CONNECTED, isAvailable: true(few types are true), isConnected: false(few types are true) 


關閉行動網路 
  • NetworkInfo: [Landroid.net.NetworkInfo;@444b0530, 
  • activeInfo: null 
  • type: MOBILE, state: DISCONNECTED, detailed state: DISCONNECTED, isAvailable: true, isConnected: false 
  • 其他 type 的 values 皆為以下
    • state: UNKNOWN/DISCONNECTED, detailed state: IDLE/DISCONNECTED, isAvailable: true(few types are false), isConnected: false 


所以 state 結果應該和我們的需求一致 ,因此猜測是否得到的是狀態正在轉換時的值,試著監聽網路狀態的改變,以下方式能得到和操作一致的結果,但不確定此種方式是否正確。
// briefly
TelephonyManager.listen(new PhoneStateListener() { 
    @Override  
    public void onDataConnectionStateChanged(int state) {  
        switch(state){  
            case TelephonyManager.DATA_DISCONNECTED:
                break;  
            case TelephonyManager.DATA_CONNECTING:
                break;  
            case TelephonyManager.DATA_CONNECTED: 
                break;  
        }  
    }                     
}, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);  

另一種則是 onReceiver action "android.net.conn.CONNECTIVITY_CHANGE" 
但在改變任何狀態時皆收不到相關的 action!!!?


Pending Issues
監聽網路狀態 Using receiver to listen action "android.net.conn.CONNECTIVITY_CHANGE"


* Reference
- Android – 判斷手機是否連上網路 (ConnectivityManager)
- network: android 网络判断 **
- android之ConnectivityManager简介,网络连接状态
- NetworkInfo - ConnectivityManager
- 网络连接状态的监听和判断(android,wifi,Gprs)
- Android判断网络状态方法详解
- 监听手机的网络连接状态

2011年10月16日 星期日

[English] Difference among Image, Photo, Picture and Graphic

Photo
  • A photo is a picture taken with a camera.
  • Short for "Photograph".
  • Photo means 'light'. (?)

Picture
  • A picture is any visual representation of a subject.
  • A picture is usually something real.
  • Refers to a photo or drawing of something for art purposes

Image
  • An "image" is something generated or a representation of something in any other way.
  • All photos are images, but not all images are photos.

Graphic
  • A graphic is usually something drawn on a computer. realize that those terms are pretty broad and overlap a bit.
  • Sometimes a picture is a graphic and a graphic is a picture if you are using the terms loosely. Both of the two are still shots that happen at one point in time.
  • Work done for a company, occasion or event. ie, a logo.
  • Generally done on computers, and normally includes words or symbols

Animation
  • A collection of images, that rotate around like a movie, so only one is visible at a time, and is only shown for a short amount of time, like a movie


* Reference
- What is the difference between Image, Photo, and Picture? - Yahoo! Answers
- word choice - Difference between "picture" and "photo" - English Language and Usage - Stack Exchange
- word choice - What is the difference between "photo" and "image"? - English Language and Usage - Stack Exchange
- What's the difference between a picture, graphics and an animation? - Yahoo! Answers

[English] Difference between "day" and "date"

Day
Referring the seven days in a week: Sunday, Monday, and so on.

Date
Talking about what particular date of a month: 23rd of April, 1st of August, etc.


* Reference
- difference between "day" and "date" - UsingEnglish.com ESL Forum

[Security] SSL and HTTPS

[SSL]
  • Secure Socket Layer (安全套接層)。
  • 運行在TCP/IP層之上、應用層之下,與其繼任者傳輸層安全(TLS)是在網絡上為應用程序提供加密數據通道
  • 是網頁伺服器和瀏覽器之間以加解密方式溝通的安全技術標準,這個溝通過程確保了所有在伺服器與瀏覽器之間通過資料的私密性與完整性。
  • 採用了RC4、MD5以及RSA等加密算法。

Used for...
  • 確保 client 和 server 間的認證(網站身份認證)。
    • 因為 www 上充斥著假網站(釣魚網站)來騙取帳密,所以要驗證對方是真的。
  • 加密傳送資料,以防中途被竊取。
  • 維護數據的完整性,防範數據在傳送過程中被改變。

Process
  • 當瀏覽器端與 WWW 伺服器端同時支援 SSL 的傳輸協定時,在連線階段 SSL 同步確認 client 和 server,瀏覽器與伺服器就會產生那把的金鑰。
  • 產生金鑰後就能夠利用瀏覽器來傳送與接收加密過的重要資料啦。
  • 要注意的是,在某些很舊的瀏覽器上面是不支援 SSL 的。
  • Steps:
  1. Client request for server so start a new session. 告知伺服器端本身可實現的算法列表和其他一些需要的資訊。  
  2. Server 根據 client 的訊息確定是否要生成新的主密鑰,如果需要則 server 在 response 中包含生成主密鑰所需的資訊(資訊內包含身分及公鑰)。  
  3. client 根據收到的 response,產生一個密鑰,並用 server 的公鑰加密後傳給 server。(client 會自動的分析此證書,並根據不同版本的 browser,產生 40 位或 128 位的 session private key,用於加密傳送訊息。
  4. server 再用自己得私鑰解密得到 client 傳來的私鑰,並以私鑰加密要回傳的訊息,以讓 client 認證 server。




Problem
  • 那把 Public key 是伺服器產生且任何人都能取得的! ex:
    • 如果你不小心在釣魚網站輸入帳密,因為公鑰是誰都能拿到的,所以你的帳密還是被竊取,所以這時就需要第三方公正單位。

憑證
  • 可分為兩種:
    • 最低 40位和 128位 (private key 的長度,越長越不容破解)證書。
    • 最低 40位 server 證書在建立 session 時,根據 browser 版本不同,兩種都可以產生;而最低 128位 server 證書不受 browser 版本限制可以產生 128位以上的 private key,無論是 IE 或 Netscape,需要十年才能破解。
  • 一份 SSL 證書包含一個公鑰和一個私鑰。
    • 公鑰用於加密信息,私鑰用於解譯加密的信息。

CA
  • Certification Authority,認證中心。
  • 就是一個公認的公正單位,你可以自行產生一把金鑰且製作出必要的憑證資料並向 CA 單位註冊 (要錢的意思!),那麼當用戶端的瀏覽器在瀏覽時,該瀏覽器會主動的向 CA 單位確認該憑證是否為合法註冊過的:
    • 如果是的話,那麼該次連線才會建立。
    • 如果不是呢,那麼瀏覽器就會發出警告訊息, 告知使用者應避免建立連線啊。

Digital Signature
  • 在網路上﹐我們還可以使用“數位簽章(Digital Signature)”來進行身份確認。
  • 數位簽章可以說是一個獨一無二的數值﹐它由使用者的私有鍵值進行加密﹐然後利用公用鍵值進行確認
    • 若 public key 能通過驗證,那我們就肯定所對應的 private key 之正確性m
    • 否則,則可排除簽章所用的 private key 。
  • 換而言之,數位簽章兼具這兩種雙重屬性
    • 可確認性。
    • 不可抵賴性。


[HTTPS]
  • Secure Hyper Text Transfer Protocol (安全超文本傳輸協議)
  • Netscape公司相應開發了HTTPS協議並內置於其瀏覽器中。
  • 它是一個URI scheme(抽象識別字體系),https:URL表明它使用了HTTP,但HTTPS存在不同於HTTP的默認埠及一個加密/身份驗證層(在HTTP與TCP之間)。
  • HTTPS是以安全為目標的 HTTP通道,簡單講是HTTP的安全版,即HTTP下加入SSL層(因此加密的詳細內容請看SSL),實際上就是SSL over HTTP

HTTP vs. HTTPS

Advantages:
  • 所傳送的數據不容易被網絡黑客截獲和解密
    • 使用SSL在發送方把原始數據進行加密,然後在接受方進行解密,加密和解密需要發送方和接受方通過交換共知的密鑰來實現。

Disadvantages:
  • 耗效能
  • 加密和解密過程需要耗費系統大量的開銷,嚴重降低機器的性能,相關測試數據表明使用HTTPS協議傳輸數據的工作效率只有使用 HTTP協議傳輸的十分之一
    • 所以,我們只需對那些涉及機密數據如網上購物、交易付錢的交互處理、安全電子郵件等使用HTTPS協議,不需要用HTTPS 的地方,盡量不要用。

Overview


* Reference
- 小詞典: SSL和HTTPS
- 鳥哥的 Linux 私房菜 -- WWW 伺服器 Apache
- 加密網路封包鑑識設備
- 網路教學-資料加密
- SSL证书_百度百科
- https_百度百科
SSL和CA基礎知識
- 網站SSL加密原理簡介 ***

2011年10月15日 星期六

[Programming] Dev note

可以另外 export project 專門用來 build

apart build and editor projects

[JPA] Repeat fields

有重複 mapping 的欄位的話 只能有一個是可 insert 和 update 的

不然 JPA 不知道哪一個 attribute 才是要吃的值(不是取出時發生問題,是 set to db 的問題)

ex:
a attribute 跟 b attribute 都是 column "APP_ID"

存檔的時候,a 的值是 a ,b 的值是 b

它根本不知道要存 a 還是 b


[Note]

要存檔時是從物件呼叫 getter 塞給 db

setter 是從 db 取出來之後呼叫 setter 把值塞給物件

[Resources] not found for MessageSource

Error Message

main WARN org.springframework.context.support.ResourceBundleMessageSource.getResourceBundle(ResourceBundleMessageSource.java:223) - ResourceBundle [resource] not found for MessageSource: Can't find bundle for base name resource, locale en


Solution

因為找不到 properties file

一般應該要在 class 下

test case 中應和 configuration 放在同一層 否則要記得在 configuration 中要指定路徑。


[Note]

Sping test case 中指定 configuration 的 annotation:

@ContextConfiguration(locations = {"/applicationContext.xml"})


[SQL] ORA-00979: 不是一個 GROUP BY 表示式

Error Message

main WARN org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReporter.java:233) - SQL Error: 979, SQLState: 42000
main ERROR org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReporter.java:234) - ORA-00979: 不是一個 GROUP BY 表示式


Solution

做為 ORDER BY 的欄位

如果有使用到 GROUP BY 的話

那些欄位也要在 GROUP BY 中


2011年10月9日 星期日

[Java] Copying list to linkedList

Error Message

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0

occurred when copying list to linkedList


Solution

[Java] List


Error Message

java.lang.UnsupportedOperationException
      at java.util.AbstractList.remove(AbstractList.java:144)
      at java.util.AbstractList$Itr.remove(AbstractList.java:360)
      at java.util.AbstractCollection.removeAll(AbstractCollection.java:337)

occurred when  using removeAll


Solution

[JPA] Join

JPA get attribute in another table will join that table.


[J2EE] JUnit with weblogic

junit 沒通過 weblogic, run on J2SE


[J2EE] Log

Exception e

logger.error("test message", e);

log:
[2011...] main (...A) - test message
(......B)

A: log4j 裡設定的 pattern
B: e's trace stack

[Design] SQL condition

若 A、B、C 都要限制條件 x

可以以外層條件來寫 A.x = B.x and A.x = C.x

這樣 value 只要寫一次就可以了

......

form A

join A.x = B.x and A.x = C.x

where A.x = 'value'


[SQL] condition order

執行順序如下:
  1. where
  2. group by
  3. having

where 會在 group by 前執行

having 在 group by 後才執行



[JSP] type of Map's key

Map autoboxing uses Integer as key; JSP EL uses Long.

That's why the following codes are not working, if key defined as "1":



    ....





2011年10月3日 星期一

[ListView] The World of List View

[Adapters]
  • Terminology
    • index: Child views
    • position: Data in Adapter
    • id: Unique identifier for data
  • getView(int position, View convertView, ViewGroup parent)
    • Full data presentation control
    • Optimization
    • Shoot yourself in the foot (and the face) (搬起石頭砸自己的腳?)
  • convertView
    • Supplied by ListView
    • Matches item types
    • Reuse it

  • The Right Way to use getView().
    • 當 convertView 是 null 時,才 inflate layout,這樣才真正有 reuse。

public View getView(int position, View convertView, ViewGroup parent) { 
     if (convertView == null) { 
         convertView = mInflater.inflate(R.layout.item, parent, false); 
     } 
     ((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]); 
     ((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap( 
             (position & 1) == 1 ? mIcon1 : mIcon2); 
     return convertView; 
}


  • The Fast Way to use getView().
    • 將 layout 的 element 儲存在 viewHolder,共用同一份物件。
static class ViewHolder { 
        TextView text; 
        ImageView icon; 
}

  • How to shoot yourself in the foot (?)
    • Local view cache
    • Accessing views from the adapter
    • Change convertView’s structure
    • Assumptions about getView calls
  • Handling data changes
    • notifyDataSetChanged()
      • New or updated data
    • notifyDataSetInvalidated()
      • No more data available
  • Focusable
    • Do list items focus as a whole? (false)
    • Can views within list items have focus? (true)
  • Headers and footers - Scrolling
    • ListView.addHeaderView()/ListView.addFooterView()
    • Must be called before setAdapter()
    • isSelectable == Adapter.isEnabled()

[Don’t!]
  • android:layout_height=”wrap_content”
    • ListView is virtualized, remember?
    • wrap_content = “as big as my children”
    • ListView supports unevenly sized children
    • Measure thousands of children? Android framework cheats, measures only 3 children
  • ListView inside a ScrollView
    • ScrollView scrolls and ListView scrolls, who will scroll?
  • Cache views in the adapter (?)
    • Don’t outsmart ListView
      • ListView assumes ownership of views
    • Complex recycling mechanism
      • Numerous optimizations
      • Sometimes we even leave bugs there
    • Undead views is the worst case
      • View both in the recycler and on screen
  • Use a ListView when you don’t need one!
    • ListView...
      • Is for repeating, unbounded data
    • Adds (lots of) complexity



* Reference
- 2010 Google IO - The World of List View (android-world-of-listview-android.pdf)

2011年10月2日 星期日

[jQuery] ready() vs. onload()

[jQuery ready()]
  • 先透過 $() 取得 document 物件,接著使用 ready() 帶入一個函數,就可以在網頁下載完成後立即執行。
  • ex: $(document).ready(function());
  • 是模擬 W3C DOM 標準的 DOMContentLoaded 事件,因為,IE 目前的版本 6 和 7 並不支援 DOMContentLoaded 事件,所以 jQuery 用了此方法來達到模擬 DOMContentLoaded 的事件。
  • 在 DOM 文件下載完成後觸發。

[window.onload()]
  • 是文件和所有文件內的元件,包含圖檔等等全部下載完成後才會觸發

[versus]
  • 通常 window.onload 的發生時間要比 DOMContentLoaded 晚一點(如果你的網頁內確實有用到一些圖檔)
    • 所以,有時候你所需要執行的程式並不需要等所有圖檔都下載完成,因此,放到 DOMContentLoaded 事件內處理是比較合適的。
  • window.onload 並沒有辦法多次指定不同的函數來執行,最後指定的那個函數會複寫掉先前的。


* Reference
- jQuery 教學 - 基礎篇 - JavaScript 教學、心得分享 - jsGears.com 技術論壇 - AJAX, JavaScript, jQuery, 網站開發, 前端效能優化 - Powered by Discuz! **

[Network] DNS

[DNS]
  • 全名為Domain Name System「網域名稱系統」
  • 其主要的目的是用來解釋網際網路上的電腦主機名稱與IP位址之間的關係,進而能正確的在網際網路上找到該主機並傳送正確的訊息。
  • 架構
    • DNS網域名稱的架構是採分散式處理的模式來分類
    • 從根網域出發,分類出不同的分類網域環境,在每一個網域下又可再建立該網域的主機名稱,主機名稱下又可在延伸另一個子網域,整個樹狀結構我們稱為網域名稱空間(Domain Name Space)
  • DNS指向
    • 是公告大家該網域是由哪台DNS伺服器來管理
    • 所有關於該Domain Name的網路資料都記錄在該DNS主機,所以到該主要DNS伺服器上就可以查到。
    • 分為Client和Server:
      • Client扮演發問的角色,也就是問Server一個Domain Name。
      • Server必須要回答此Domain Name的真正IP地址。
    • 當地的DNS先會查自己的資料庫。如果自己的資料庫沒有,則會往該DNS上所設的的DNS詢問,依此得到答案之後,將收到的答案存起來,並回答客戶。
    • DNS伺服器會根據不同的授權區(Zone),記錄所屬該網域下的各名稱資料,這個資料包括網域下的次網域名稱及主機名稱。


[DNS伺服器]
  • 在網際網路中,電腦與電腦之間均以IP來辨識位址,而DNS網域名稱伺服器主要的功能就是建立Domain Name與IP的對應
  • DNS伺服器是DNS「網域名稱系統」的一種工具,用來完成DNS「網域名稱系統」,幫忙系統的運作正常。
  • 記錄了自己網域內的各種伺服器的主機名稱和IP位址,同時也提供DNS的查詢。
  • 網址為二個部分組成:主機名稱跟網域名稱
  • ex: 一般用戶要來瀏灠Seednet網頁,他會在網址內鍵入www.seed.net.tw,就可看到Seednet網站,實際上Seednet網站位址為139.175.1.10,至於如何建立www.seed.net.tw這個Domain Name與IP的對應,中間就需要有DNS Server來作對應了


* Reference
- Seednet教室 = = DNS基本觀念 = =
- Seednet教室 = = DNS運作原理 = =

[JAVA] 序列化

序列化是將 object 轉為 string,好用來傳遞。

Java 中的序列化只會對 object 的 attributes,而不會連 methods 也序列化。

因為 methods 是不帶狀態的,僅是指令,只要 JVM classloader 可以 loader 到那個類,那麼自然可以獲得 methods (?)。

序列化真正要保存的是 object attributes 的值和 object 類型。


In a word, 序列化會保存 object 的以下內容:
  • object type
  • object attributes' type
  • object attributes' value



* Reference
- Java序列化机制要序列化那些内容 - 丸子 - ITeye技术网站

[AndroidManifest] android:configChanges

* Definition
  • When a configuration change occurs at runtime, the activity is shut down and restarted by default.
  • But declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.
  • 在預設上,當任一屬性改變時,activity 會被關閉並且重啟;但若有指定此設定及屬性,則當被指定屬性改變時,activity會執行並通知系統 call onConfigurationChanged().


* Attribute values
  • mcc
    • The IMSI mobile country code (MCC) has changed — that is, a SIM hasbeen detected and updated the MCC.
    • IMSI 中的移動國家號碼,有三位數,每個國家都有自己獨立的MCC,可以識別手機用戶所屬國家。
  • mnc
    • The IMSI mobile network code (MNC) has changed — that is, a SIM hasbeen detected and updated the MNC.
    • 在一個國家或地區中,用於區分手機用戶的服務商。
  • locale
    • The locale has changed — for example, the user has selected a new language that text should be displayed in.
    • 使用者的所在區域改變。
  • touchscreen (?)
    • The touchscreen has changed. (This should never normally happen.)
  • keyboard
    • The keyboard type has changed — for example, the user has plugged in an external keyboard.
  • keyboardHidden
    • The keyboard accessibility has changed — for example, the user has slid the keyboard out to expose it.
  • navigation (?)
    • The navigation type has changed. (This should never normally happen.)
  • orientation
    • The screen orientation has changed — that is, the user has rotated the device.
    • 螢幕直向與橫向的轉換。
  • fontScale
    • The font scaling factor has changed — that is, the user has selected a new global font size.
    • 字體改變大小。
  • uiMode (?)
    • The user interface mode has changed — this can be caused when the user places the device into a desk/car dock or when the the night mode changes. See UiModeManager.
    • Introduced in API Level 8.
    • CAR_MODE or DESK_MODE....
  • screenSize (?)
    • The current available screen size has changed. 
    • This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. 
    • However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
    • Added in API level 13.
  • smallestScreenSize
    • The physical screen size has changed.
    • This represents a change in size regardless of orientation, so will only change when the actual physical screen size has changed such as switching to an external display.
    • A change to this configuration corresponds to a change in the smallestWidth configuration.
    • However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
    • Added in API level 13.



* Reference
- Android ConfigChanges用法 - Android实例教程 - Android开发论坛 - 安卓开发论坛 - Android开发
- Android Developer - android:configChanges

[Java] Java Message Service


* Definition
  • The Java Message Service (JMS) API,用來訪問消息收發系統,類似於JDBC(Java Database Connectivity)角色,只是是功能是訊息的傳遞。
  • Java Message Oriented Middleware (MOM) API for sending messages between two or more clients.
  • A messaging standard that allows application components based on the Java Enterprise Edition (JEE) to create, send, receive, and read messages.
  • 是由Sun與MOM廠商所共同制定的介面,定義了訊息的傳送、接收、頻道(Channel)、主題(Topic)、佇列(Queue)等標準介面。
  • 實作部份由廠商完成,Java開發人員只要學習標準API介面的使用,就可以利用各廠商的JMS支援系統來進行訊息傳送、接收等處理(您可以想像JDBC與資料庫廠商之間的關係)。
  • ex: 包括 IBM 的 MQSeries、BEA的 Weblogic JMS service和 Progress 的 SonicMQ。

* Advantages
Allows the communication between different components of a distributed application to be loosely coupled, reliable, and asynchronous.

* API
  • 頻道是用Destination這個介面來定義
    • 在訊息(Message)觀念中提及,訊息服務有兩種模式:
      • 出版-訂閱(Publish-Subscribe)
      • 點對點(Point-to-Point)
  • 頻道分為:
    • 主題
    • 佇列
  • Destination有兩個子介面Topic與Queue來分別代表。
    • 根據兩種模式的不同,ConnectionFactory有TopicConnectionFactory、QueueConnectionFactory兩個子介面。
  • 對於訊息產生者、訊息消費者的定義則分別為:
    • MessageProducer
    • MessageConsumer介面
    • 而在兩種模式下,分別有發佈 者(Publisher)、傳送者(Sender),以及訂閱者(Subscriber)、接收者(Receiver)。


* Usage
伺服端必須設定好ConnectionFactory以及Destination,並分別使用一個名稱向JNDI註冊,端點必須使用JNDI名稱查找ConnectionFactory及Destination,JMS端點取得ConnectionFactory,使用其與伺服端建立連線,連線以Connection介面定義。


[Message]
  • Messaging is a form of loosely coupled distributed communication, where in this context the term 'communication' can be understood as an exchange of messages between software components.
  • Message-oriented technologies attempt to relax tightly coupled communication (such as TCP network sockets, CORBA or RMI) by the introduction of an intermediary component.
  • The advantages of messaging include the:
    • Ability to integrate heterogeneous platforms.
    • Reduce system bottlenecks, increase scalability.
    • Respond more quickly to change.


[Message passing]
  • A form of communication used in parallel computing, object-oriented programming, and interprocess communication.
  • In this model, processes or objects can send and receive messages (comprising zero or more bytes, complex data structures, or even segments of code) to other processes. By waiting for messages, processes can also synchronize.
  • Message passing is the paradigm of communication where messages are sent from a sender to one or more recipients. Forms of messages include (remote) method invocation, signals, and data packets.



* Reference
Java Message Service - Wikipedia, the free encyclopedia
Message passing - Wikipedia, the free encyclopedia
簡介 Java Message Service
訊息(Message)觀念
JMS_百度百科

[Android] ContentProviderClient vs. ContentResolver

* Your android device has many databases, each of which is identified by a unique Content Authority. This is the "domain name" equivalent part in the content:// uri -- everything before the first slash.


[ContentResolver]
  • ContentResolver stores data providing a mapping from String contentAuthority to ContentProvider.
  • When you call ContentResolver.query() or update() or what have you, the URI is parsed apart into its components, the contentAuthority string is identified, and contentResolver has to search that map for a matching string, and direct the query to the right provider.
  • This expensive search occurs during every single call, becuase the URI might be different from call to call, with a different contentAuthority as well.
  • Additinally, there may be some costs involved in setting up and tearing down a connection to that specific provider -- It can't be reused across calls. I'm not sure of the overhead involved there, that's some pretty deep OS level code.


[ContentProviderClient]
  • By contrast, when you call acquireContentProviderClient(authority), that "what-provider do I need?" lookup is done once, and you are given a ContentProviderClient which is essentially a direct link to the ContentProvider. (There's a bit of glue between you and the provider that involves cross-thread communication and concurrency locking).
  • However, when you use ContentProviderClient, you will talk directly to the Provider for the authority you requested. This removes the waste of constantly re-computing "which provider do I want?"


NOTE:
Per acquireContentProviderClient() documentation: If you obtain a ContentProviderClient,
"The caller must indicate that they are done with the provider by calling ContentProviderClient.release() which will allow the system to release the provider it it determines that there is no other reason for keeping it active."
So essentially, leaving a stale Client open will force the Provider to keep running as a service in the background. So, remember to clean up!


Summary:
  • Many calls to varying contentAuthorities: Use ContentResolver.
  • Repeated calls to the same Authority: Obtain and use ContentProviderClient. Remember to release() it when you're done.



* Reference
- android - using ContentProviderClient vs ContentResolver to access content provider - Stack Overflow

2011年10月1日 星期六

[Permission] Security and Permission

[Security Architecture]
  • In the Android security architecture, by default,
    • No application has permission to perform any operations that would adversely impact other applications, the operating system, or the user.
    • ex:
      • reading or writing the user's private data (such as contacts or e-mails)
      • reading or writing another application's files
      • performing network access
      • keeping the device awake, etc.
  • Applications statically declare the permissions they require, and the Android system prompts the user for consent at the time the application is installed.
  • Android has no mechanism for granting permissions dynamically (at run-time) because it complicates the user experience to the detriment of security.

[Application Signing]
  • The purpose of certificates in Android is to distinguish application authors.
  • This allows the system to grant or deny applications access to signature-level permissions and to grant or deny an application's request to be given the same Linux identity as another application.

[User IDs and File Access]
  • At install time, Android gives each package a distinct Linux user ID. 
  • The identity remains constant for the duration of the package's life on that device. On a different device, the same package may have a different UID
  • Because security enforcement happens at the process level, the code of any two packages can not normally run in the same process, since they need to run as different Linux users.
  • The two packages are then treated as being the same application, with the same user ID and file permissions.
  • Note that in order to retain security, only two applications signed with the same signature (and requesting the same sharedUserId) will be given the same user ID.

[Using Permissions]
  • A basic Android application has no permissions associated with it, meaning it can not do anything that would adversely impact the user experience or any data on the device.
  • A particular permission may be enforced at a number of places during your program's operation:
    • At the time of a call into the system, to prevent an application from executing certain functions.
    • When starting an activity, to prevent applications from launching activities of other applications.
    • Both sending and receiving broadcasts, to control who can receive your broadcast or who can send a broadcast to you.
    • When accessing and operating on a content provider.
    • Binding to or starting a service.

[Declaring and Enforcing Permissions]
For example, an application that wants to control who can start one of its activities could declare a permission for this operation as follows:



  • <protectionLevel>
    • Is required.
    • Telling the system how the user is to be informed of applications requiring the permission, or who is allowed to hold that permission.
  • <permissionGroup>
    • Is optional, and only used to help the system display permissions to the user.
  • <android:label>
    • Should be supplied.
    • Can be displayed to the user when they are viewing a list of permissions.
  • <android:description>
    • Should be supplied.
    • Details on a single permission 
    • Our convention for the description is two sentences.
      • The first describing the permission.
      • The second warning the user of what bad things can happen if an application is granted the permission.
  • You can look at the permissions currently defined in the system with the shell command adb shell pm list permissions. 
    • In particular, the '-s' option displays the permissions in a form roughly similar to how the user will see them.
    • ex: adb shell pm list permissions -s

[Enforcing Permissions in AndroidManifest.xml]
  • Activity, Service, BroadcastReceiver, ContentProvider if the caller does not have the required permission then SecurityException is thrown from the call.
  • 其中 ContentProvider 還可分以下兩種 permission:
    • android:readPermission
      • Using ContentResolver.query() requires holding the read permission.
    • android:writePermission
      • Using ContentResolver.insert(), ContentResolver.update(), ContentResolver.delete() requires the write permission.


[Enforcing Permissions when Sending Broadcasts]

[URI Permissions]
  • The solution to this problem is per-URI permissions: 
  • .....


[API]
  • android:protectionLevel
    • The default value is normal.
  • android:sharedUserId
    • By default, Android assigns each application its own unique user ID.
    • If this attribute is set to the same value for two or more applications, they will all share the same ID — provided that they are also signed by the same certificate.
    • Application with the same user ID can access each other's data and, if desired, run in the same process.
  • Manifest.permission
  • SecurityException


* Reference
- Security and Permissions
- android自定义权限
- Android开发指南-框架主题-安全和许可

[Spring] mvc annotation

* mvc:annotation-driven
  • registers a DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter.
  • @NumberFormat and @DateTimeFormat annotations.
  • JSR-303 Bean Validation API support will be detected on classpath and enabled automatically.

* mvc:default-servlet-handler
  • allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container's default Servlet),
  • while still allowing static resource requests to be handled by the container's default Servlet.


[J2EE] Apache and Weblogic


Weblogic default port is 7001.

Apache default port is 8001. (Or could refer /conf/httpd.conf "ServerName")

所以若是從 7001 連入則只能看見 weblogic 下的資源,從 8001 連進則能看見 apache 和 weblogic 的資源。


[JPA] Object connect to DB data

Error Message

JPA OBJECT 會和 db 連結在一起

所以修改時取出物件到頁面 當 user 更動了資料

其實 db 裡的資料也已經被更動 JPA session 裡的資料也會一同更動

因此當 user submit 後 若我們要檢查 user 是否有更動資料

再去取一次 object 是比對不出來的

因為 db 內的資料已和被更動到和頁面上的資料一樣
(在還沒 commit 前是不會更動到 db 內的資料的)

因為實際上我們取到的會是 session 裡已經被更動到的資料
(類似 browser cache)


Solution

使用 entityManager.clear() 切斷 object 和 db 間的關係 (clear session)

但切斷關係的後 使用 lazy 的 attribute 會發生取不到的問題 (因為已對應不到db)

所以在 clear 前 要先把需要用的 attribute 的 promary key 取出存下

好在要使用時能去再 select 出來 塞回物件

[J2EE] note

* submit 後將 form 中欄位的值送到 server

* server site 也做檢查是避免惡意人士 造假頁面試圖躲過頁面上的檢查 然後 submit 到我們的 server 的 action url

* jsp 會被 server compiler,html tag js 應視為頁面上固定死的東西(字串) ,所以 java 穿插在其中的 code 應以 compiler 後的值來看,而不是以 java code 的角度來看。



[Struts] action and jsp


    jsp file path

method: 指定要去執行的 method。

result: 是 action 裡指定要對應到頁面的字串。

[Struts2] s:hidden

<s:hidden name="parentCategoryId" id="parentCategoryId"></s:hidden>

不用指定 value 便會將值塞進去

[J2EE] action, controller and servlet

action = controller = servlet