Saturday, December 30, 2006

Entity Management for EJB3 Stateless Session Beans

@Stateless
public class StatelessSessionBean implements LocalInterface {
@PersistenceUnit(name="PUName")
private EntityManager em;
// operations on the entities, such as creating, editing, destroying, and finding.
}
  • Creates a container-managed entity manager.
  • Entity manager is transaction-scoped (meaning persistence contexts are managed by a container-controlled JTA transaction).
  • Entity manager is stateless (which is why they can be stores in any Java EE component).
  • Transaction initiated when the session bean is first invoked, and its lifecycle managed by the container.

Friday, December 29, 2006

17 Things Linux Does Better Than Windows

In June 2007, the French parliament is moving their computing base to the Linux operating system, Firefox browser, and OpenOffice.org productivity suite. It's not clear whether the whole government will eventually move away from Windows, but this is law in France.
I've had a love-hate relationship with Linux over the years, and although I still develop/run everything on Windows, there's a lot Linux offers that I wish Windows would do better:
  1. More flavors of Linux from different vendors = more competition = better software. With Windows, you are stuck with only Microsoft. Linux flavors include Linspire, Red Hat, SuSE, Ubuntu, Mandr*, Slackware, etc.
  2. Customizability to special purpose builds. If I am installing a server, I probably need less than the bulk Windows forces you to install for the same purpose. Linux builds exist that can run off floppies; with Windows, even installs can no longer be initiated from floppies.
  3. Optional GUI for a fully functional OS means increased efficiency and allows for easier remote control administration. With Windows, the GUI is pretty much required for everything; DOS and the Recovery Console might help, but we all know how limited they are.
  4. More robust shell in Linux and the option to use multiple shells. In Windows, DOS is all you got. Their new WSH is heavily dependent on Windows itself that it's almost a program within Windows than a standalone framework.
  5. Linux is essentially free for a basic home machine. You purchase support and extra packages for server platforms, but all in all, for the same level of performance and features, you spend about 1/7 the cost of Windows on Linux. Windows desktop versions start at $200. Then there's the question of ongoing costs - maintenance, bugs, viruses, and upgrades - Linux costs less in this regard.
  6. More freedom with the software you purchase: Windows allows one copy per machine (WPA/Genuine Windows) and still essentially owns your copy of the OS. With Linux you can install any number of bases with no strings attached.
  7. Smarter installs to multihomed systems: if you ever need to install Windows and Linux operating environments, you start with Windows, then Linux. Somehow, Windows kills off bootstraps of OSes it does not recognize (read non-Microsoft), whereas Linux accommodates other OSes with customizable booters.
  8. Fewer viruses, spyware, and adware. And contrary to the myth that it's because the installed base is larger, consider the Apache web server (60% of web servers) which gets significantly fewer security problems than Microsoft's IIS. Thus, Linux is more secure. Also, some default installations of Windows allow a no-password account (with Admin rights).
  9. Certification stability. For those that have navigated the certifications world, you know how soon Windows OS certification expire. Microsoft releases a new OS every 3-5 years, making certifications on older OSes obsolete. A Linux certification goes much further.
  10. I've been irked by the option to buy support and patches from Microsoft - for Windows! What the hell is wrong with this picture? If you make software, please don't charge people for fixes to your won mistakes. Sure lost updates are free, but as a developer, I know I've hit the price wall in this regard. Linux support through forums and other user bases removes this problem (though sometimes hard to come by).
  11. Wider diversity of hardware. Windows no longer runs on MIPS and Alpha processors, for example. Linux can run on even the oldest and slowest of machines - has fewer hardware requirements. Have you heard of Linux fro iPods? Try iPodLinux ... an OS that can run on iPod power.
  12. Better clustering support - you can essentially run a supercomputer using Linux for a small fraction of the cost of using windows solutions.
  13. Linux is the original true multiuser environment. Windows was originally designed as a single-user environment, but has made strides with Terminal Services/Remote Desktop/Remote Assistance. Only the latest (Windows 2003 or later) have come close.
  14. Unlimited logical partitions in Linux, as opposed to 32 for Windows. Well, there are theoretical limits (and those imposed by hardware/software constraints), but it's good to be able to create 100 small partitions that can all be used in the OS. Windows limits you to what you can name them (A-Z) - DFS may add some capabilities.
  15. Ability to schedule (and even abort) shutdowns. I can't tell you how many times I've wished I could stop a shutdown or set it to run at a certain time (without having to create a batch file and use the Scheduler program to set it - not streamlined).
  16. Linux is modular by design, so plugins and failures are localized. Windows was originally a monolithic design, although 'modular' features are offered though DLLs and COMs, and other 'plug in' models. Still, when one area suffers, it can be felt everywhere in Windows (think Blue Screens).
  17. Linux is not constrained by the RPC model, which runs all programs as network components. It makes it easier to locate programs/services across the network, but for applications without networking features, there's no need to be 'network borne' locally. Like, there's shouldn't be a need to rely on ports/sockets when 2 applications only need to run and communicate on the same machine, networkless.
That's my two cents. In the coming year, I am brushing up again on my Linux skills (hot in the job market right now) and might even pursue a Linux certification. We shall see.

Friday, December 22, 2006

Customizing Simple EJB 3.0 Entities and Tables

The Java Persistence API does a good job mapping entities and fields in default mode to tables in a database. But sometimes you need to specify the name and columns of a table (maybe to take advantage of an existing schema). Using annotations in your entities makes this easy to implement. As an example, let us suppose you need to represent an employee in a database:
With EJB 3.0, you begin by writing an entity for the employee. The Employee class is a basic POJO, but annotations added to it are what make it persistable as we desire.

@Entity
@Table(name="EMP")
public class Employee implements Serializable {
@Column(name="NAME")
private String name;
@Column(name="SAL")
private long salary;
@Column(name="COMM")
@Basic(fetch=FetchType.LAZY)
private String comments;
@Basic(fetch=FetchType.LAZY)
@Column(name="PIC")
@Lob
private byte[] picture;
@Column(name="HIRED")
@Temporal(value = TemporalType.DATE)
private Date dateHired;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="EMP_ID")
private Long id;
@Transient
private transient String nameString;

@Override
public int hashCode() { ... }
@Override
public boolean equals(Object object) {...}
@Override
public String toString() {...}
}

The simple class above is much of what you need to represent an entity in a database. @Entity tells the persistence provider that the data of this class shall be saved in the database. @Table specifies which table shall be used. The entity must be serializable so that RMI and reflection features of Java technology can be used.
Within the table, @Column names the column for each of the attributes that shall be persisted. You can use lazy fetching to improve performance when reading entities from databases - lazy fetching skips reading columns in regular reads until the attribute is actually accessed. So it is recommended for attributes that will not be used much - in our example, pictures and comments.
The API makes it really easy to work with large objects (BLOBs and CLOBs). When we upload a picture for an employee, it'll be a huge resource. @Lob is used to indicate that a special column be allocated in the table for this kind of data.
@Temporal is used to convert dates to and from SQL types. I would not need it if I used javax.sql.Date type to represent dates in my application.
@Id specifies that the attribute/column is the primary key in the table. @GeneratedValue indicates that the primary key should be automatically generated for us. AUTO allows the persistence provider to choose a strategy (either SEQUENCE, IDENTITY, or TABLE), although you can use them directly yourself.
@Transient or the transient qualifier for properties indicates that the attribute should not be persisted. Variables like this are used to hold results of processes that use other variables and not expected to change much - helps improve efficiency if you don't have to recalculate data every time it is requested.
As usual, you need to implement hashCode(), toString(), and equals(), overriding what Object provides. Also advisable is implementing the Comparable interface on the class for sorting algorithms.

This is a basic single-entity implementation; we know that seldom do applications have single entities like this, so in the next few posts, relationships will be summarized.

Saturday, December 09, 2006

Part III(a): Entertain(r) to Become User-Based - Requirements

The Entertain(r) application we've been developing (see Part II) has a new set of requirements - apart from managing movies only:
(1) It needs to become user-based. This includes the ability to add, edit, delete, and find users.
(2) Users must be logged in to view pages or do anything else on the system.
(3) All pages should have a standard menu that includes links to lists of users, movies, and the home page.
(4) Have a generic error page for the application.
(5) Handle database cell overflow problems.

Fullfilling these requirements will demonstrate how to use servlet filters, call JavaBeans from JSP pages, use EJB 3.0 stateless beans, and configure a generic error page for the application using NetBeans 5.5. At the end of the exercise, a basic infrastructure will exist that we can use to further explore EJB 3.0 features.

#1: a user entity must be created, with an accompanying session bean. It'll use the persistence unit we already have. Also, a servlet that does user-oriented business logic needs to be created (adding, editing, deleting, finding).
#2: Create a servlet filter that checks all requests for authentication and redirects to the login page if not logged in.
#3: Create a servlet filter that uses a response wrapper to add the menu to the response.
#4: Configure a JSP page as the error page and update the web descriptor for the web module.
#5: Check for content length and truncate, or redirect to the error page.

An auterior goal is also to find out how long it takes to add such support to an application