Sunday, October 18, 2009
Smart technical Questions
http://newbielearnlinux.googlepages.com/SmartQuestions
(http://sites.google.com/site/newbielearnlinux2/SmartQuestions)
Warning: this style should NOT be applied when talking with girls, unless you are trying to dump her :-)
Sunday, May 03, 2009
JavaScript gotcha Overloading
Thường các gotcha lập trình này cần phải có nhiều kinh nghiệm mới phát hiện được (hoặc nhờ đọc bài viết của người có kinh nghiệm, hehe) . Nếu bạn đã từng trải qua hàng đống giờ dò lỗi (debug) vì 1 gotcha nào đó, thì hẳn sẽ rủa "mấy tay nào đó" làm cái chức năng ngớ ngẩn làm mất bao nhiêu công sức của mình. Do đó nếu có thời gian cũng nên xem thử các gotcha liên quan đến công việc của mình, phòng khi gặp trường hợp như trên.
JavaScript thì theo tôi biết có khoảng 15 gotcha dễ gặp, và overloading sẽ là gotcha đầu tiên trình bày ở đây.
(to be cont)
Sunday, April 19, 2009
XPath quick notes
The most useful path expressions to select nodes:
| Expression | Description |
|---|---|
| nodename | Selects all child nodes of the named node |
| / | Selects from the root node |
| // | Selects nodes in the document from the current node that match the selection no matter where they are |
| . | Selects the current node |
| .. | Selects the parent of the current node |
| @ | Selects attributes |
XPath wildcards to select unknown XML elements.
| Wildcard | Description |
|---|---|
| * | Matches any element node |
| @* | Matches any attribute node |
| node() | Matches any node of any kind |
XPath axes defines a node-sets relative to the current node.
| AxisName | Result |
|---|---|
| ancestor | Selects all ancestors (parent, grandparent, etc.) of the current node |
| ancestor-or-self | Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself |
| attribute | Selects all attributes of the current node |
| child | Selects all children of the current node |
| descendant | Selects all descendants (children, grandchildren, etc.) of the current node |
| descendant-or-self | Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself |
| following | Selects everything in the document after the closing tag of the current node |
| following-sibling | Selects all siblings after the current node |
| namespace | Selects all namespace nodes of the current node |
| parent | Selects the parent of the current node |
| preceding | Selects everything in the document that is before the start tag of the current node |
| preceding-sibling | Selects all siblings before the current node |
| self | Selects the current node |
Sunday, March 22, 2009
Java basic videos
http://www.mediafire.com/?5r4mmsaw5bn
http://www.mediafire.com/?woeyul1ltqk
http://www.mediafire.com/?ylujqjaz5iq
http://www.mediafire.com/?p4gyce0s2lf
Password mediafire :
mgsvn
HAVE FUN !
Thursday, March 19, 2009
Why Eclipse IDE
A PICTURE IS WORTH A THOUSAND WORDS !
Debug Java ( //www.ibm.com/developerworks/opensource/library/os-eclipse-platform )
Customize perspective, views, hotkey... ( //www.ibm.com/developerworks/opensource/library/os-eclipse-master1/ )
Customize formatting ( //www.ibm.com/developerworks/opensource/library/os-eclipse-master3/ )
Refactoring 2003 ( //www.ibm.com/developerworks/library/os-ecref/ ) :
Integrate SVN/CVS ( //www.ibm.com/developerworks/opensource/library/os-ecl-subversion/ )
Debug PHP ( //www.ibm.com/developerworks/opensource/library/os-ecbug/ )
Debug C/C++ ( //www.ibm.com/developerworks/library/os-eclipse-cdt-debug2 )
Debug Python ( //www.ibm.com/developerworks/opensource/library/os-ecant/ )
Debug ActionScript ( //swingchen.bokee.com/6028838.html )
Debug ColdFusion ( //www.ibm.com/developerworks/opensource/library/os-eclipse-cfeclipse/ )
And Ruby ( //www.ibm.com/developerworks/opensource/library/os-eclipse-rdt/ )
even .NET ! ( //www.ibm.com/developerworks/opensource/library/os-eclipse-migratenetvs/ )
and more... ( //www.ibm.com/developerworks/opensource/library/os-eclipse-iphone/ )
Rocks solid on multi-OS : ( //www.ibm.com/developerworks/opensource/library/os-eclipse-osxjava/ )
Other IDEs which turn out to use Eclipse codebase :
FlexBuilder (Adobe)
Websphere Studio Application Developer (IBM)
JDeveloper (Oracle)
JBuilder 2007+ (Borland)
WebLogic workshop (BEA)
ZendStudio (Zend)
Aptana (Aptana)
PowerDesigner (Sybase)
MyEclipse (Genuitec)
Rational XYZ (IBM)
Parasoft XYZ (Parasoft)
. . .
...
Tuesday, March 10, 2009
Collaboration online services
Bookmarks
http://foxmark.com
Technical notes
http://pastebin.org
To-Do list
http://tadalist.com
IRC gossips:
http://mibbit.com
Compilers:
http://codepad.org
and more...
Sunday, March 08, 2009
Java mess detector
But do you have any comparision or advice for me about other tools: FindBugs, Hammurapi, TFTP, JLint, ...
I just want to make a list of Top 5 tools that is really useful in each catergories of software development (in a certain language, such as Java).
RANK ? : PMD
RANK ? : Checkstyle
RANK ? : FindBugs
RANK ? : Hammurapi
RANK ? : TFTP
Wednesday, February 18, 2009
Java Exception revisited
Wednesday, February 11, 2009
Quote for developers
"Your organization is going to spend a lot more on somebody - you or somebody else - reading what you're writing right now than they are ever going to spend on you writing it,"
"You're going to read that code yourself 10 to 100 times for every time you write it, so it's worth taking the trouble to make it readable. You're going to modify it five times after you write it the first time, so it makes sense to make it easy to change. And because you can't predict the future, it doesn't make any sense to build a lot of stuff you don't need right away. These are unchanging principles of software development, and nothing about applying the words 'scripting' or 'model driven' or whatever the programming metaphor du jour happens to be changes any of that."
QFT,
Monday, January 12, 2009
Java coding convention [2]
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ì:
Saturday, January 10, 2009
JavaCard quick notes [4]
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
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
+ 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
+ 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
Just for not having to google them again :D
1/ SubVersioN client:
http://subclipse.tigris.org/update_1.4.x/
2/ Project build:
http://m2eclipse.sonatype.org/update/
3/ Coding style:
http://pmd.sourceforge.net/eclipse/
4/ Code coverage:
http://update.eclemma.org/
5/ Continuous integration:
http://hudson-eclipse.googlecode.com/svn/trunk/hudson-update/
6/ Unit test:
http://beust.com/eclipse/
7/ ORM framework:
http://download.jboss.org/jbosstools/updates/stable/
8/ POJO framework:
http://springide.org/updatesite/
... (FlexBuilder, WTP, Unitils, DbUnit, liquidBase, etc ) ...
Monday, January 05, 2009
JavaCard quick notes [3]
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.
Friday, January 02, 2009
JPA quick notes
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
//...
}
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 ?
IMHO the BREAD term (Browse, Retrieve, Edit, Add, Delete) is better than CRUD (Create, Read, Update, Delete) .
I will explain later.
Wednesday, December 31, 2008
Java annotations revisit
=== Java Annotations ===
Annotations are presented as metadata – that is data about data. In the case of Java this means that they provide information about various elements of a Java class. For example, they may annotate a method, class or instance variable. One example of an annotation is to note that a method has been deprecated, or that it overrides a method in the superclass. These annotations can then be used by an annotation processing tool (such as APT), or an IDE (such as Eclipse) or indeed a framework, to validate, configure or add to the original Java. For example, if you have annotated a method as overriding a parent class method, then the annotation processing can confirm that you are indeed overriding a method.
There are seven annotations provided in the J2SE 5.0 release (see the annotations guide here; these are provided in two packages, java.lang and java.lang.annotation:
In the package java.lang there is:
• @Deprecated – indicates that the associated Java element has been deprecated. It is an alternative to using the Javadoc @deprecated element. A deprecated method or class is essentially one that should no longer be used and that is not guaranteed to be available in future versions of the software. It is thus often useful to know that you are using “old” versions of an API. Although the use of the Javadoc tag already allows many tools (such as Eclipse) to indicate that a language feature is deprecated, the use of the @Deprecated annotation makes this simpler and allows a wider range of tools to report on the use of deprecated features.
• @Override - indicates that the method should override a method in the superclass.
• @SuppressWarning – directs the compiler to suppress the specified warning.
In the package java.lang.annotaiton:
• @Documented – directs tools to automatically generate Javadoc for the annotated element (e.g. a method or variable).
• @Inherited – this indicates that the associated annotation is inherited by subclass of the current class.
• @Retention – indicates how long annotations with the annotated type are to be retained. For example, a retention type of RUNTIME indicates…
• @Target – This indicates the Java element to which associated annotations apply.
It is also possible to extend the set of annotations available by defining your own annotations. This enables project, task and company specific annotations to be created.
=== What are annotations for? ===
Annotations are intended to provide three basic facilities. These facilities are:
• The provision of additional semantics for various class elements. This additional semantic information can help developers to understand the intent behind some feature or implementation detail.
• The execution of additional compile time checks that ensure various constraints are met.
• The support of additional code analysis by annotation-aware tools.
None of these requirements are new and indeed many developers have found ways of overcoming the lack of any annotation-like feature in previous versions of Java.
For example, I have tended to make extensive use of Marker Interfaces over the last few years. These are interfaces that may not contain any methods, but are used to denote a particular concept or entity within an application. This is not a particularly radical idea and indeed there is an example of such an interface in the Java language itself - the java.io.Serializable interface. This interface is a marker interface in that it does not require any methods to be implemented but indicates that a class is capable of being serialized via the Java Serialization mechanism.
Such marker interface can now be replaced with annotations. We can define our own annotation that can be used to mark a class as being a particular concept or entity etc.
=== Using annotations ===
Annotations are straightforward to use; they merely require that an appropriate annotation type be placed directly before the Java language element being annotated. For example:
@Override
public String getName() {
return this.name;
}
}
This means that when this code is compiled, or when it is analysed by tools such as Eclipse, a check can be made to ensure that the method getName() does override a method in the class Person’s superclass. In this particular case, the class Person extends the class Object as a default. The class Object does not contain a method getName() and thus it does not override such a method. This therefore results in an error message being generated. For example, in figure 1 Eclipse has identified that the method getName() should override a method in the parent class and has provided a pop up to this effect.
However, marking which methods you expect to override parent class methods is probably a step two far for many developers. A rather more useful annotation may be the @SuppressWarnings annotation.
The @SuppressWarnings annotation can be very useful if you have some code that uses a deprecated method or class (possibly because it has been in your system since before that method was deprecated) and you do not want the compiler to churn out lots of warnings about using deprecated APIs. By using the @SuppressWarning annotation and the parameter value “deprecation” it is possible to suppress (turn off) the production of the deprecated warning. For example:
public static void terminateProcess() {
Thread.currentThread().stop();
}
=== Defining your own annotations ===
You can easily create your own annotations by defining a new annotation type. This is done using a new piece of language syntax, the @interface key word. For example, to define a new annotation @Auditor we would define the following annotation type.
}
Note that although the syntax for this is almost exactly the same as for a standard interface, the “@” symbol at the start of the keyword changes this to be an annotation declaration. When you compile the resulting Auditor.java file this creates a standard Auditor.class file. If you place this class file on your class path, then you can use this new annotation type within your Java code. For example, if you place the @Auditor just before the class declaration, this marks the class as being of the entity type Auditor. This is illustrated in Figure 2.
You can also define parameters that can be used with annotations, and accessor methods for retrieving information about the options specified with an annotation.
=== Drawbacks of Annotations ===
Annotations are not without their drawbacks. Not least of which is that they are not really metadata – that is they are not data about data – they are data about classes, methods, instance and static variables etc.
=== Window dressing ===
As such annotations are syntactic sugar – they coat the elements of a class without actually telling you anything in detail about that class (you can use the reflection API for some of that). Thus they provide guidance to processors, tools and frameworks to help in the analysis, compilation or deployment of that software.
Inheritance
One of the major features of an object-oriented system is inheritance. You can subclass a class, and subclass an interfaces – but you can’t subclass annotations.
=== Null values ===
If a null value should be treated as an un-initialized value then annotations are somewhat awkward in the way they handle these – rely on the developer to provide a way of indicating un-initialised rather than initialised to null.
=== Values in General ===
These are somewhat limited in what you can use – although in the main this is fine.
=== Annotations hold constants ===
The values used with annotations are hard coded rather than variable. Thus if an annotation takes a literal value of 40 – then that value is now hard coded into your program.
=== Annotations and code synchronization ===
Just as with Javadoc comments themselves, annotations need to be maintained to reflect any code changes that may occur. However, as we all know, it is all too easy to change the source code and not to update the associated Javadoc (even when they are next to each other). Exactly the same is true for annotations. If the code relating to an annotation changes, then the associated annotation may also need modification. This may not be as straightforward as it seems. For example, if I rename a method in a class I am working on, then this may impact on another class, that I may know nothing about; if that class requires that one of its methods overrides mine (due to the use the @Override annotation). Of course this may be what is desired or it may not! As you can define your own annotations this situation may become much worse, with significant repercussions for on-going maintenance, clarity and general stability of the code.
=== Summary ===
So where does that leave the question “To Annotate or not to Annotate?”. In essence, as with many things in life, annotations can be very useful but should not be over used or abused. They can add extremely useful additional information to Java code that can be analysed by tools, frameworks, analysers as well as developers themselves – but they should not be used without due consideration.
(main reference: TheRegister)
See also :
http://javabeat.net/articles/30-annotations-in-java-50-1.html
http://www.developer.com/java/other/article.php/10936_3556176_1
http://www.oracle.com/technology/pub/articles/hunter_meta.html
...
Monday, December 29, 2008
JavaCard quick notes [2]
=== Các lỗi thường gặp với JCOP ===
Sau một hai buổi mày mò lăn xả với JCOP, mình trở về với thân thể trầy xước tả tơi, dưới đấy là vài kinh nhiệm mình gặp phải và cách xử lý
1 - Lỗi upload ".cap" file không thành công.
- Build file cap không thành công, không có file .cap để upload.
Xử lý:
- Từ menu Window->Preferences..-> Java->Compiler
- Hiệu chỉnh "Compiler Complance level" -> 1.5
- Build lại project của bạn và Run.
2 - Lỗi không thể send các command.
Thông báo lỗi:
- "CLA value not supported"
- "INS value not supported"
Lý do:
- process() của bạn hiện tại không bắt, xử lý được với các mã CLA/INS lệnh theo yêu cầu.
Thông báo lỗi:
- "Conditions of use not satisfied"
Lý do: bạn phải /select applet mới có thể bắt đầu truyền các command hoặc applet chưa được xác thực (nếu có)
3 - Lỗi "No precise diagnosis"
Đây là lỗi làm "điên người" nhất mà mình tạm cho 1 lý do tạm là .. trình biên dịch JC còn củ chuối. Khi gặp lỗi này, bạn nên xóa mọi hành động vừa mới làm và bắt đầu cẩn thận lại từ bản backup gần nhất :D, nôm na ra là .. bó hand
Vài lỗi nhỏ trên là cơ bản, sẽ còn lỗi nhiều nữa, mình sẽ liệt kê thêm nếu gặp phải
=== Vòng đời của 1 "cardlet" ===
Trước tiên lưu ý: "Cardlet" là cách gọi của mình về applet của JavaCard, chưa phải thuật ngữ chính thức.
Theo đặc điểm kỹ thuật, vòng đời của một JavaCard Applet bắt đầu từ khi "em" được đăng ký vào card với phương thức Applet.register() . JCRE (JavaCard Runtime Environment) sẽ tương tác với applet thông qua các phương thức tĩnh của applet là: install, select, deselect và process.
Phương thức install():
Khai báo:
- Khi applet được cài đặt vào JC, phương thức install được thực thi một lần duy nhất cho mỗi thể hiện của applet. Các phương thức khởi dựng không nên được truy cập một cách trực tiếp mà phải thông qua phương thức install. Nhiệm vụ chính của phương thức install là tạo thể hiện của applet thông qua các constructor và đăng ký applet với JCRE thông qua phương thức register(). Chỉ khi được đăng ký thành công, JCRE mới có thể cho phép thao tác lệnh APDU với applet.public static void install(
byte[] bArray, short bOffset
, byte bLength )throws ISOException;
Phương thức register(..):
Khai báo:
protected final void register()throws SystemException;- Phương thức này được dùng để đăng ký một thể hiện của ứng dụng "cardlet" với JCRE với một mã (AID) xác định. Mã AID xác định bởi một chuỗi Hexadecimal, có độ dài trong khoảng 5-11 bytes (1byte = 8bits). Mã AID này là tham số đầu vào cho lệnh Select applet. Thông thường, phương thức register() được gọi từ thân của phương thức install() để applet được đăng ký với JCRE 1 lần cho mỗi card.
protected final void register(
byte[] bArray,short bOffset
,byte bLength)throws SystemException;
Phương thức select():
Khai báo:
public boolean select(); - Phương thức select() cho phép chuyển quyền nhận lệnh cho một thể hiện của Applet. Phương thức select applet được JCRE thực thi khi JCRE nhận được lệnh SELECT FILE APDU cùng một mã Applet từ thiết bị. Việc select Applet sẽ chuyển trạng thái applet từ deselect -> select và cho phép applet nhận các lệnh từ bên ngoài thông qua phương thức process() do JCRE chuyển giao. Tuy nhiên, trước khi select Applet, JCRE sẽ tự động thực hiện hành động deselect() một (hoặc các) applet đã được select trước đó.Phương thức process():
Khai báo:
public void process(APDU apdu) throws ISOException;- Sau khi được select(), tất cả các lệnh APDU sẽ được JCRE chuyển cho Applet thông qua phương thước process(). Các nhân xử lý của applet sẽ được thể hiện (hoặc phân hướng xử lý) ở phương thức này. Từ đây, các thao tác dữ liệu, nhận và trả lệnh APDU được thực hiện trên vùng buffer có giới hạn đã được applet đăng ký trong hàm register().Phương thức deselect():
Khai báo:
public void deselect();- Phương thức được gọi thực thi bởi JCRE khi có yêu cầu hoặc khi có hành động select một Applet khác. JCRE sẽ tự động thực hiện deselect() Applet hiện tại.
- Khi có lỗi khi thực hiện deselect, JCRE sẽ tiếp nhận lỗi, và tại thời điểm đó, applet đã được deselect.
GoF Design Patterns [5]
Decorator
Visitor
(will be updated on demand)