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