Saturday, January 31, 2009

Cloud Computing basics

=== Needs ===

Nguyên nhân cho sự ra đời của Cloud Computing :

- Mỗi doanh nghiệp làm business bao giờ cũng cần xây dựng một hệ thống thông tin cho riêng mình, thông thường bao gồm các hệ thống: web pages, payroll, email management, CRM,... Để thiết kế và duy trì hệ thống này, các doanh nghiệp phải chi ra một số tiền không nhỏ, nhất là tiền lương trả cho DBAs. Với các doanh nghiệp nhỏ thì đây là một khoản đầu tư đáng kể. Có một cách tiếp cận khác là thay vì tự xây dựng một hệ thống như thế cho riêng mình thì việc outsource bằng cách thuê lại của đơn vị khác để giảm chi phí build và management.

- Khi mà internet bandwidth không còn là vấn đề nữa thì các ông lớn như MS, IBM, Google, Yahoo,... ngửi thấy mối hàng béo bở này liền bắt tay xây dựng một hệ thống có thể cung cấp cho khách hàng tất cả các loại dịch vụ trên thông qua các web services.




=== Problems ===

Khi xây dựng một thống centralized để phục vụ cho hệ thống trên thì dễ thấy các vấn đề nổi bật sẽ xuất hiện là:

- Cần phải lưu trữ một khối lượng dữ liệu lớn đến rất lớn.

- Dữ liệu đa định dạng, phân tán

- Cần phải có một hệ thống tính toán đủ mạnh để có thể xử lý hàng ngàn ứng dụng (phép toán) 1 lúc cho 1 lượng dữ liệu khổng lồ .




=== Solutions===

Cloud Computing ra đời để giải quyết 2 vấn đề này:

- Dữ liệu được lưu trữ ở các Data Center khổng lồ. Mỗi một công ty lớn như MS, Google có hàng chục data center như vậy nằm rải rác khắp nước Mỹ và các nơi trên thế giới. Vấn đề chính cho các data center này chủ yếu là công suất tiêu thụ và sự tản nhiệt. Vì thế gần đây các data centers thường được xây dựng ở gần các con sông lớn (như dọc sống Colorado) .

- Còn vấn đề về computing power thì có 2 giải pháp: 1 là mua các supercomputer từ Gray, Sun, Teradata,.. và 2 là dùng hệ thống tính toán song song với các commodity hardware. Tất nhiên cách thứ 2 là cách rẻ tiền nên được ưa chuộng hơn. Tuy nhiên, cách này yêu cầu có một cách phân chia công việc, scheduling và failure management một cách hợp lý. Có rất nhiều mô hình tính toán song song được phát triển, nhưng gần đây mô hình MapReduce của Google thu hút được nhiều sự chú ý về tính đơn giản và hiệu quả. Hadoop là một giải pháp open source của Apache Foundation (xuất phát từ Yahoo) lấy ý tưởng từ cái MapReduce này. Hiện tại MapReduce và Hadoop đang là những keyword khá hot.


- Ngoài ra thì để quản lý hệ thống cơ sở dữ liệu khổng lồ này cần có cách lưu trữ, truy nhập hiệu quả mà các DBMS thông thường không đáp ứng được.

+ MS đang chuẩn bị cho ra đời một hệ thống như thế gọi là CloudDB và 1 hệ điều hành tên là Windows Cloud OS. Yahoo thì chưa có CC theo đúng nghĩa, vì nó chỉ có các computing cloud chạy được mỗi app của chúng nó, còn không open và không customize được. Cái này gần với Sever Clustering hơn là Cloud Computing.

+ IBM có Cloud Computing trên nền Linux và AIX, gọi là Blue Cloud, nhưng lại bị giới hạn bởi phạm vi địa lý và computing resrource.

+ Google có App Cloud, nhưng chạy được mỗi Python App, không có database và không cài thêm được app.

+ Sun và HP cũng có Cloud Computing offering nhưng còn trong giai đoạn thử nghiệm bởi tính ứng dụng còn ở dạng "tiềm năng".

+ Hiện tại chỉ có Cloud Computing của Amazon (EC2) là được đánh giá phát triển đáng kể nhất. Amazon có lợi thế lớn là có một sever farm khổng lồ ở hầu hết mọi zone trên thế giới, các team dev hiện cũng đang sử dụng Amazon Web Services để phát triển phần mềm và deploy phần mềm. Amazon S3 cung cấp dịch vụ lưu trữ với unlimited space, có thể lưu trữ tại bất kỳ vùng địa lý nào, ví dụ như Nam Mỹ, Bắc Mỹ, Châu Âu, Châu Phi, Châu Á ..., nên hạn chế được sự chậm trễ do khoảng cách. Nếu như một công ty nào đó có nhiều chi nhánh trên thế giới, có thể dùng nhiều S3 để lưu trữ.


Amazon EC2 cho phép người dùng chọn bất kỳ hệ điều hành nào, ví dụ như Linux (Fedora, Ubuntu ...), BSD. Hình như giờ mới có cả Window server. Mỗi EC2 instance là một virtual server, có RAM nhiều hay ít, một hay nhiều processor tùy theo loại của instance, và người dùng có thể dùng EC2 tools hoặc SSH vào, cài bất kỳ software nào mình thích lên, như là một computer bình thường. Hoặc có thể setup một EC2 instance image, rồi khi cần có thể chạy một loạt server có cấu hình giống hệt như cái instance image đấy, số lượng server là bao nhiêu là tùy ở mình.


Amazon Persistence Service cho phép người dùng sử dụng như một đĩa cứng ảo gắn vào máy tính ảo EC2.


Theo đánh giá của 1 số dev đang phát triển bằng Amazone Web services, Amazon WS rất an toàn, vì nó dựa trên RESTful Web Services, SSL và độc đáo hơn nữa là time-based URL, nghĩa là URL để download hay upload hay truy cập site trong AWS có thể expire sau một thời gian nhất định.




(theo IBM developerWorksblog Alibobo)

Saturday, January 24, 2009

2009 informatic technologies

Top 10 hot technologies for 2009

* Virtualization (ảo hóa)

* Cloud computing (tính toán mây)

* Servers (máy chủ)

* Web-oriented architectures (kiến trúc hướng web)

* Enterprise mashups (thương mại tổng hợp)

* Specialized systems (hệ chuyên gia)

* Social software and social networking (mạng xã hội)

* Unified communications (giao tiếp thống nhất)

* Business intelligence (nghiệp vụ thông minh)

* Green IT (công nghệ tin học xanh)



Runner-up: RFID (xác định bằng tần số radio)

Friday, January 23, 2009

Linus on Git

Trong thế giới Software Configuration Management (SCM, hay thường được gọi là VCS hay RC) thì CVS (Concurrent Versions System) là một bước ngoặt, ngay từ lúc ra đời đã vượt trội SCCS, RCS, SS... để trở thành SCM tiên phong mạng diện rộng (WAN, Internet). Thành công của CVS chỉ đến khoảng 2000 thì bắt đầu bị cạnh tranh mạnh mẽ bởi SVN (SubVersioN), và đến bây giờ thì có thể nói SVN đã lấn áp được CVS để trở thành VCS được ưa chuộng nhất, họa may chỉ có Perforce mới cạnh tranh được, chứ VSS hay TFS thì còn xa mới theo nổi.

Tuy nhiên tương lai của SCM/VCS sẽ là distributed SCM, trong đó ứng cử viên sáng giá nhất hiện nay là Git, kế đến là Bazaar và Mercurial.


Git là một VCS mã nguồn mở dạng phân tán , được Linus Torvard viết ra nhằm thay thế 1 DSCM khác là BitKeeper , khi tác giả BK quyết định đổi license của BK. Và hiện nay Git được sử dụng thay cho BitKeeper trong việc phát triển kernel Linux, cũng như đang mở rộng ra nhiều ứng dụng khác (X-server, Samba, Qt, WINE, Perl, Android, RoR, VLC, Prototype, ...) .


Các bạn có thể xem đoạn Linus Torvards giới thiệu về Git tại Google Tech Talk:





Điều ấn tượng nhất với tôi qua cuộc nói chuyện này, đó là Linus không hề có vẻ gì là "geek" hay "anti-social" như nhiều người vẫn nghĩ, trái lại kỹ năng dẫn dắt vấn đề thu hút, trình bày dễ hiểu và hấp dẫn của anh đáng để khâm phục và học hỏi.


Một người có sức sáng tạo dĩ nhiên là một người thích khôi hài rồi, có phải không ?

Thursday, January 22, 2009

Top FireFox extensions

IMHO:


* Top 5 extensions for general users :

+ AdBlock Plus

+ DownThemAll(Linux,Mac)/FlashGot(Windows)

+ Session Manager

+ Download Status Bar (probably deprecated since FF 3.0)

+ FasterFox


Runner-up : Colorful Tabs




* Top 5 extensions for web developers :

+ FireBug

+ Grease Monkey

+ IE View Lite

+ MeasureIt

+ ColorZilla


Runner-up : Html Validator




* Top 5 extensions for Internet addicts :

+ Foxmarks

+ Fast Video Download

+ FireShot

+ Interclue

+ FoxyProxy

Runner-Up: Cooliris




Am I missing some thing?

Tuesday, January 13, 2009

ThunderBird duplicate mails

To make ThunderBird automatically handle possible duplicate emails, you can edit the value of "mail.server.default.dup_action" in its prefs.js (or use its Config Editor) :

* 0 - (default value) retrieves duplicate mails like normal mails.
* 1 - duplicate mails will be deleted automatically once retrieved
* 2 - duplicated mails will be moved right into the trash
* 3 - finally marks duplicate mails as read




To remove those duplicate ones which has already been retrieved, you should install the "Remove Duplicate Messages" add-on.


:-)

Monday, January 12, 2009

Java coding convention [2]

Trong bài đề cập về coding convention của Java (http://mediocre-ninja.blogspot.com/2008/11/java-coding-convention.html), hầu như các điểm đã nêu đều phù hợp với convention của Sun và bao quát gần hết các điểm đáng chú ý. Tuy nhiên thực tế cho thấy còn vài vấn đề thường gặp về coding style mà quy ước của Sun cũng chưa đề cập, hoặc ngay cả bộ sun-JDK cũng không nhất quán (inconsistent).

Chẳng hạn, một vấn đề về quy ước đặt tên (naming convention) khi đặt tên lớp (class name) hoặc tên phương thức (method name), theo Sun thì class sẽ capitalize theo PascalCase (UpperCamelCase), còn method thì theo camelCase (lowerCamelCase) :

Class names should be nouns, in mixed case with the first letter of each internal word capitalized.
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.


nhưng trường hợp class/method có dùng các từ viết tắt (quen thuộc) như: HTTP, XML, URL,... thì sao? Liệu chúng ta nên viết hoa toàn bộ (all uppercase) cụm từ đó, hay là chuyển nó thành CamelCase ? Trong bộ JDK thì Sun có dùng cả 2 cách, trong đó cách thứ nhất chiếm số lượng nhiều hơn.

Theo tôi thì 2 chọn lựa trên mỗi cách đều có ưu và khuyết điểm :

+ Viết hoa toàn bộ cụm viết tắt: đang được Sun ủng hộ, các ưu nhược điểm: ...

+ Viết cụm đó thành dạng CamelCase : được cộng đồng Open Source (Apache, Spring, Hibernate, ... ) ủng hộ, có các ưu nhược điểm: ...


Vậy chúng ta nên chọn cách nào ?



Well, tôi ủng hộ cách thứ 2, tức là cách always use strict camelCase for naming method, bởi vì:

Sunday, January 11, 2009

ThunderBird Gmail IMAP

+ Trước tiên đăng nhập vào web mail.google.com, bật chức năng IMAP :

- Settings -> Forwarding and POP/IMAP -> IMAP access -> Status: Enable IMAP


+ Tạo account mới trong ThunderBird với tài khoản Gmail :

- Tools -> Account Settings -> Add Account -> Email account -> Next : nhập tài khoản mail Google (ví dụ: username@gmail.com )


+ Chọn phương thức lấy thư, server lấy thư, server gởi thư:

- Next : type of incoming server -> IMAP ; Incoming server -> imap.gmail.com ; Outgoing server -> smtp.gmail.com


+ Chọn tên hiển thị trong thư gởi đi và thư nhận : để đơn giản nên điền chính tài khoản mail Google

- Next : Incoming User Name: username@gmail.com , Outgoing User Name: username@gmail.com


+ Chọn tên đại diện cho tài khoản trong Thunder Bird:

- Next -> AccountName : "gì cũng được :) " -> Next -> Finish !


+ Thiết lập trong ThunderBird (Account Settings), phần máy chủ nhận (Server Setting) :

- Server Settings -> Port : 993.
- Server Settings -> Security Settings -> Use secure connection -> SSL .


+ Thiết lập trong ThunderBird (Account Settings), phần máy chủ gởi (Outgoing server SMTP) :

- Chọn tài khoản tương ứng (thường có chữ Default) -> Edit -> Server Name : smtp.gmail.com ; Port : 587 (hoặc 25 ) ; User name and password : username@gmail.com (nên điền đủ cả phần @) ; Use secure connection : TLS, if available


+ OK, OK , thiết lập cơ bản vậy là xong ! Bây giờ có thể thử get mail và send mail :-)


Còn phần Recommended Settings sẽ ở 1 post sau :-)

Have fun,




Saturday, January 10, 2009

JavaCard quick notes [4]

=== JavaCard architecture overview ===

Smart cards represent one of the smallest computing platforms in use today. The greatest challenge of Java Card technology design is to fit Java system software in a smart card while conserving enough space for applications. The solution is to support only a subset of the features of the Java language and to apply a split model to implement the Java virtual machine - JavaCard virtual machine.

The Java Card virtual machine is split into two part: one that runs off-card and the other that runs on-card. Smart cards differ from desktop computers in several ways. The memory configuration of a smart card might have on the order of 1K of RAM, 16K of EEPROM, and 24K of ROM. In addition to providing Java language support, Java Card technology defines a runtime environment that supports the smart card memory, communication, security, and application execution model. The Java Card runtime environment conforms to the smart card international standard ISO 7816.


Java Card technology essentially defines a platform on which appli-
cations written in the Java programming language can run in smart cards and other
memory-constrained devices. (Applications written for the Java Card platform are
referred to as applets.) Because of the split virtual machine architecture, this plat-
form is distributed between the smart card and desktop environment in both space
and time. It consists of three parts, each defined in a specification.

• The Java Card 2.1 Virtual Machine (JCVM) Specification defines a subset of the Java programming language and virtual machine definition suitable for smart card applications.

• The Java Card 2.1 Runtime Environment (JCRE) Specification precisely describes Java Card runtime behavior, including memory management, applet management, and other runtime features.

• The Java Card 2.1 Application Programming Interface (API) Specification describes the set of core and extension Java packages and classes for programming smart card applications.


Supported and Unsupported features in JavaCard :





:-)

Friday, January 09, 2009

Software 2009 forecast

Well, ai cũng biết là 2008 là năm trượt giá đáng kể ở VN kể từ khi mở cửa. Nhiều người cũng thấy cảnh khó khăn của nhiều công ty phần mềm trong nửa sau 2008, ảnh hưởng của khó khăn xuất phát từ nền kinh tế Hoa Kỳ, cũng như vài chính sách củ chuối của bác Ba Dũng.
Do đó không nhất thiết phải là 1 genius để tiên đoán về khó khăn của ngành phần mềm năm 2009, không chỉ ở VN. Nhưng cứ thử xem sao :-) .



Tổng kết lại, có thể thấy những thay đổi sẽ diễn ra trong các năm tới đây:

* Những kỹ sư phần mềm có trình độ cao, có nhiệt huyết và tham vọng sẽ là những cỗ máy làm ra tiền.

* Những lập trình viên không có kỹ năng đặc biệt có lẽ nên tìm việc làm ở lĩnh vực khác.

* Những thay đổi mà chúng ta đang thấy ở thị trường phần mềm đại chúng sẽ diễn ra ở các công ty lớn.

* Đưa phần mềm cho nước ngoài gia công (outsourcing) sẽ ngày càng ít tính kinh tế hơn.

* Khoa học máy tính vẫn là lĩnh vực cạnh tranh và đòi hỏi cao.



==> Tương lai của các LTV Việt Nam:

Nhìn các xu hướng đang diễn ra trên thế giới, có thể thấy rằng các dự án cần hàng trăm người sẽ ngày càng ít đi. Theo tính toán của Mỹ, chi phí outsourcing đang gia tăng (từ 1/10 lên 1/3 so với giá thành sản xuất trong nước) làm cho việc đưa phần mềm ra nước ngoài gia công ngày càng kém hấp dẫn. Ngoài ra, do khó khăn về giao tiếp và chệnh lệch về trình độ, chất lượng các dự án này cũng không được như mong muốn và rất khó bắt kịp các thay đổi của khách hàng.

Các LTV luôn có xu hướng muốn gia nhập các công ty lớn, tham gia vào các dự án lớn. Nhưng có thể đấy sẽ cách tiếp cận sai lầm vì:

* Tương lai của các công ty làm xuất khẩu phần mềm dạng này đang ngày càng bấp bênh.

* Bản thân các LTV thường không cải thiện được trình độ vì các công việc được giao ít cần kỹ năng cao hay tính sáng tạo.

Tất nhiên, nhìn thẳng vào thực tế, sự thay đổi sẽ không diễn ra ngay trong nay mai — mô hình thác nước và các biến thể của nó vẫn sẽ được dùng, người ta sẽ vẫn outsourcing. Nhưng mọi thứ sẽ ngày càng khó khăn hơn, đòi hỏi cao hơn và chỉ khi bạn thực sự chuẩn bị tốt cho sự thay đổi thì mới tránh được việc bị đào thải.

Đáng lo ngại nhất là các LTV Việt Nam còn xa mới theo kịp các đồng nghiệp ở các nước như Ấn Độ hay Ireland cả về mặt tổ chức lẫn kỹ năng. Chúng ta quá chú trọng tới các công nghệ độc quyền của Microsoft, Oracle hay IBM và hiểu biết về mã nguồn mở là một lỗ hổng lớn. Không may, có thể ngày mai công ty sẽ nói lời chia tay với bạn chỉ vì bạn không có kinh nghiệm gì về Python hay cơ sở dữ liệu MySQL. Như tựa một bộ phim "Đó là một tương lai không quá xa" (Not too far future), xin hãy suy nghĩ lại con đường của mình.


(có trích đoạn từ blog của Chương Alibobo)

Thursday, January 08, 2009

BlazeDS quick notes

=== What is BlazeDS? ===

+ Java remoting and Messaging Technology.

+ Enables developers to connect to back-end distributed data and push data in real-time to Adobe Flex and Adobe AIR applications

+ Open Source

+ From SOAP to AMF (Action Message Format)

+ 10 times faster than XML based protocols, how?

+ Previously known as Adobe LCDS







=== Remoting (RPC) ===

+ Instead of Contacting services, RPC components contact 'Destinations'

+ Destination: Manageable Service Endpoints

+ Managed using XML based configuration file

+ 'Remote Object' not possible without BlazeDS
( Adobe Flash Player blocks request to any external hosts, solution? )


+ crossdomain.xml required ( For apps that are not using BlazeDS )

+ XML file that indicates:
- Data and documents are available to SWF files served from certain/all domains
- Must be in 'web root' of the server


=== AMF (10 times faster!) ===

+ Compact binary format for data serialization/ deserialization and remote method invocation.

+ Object encoding controls how objects are represented in Action Message Format (AMF).

+ Representation that can be transferred over HTTP/HTTPS.

+ As data size increases the performance benefits of using BlazeDS increase exponentially.

+ AMF improves performance by
- Dramatically compressing the size of data transferred.
- Parsing binary data into objects in memory far more efficiently than parsing XML data.


=== Quick Brief ===

+ Message Agents:
- Message Producers & Consumers
- Exchange messages through a common destination

+ Channel and endpoints
- Formats, Translates messages into network-specific form.
- Delivers to the endpoint (on the server)
- Server-Side Channel Unmarshals messages
- Configuration settings ( XML files) at runtime

+ Message Broker
- Routes messages to the appropriate service based on its type

+ Channel Types



=== Channel Configuration ===

+ Configure channels using services-config.xml

+ AMF protocol use an optimization technique

+ Assign channel at runtime( AS Code) by creating a ChannelSet object, and adding a channel to it.

var cs:ChannelSet = new ChannelSet();
var channel:Channel = new AMFChannel(“name”, endpoint)
cs.addChannel(channel);
Remoteobject.channelSet = cs;



=== Remote Object components ===

+ Access methods of server-side java objects.

+ No need to specify 0bjects as operations in web services

+ Use RemoteObject component in MXML/AS

+ Server - Proxied access to an RPC service

+ Communication happens over a 'destination'

+ Configured in the remoting-config.xml
- RPC method or URL, channel, adapter

+ Asynchronous communication
- AsyncToken object

+ Http Service and web service use proxy-service.xml for configuration.
- Limit access to specific URL
- Provide Security


=== BlazeDS with Tomcat ===
+ Unzip the blazeds-turnkey file on to your C: drive
(Blazeds comes with Tomcat default.)

+ Create a new application: C:\blazeds\tomcat\webapps

+ Copy & paste the META-INF, WEB-INF folder from the samples (zip) file.

+ Store all your java class files in WEB-INF/classes folder

+ Configure remoting-config.xml under WEB-INF/flex/ for all your remoting related details (destinations) . Create a and a specify a

+ Configure messaging-config.xml under WEB-INF/flex for all your messaging (real-time) by adding your destination

+ For all other service related details use the proxy-config.xml

+ Give references of all these xml files in services-config.xml (done by default)

+ Run your application http://:/


:-)

Wednesday, January 07, 2009

Basic Eclipse plugins

Some update sites of useful plugins for Eclipse 3.4 (Ganymede) , but most of them can work with Eclipse 3.3 (Europa) and even 3.2 !
Just for not having to google them again :D


1/ SubVersioN client: Subversive Subclipse

http://subclipse.tigris.org/update_1.4.x/


2/ Project build: Ant Maven2 (m2eclipse)

http://m2eclipse.sonatype.org/update/


3/ Coding style: Checkstyle PMD

http://pmd.sourceforge.net/eclipse/


4/ Code coverage: Cobertura Emma (eclemma)

http://update.eclemma.org/


5/ Continuous integration: LuntBuild Hudson (hudson-eclipse)

http://hudson-eclipse.googlecode.com/svn/trunk/hudson-update/


6/ Unit test: JUnit TestNG

http://beust.com/eclipse/


7/ ORM framework: iBatis Hibernate (HibernateTools)

http://download.jboss.org/jbosstools/updates/stable/


8/ POJO framework: Seam Spring (SpringIDE)

http://springide.org/updatesite/


... (FlexBuilder, WTP, Unitils, DbUnit, liquidBase, etc ) ...

Monday, January 05, 2009

JavaCard quick notes [3]

=== Quy trình phát triển một "cardlet" ===

Nhúng sâu vào lý thuyết để hiểu tường tận cơ chế. Tiếp theo, mình note thêm về Qui trình phát triển ra một Cardlet
(Applet từ đúng kỹ thuật là JavaCard Applet, nhưng nó trùng với Java Web Applet, nên mình thích gọi là "cardlet" hơn).

Mô hình dưới đây sẽ khái quát qui trình phát triển mã nguồn, thử nghiệm và kết xuất ra đầu cuối cho thiết bị của một applet:



- Step 1: Bằng bất cứ một trình soạn thảo nào bạn cũng có thể tạo ra một applet theo cấu trúc mẫu. Hoặc đơn giản hơn thì có thể dùng các IDE hỗ trợ (eclipse + jcop plugin) để tạo ra một applet bao gồm tập các file .java và dùng trình biên dịch chuẩn build thành các .class file.

- Step 2: Bằng công cụ hỗ trợ (JCOP plugin hoặc JavaCard Develop Environmen - JCDE2) để test, debug trên môi trường ảo do công cụ thiết lập.

- Step 3: Khi tiến hành build applet, bộ công cụ cũng biên tập ra các file .cap và các file .export bằng bộ Java converter. Các file .cap, .export là những tài nguyên sẽ được dùng để cài đặt trực tiếp lên các thẻ thật, thành các applet thật trên chip JavaCard. Mỗi CAP file là thể hiện của một "package" đã được tạo. Nếu cardlet có kết hợp nhiều package, thì mỗi package sẽ convert thành một .cap file và 1 .export file.

- Step 4: Sau khi đã test, debug và kiểm tra cardlet hoàn tất, xem như cardlet đã sẵn sàng để được tải lên card. Tài nguyên là các cap file và export file sẽ được dùng để tải lên card thật.

Saturday, January 03, 2009

PostgreSQL on HardyHeron

This is for Ubuntu (8.04 LTS) , but can be also applied for others.


=== Install PostgreSQL (8.3) ===

1/ Install the DBMS :

$ sudo apt-get install postgresql postgresql-contrib

(the postgresql-contrib is optional, it's just some additional facilities for Postgres)


2/ Install the GUI client (pgadmin or pg-client) to manage :

$ sudo apt-get install pgadmin3 postgresql-client


3/ Change password for user 'postgres' :

$ sudo su postgres -c psql
postgres=# ALTER USER postgres WITH PASSWORD 'password';
postgres=# \q


4/ Enable access from outside localhost (if needed) :

To do this, you may edit either postgresql.conf or pg_hba.conf or pg_ident.conf , their location in Ubuntu is /etc/postgresql/8.3/main/ . Perhaps the K.I.S.S way is to add a line into pg_hba.conf to pick the corresponding IPv4 subnet to be allowed:

host all postgres 192.168.1.0/24 md5

(That line means all private IPs 192.168.1.x will be allowed to connect Postgres)

To make sure the change is applied, restart the deamon :

$ sudo /etc/init.d/postgresql-8.3 restart



=== Some basic PostgreSQL commands ===
(to be updated)

Friday, January 02, 2009

JPA quick notes

(retrieved from Mike Keith and his famous book "Pro EJB3 - Java Persistence API" )


The Java Persistence API (JPA) is the Java standard for mapping Java objects to a relational database. Even though proprietary mapping products like Hibernate and TopLink still exist, they are now focused on providing their functionality through the JPA API, allowing all applications to be portable across JPA implementations. This short article will give users enough to understand the basics of JPA and get started writing JPA applications. It covers entities, identifers, O-R mappings, using an entity manager, creating and executing queries, and confguration of the persistence.xml file.




The basic unit of persistence in JPA is the entity, which is nothing more than a regular Java class with metadata to describe how its state maps to the database tables. Metadata may be in the form of annotations on the entity class itself, or it may be an accompanying XML file, but we are using annotations since they are easier to specify and understand.


Every entity class should have an @Entity marker and an identifier field, indicated by @Id, that is mapped to the primary key column in the database. When a field contains simple data and maps to a regular column in the database we call it a basic mapping, thus an identifier field is a special kind of basic mapping. When an entity has a field that references one or more other entities, that field maps to a foreign key column, and is called a relationship field. Other than the identifier field, basic mappings do not need to be annotated, but relationships must be specified by their relationship cardinality.

Defaulting rules in JPA mean that you are not required to specify table names and column names that an entity is mapped to. If you are not happy with the JPA-assigned defaults then you can always override them through the use of additional mapping
metadata. For example, by putting @Table on the entity class you can make the table name explicit, and by annotating a basic mapping feld with @Column you can defne the particular column that maps the state in that feld. Likewise @JoinColumn is used to override the name of the foreign key column for relationship references.


//Listing 1 - pet entity
@Entity
@Table(name="PET_INFO")
public class Pet {
@Id
@Column(name="ID")
int licenseNumber;
String name;
PetType type;
@ManyToOne
@JoinColumn(name="OWNER_ID")
Owner owner;
//...
}

//Listing 2 - pet owner entity
@Entity
public class Owner {
@Id
int id;
String name;
@Column(name="PHONE_NUM")
String phoneNumber;
@OneToOne
Address address;
@OneToMany(mappedBy="owner")
List pets;
//...
}

In a bidirectional relationship pair, such as the @OneToMany relationship in Owner to Pet and the @ManyToOne relationship back from Pet to Owner, only one foreign key is required in one of the tables to manage both sides of the relationship. As a general rule, the side that does not have the foreign key in it specifes a mappedBy attribute in the relationship annotation and specifes the feld in the related entity that maps the foreign key.




The EntityManager class is the main API in JPA. It is used to create new entities, manufacture queries to return sets of existing entities, merge in the state of remotely modified entities, delete entities from the database, and more.
There are, generally speaking, two main kinds of entity managers:

* container-managed : The managed entity managers may only be obtained within a container that supports the JPA Service Provider Interface (SPI).

* non-managed : Non-managed entity managers may be obtained in any environment where a JPA provider is on the classpath. Listing 3 shows an example of obtaining
a non-managed entity manager by frst obtaining an EntityManagerFactory instance from the Persistence root class.


//Listing 3 – Obtaining a non-managed entity manager
import javax.persistence.*;

//...
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PetShop");
EntityManager em = emf.createEntityManager();
//...
em.close();


In Listing 4 we see how a standard host container can provide a simpler way to obtain an entity manager. The only catch is that this is only supported within standard Java EE components (or containers that are compliant to the JPA container contract), so this example uses a stateless session bean.


//Listing 4 – Injecting a managed entity manager
@Stateless
public class MyBean implements MyInterface {
@PersistenceContext(unitName="PetShop")
EntityManager em;
...
}






The basic purpose of an entity manager is to perform create/
read/update/delete (CRUD) operations on entities. Listing 5
shows methods that perform these operations.


//Listing 5 – Invoking the entity manager
public Pet createPet(int idNum, String name, PetType type) {
Pet pet = new Pet(idNum, name, type);
em.persist(pet);
return pet;
}

public Pet findPet(int id) {
return em.fnd(Pet.class, id);
}

public Pet changeName(int id, String newName) {
Pet pet = this.fndPet(id);
pet.setName(newName);
return pet;
}

public void deletePet(int id) {
Pet pet = this.fndPet(id);
em.remove(pet);
}


Note that fnding the pet is the frst step to being able to perform update and delete operations on it. Also, an update does not even involve invoking the entity manager, but requires reading the pet, loading it into the entity manager and then
modifying it. The modifcation will be refected in the database when the transaction is committed.




Since we just mentioned transactions, but didn’t explain them, now would be a good time to state that JPA supports two different kinds of transactions:

* JTA container transactions : Used when running in container mode

* resource local transactions : Typically used when running in non-container
mode.


JTA transactions are started and committed using the usual container techniques, either calling the UserTransaction API or making use of container-managed transaction demarcation in EJB or Spring. For example, if the methods in Listing 5 were in a session bean that had a Required transaction attribute setting then a transaction would be started at the beginning and committed at the end of each client method invocation.


When using local transactions the transaction must be demarcated manually by invoking on the EntityTransaction instance accessed from the entity manager. Each of the three
methods in Listing 5 that caused the database to change would need to have begin and commit calls, as shown in Listing 6 for the persist method. Methods that only read from the database do not need to occur within a transaction.


//Listing 6 – Using EntityTransaction
public Pet createPet(int idNum, String name, PetType type) {
em.getTransaction().begin();
Pet pet = new Pet(idNum, name, type);
em.persist(pet);
em.getTransaction().commit();
return pet;
}











Dynamic queries are objects that are created from an entity manager, and then executed. The query criteria are specifed at creation time as a Java Persistence Query Language (JPQL) string. Before executing the query a number of possible configuration method calls may be made on the query instance to configure it. Listing 7 shows an example of creating and executing a query that returns all the instances of Pet, or the frst 100 if there are more than 100 instances.


//Listing 7 – Creating and executing a dynamic query
Query q = em.createQuery("SELECT p FROM Pet p");
q.setMaxResults(100);
List results = q.getResultList();


A named query is a query that is defned statically and then
instantiated and executed at runtime. It can be defned as an
annotation on the entity class, and assigned a name that is
used when the query is created. Listing 8 shows a named query
defned on the Pet entity.


//Listing 8 – Defning a named query
@NamedQuery(name="Pet.fndByName",
query="SELECT p FROM Pet p WHERE p.name LIKE :pname")
@Entity
public class Pet {
//...
}


The last identifer is prefxed with a colon (:) character to indicate
that it is a named parameter that must be bound at runtime
before the query can be executed. Listing 9 shows a method
that executes the query by frst instantiating a Query object
using the createNamedQuery() factory method, then binding the pname named parameter to the name that was passed into the method, and fnally executing the query by invoking getResultList().


//Listing 9 – Executing a named query
public List fndAllPetsByName(String petName) {
Query q = em.createNamedQuery("Pet.fndByName");
q.setParameter("pname", petName);
return q.getResultList();
}



Some Query APIs :






The Java Persistence Query Language is SQL-like, but operates over the entities and their mapped persistent attributes instead of the SQL schema. Many of the SQL functions and even reserved words are supported in JP QL.
There are three basic types of JP QL statements, of which the
frst is monstrously the most popular and useful: selects, bulk
updates and bulk deletes.

1. select_clause from_clause [where_clause] [groupby_clause]
[having_clause] [orderby_clause]

2. update_clause [where_clause]

3. delete_clause [where_clause]




Without counting the mappings from the entity to the database tables, there is really only one unit of JPA confguration needed to get your application up and running. It is based on the notion of a persistence unit, and is confgured in a fle called persistence.xml, which must always be placed in the META-INF directory of your deployment unit. Each persistence unit is a confguration closure over the settings necessary to run in the relevant environment. The parent element in a persistence.xml
fle is the persistence element and may contain one or more persistence-unit elements representing different execution confgurations. Each one must be named using the mandatory persistence-unit name attribute.

There are slightly different requirements for configuring the persistence unit, depending upon whether you are deploying to a managed container environment or a non-managed one. In a managed container the target database is indicated through the jta-data-source element, which is the JNDI name for the managed data source describing where the entity state is stored for that confguration unit. In a non-managed environment the target database is typically specified through the use
of vendor-specific properties that describe the JDBC driver and connection properties to use. Also, in non-managed environments the entity classes must be enumerated in class elements, whereas in managed containers the entity classes will be automatically detected. Examples of container and non-container persistence unit elements are indicated in the Listings.




Enjoy,

Thursday, January 01, 2009

CRUD or BREAD ?

Well, applications nowadays seem to always works with a certain database system (mostly Relational DBMS). And then 90% the work of coder/developer is to select, insert, update and delete the data from database. Those operations are so popular that people refer to them as CRUD , or some other terms: BREAD, ABCD, VADER, ...


IMHO the BREAD term (Browse, Retrieve, Edit, Add, Delete) is better than CRUD (Create, Read, Update, Delete) .
I will explain later.