Tuesday, April 26, 2011

Database Normalization

Database Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process:
* eliminating redundant data (for example, storing the same data in more than one table)
* ensuring data dependencies make sense (only storing related data in a table).

Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.

The Normal Forms

The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF.

First Normal Form (1NF)

First normal form (1NF) sets the very basic rules for an organized database:
* Eliminate duplicative columns from the same table.
* Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

Second Normal Form (2NF)

Second normal form (2NF) further addresses the concept of removing duplicative data:
* Meet all the requirements of the first normal form.
* Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
* Create relationships between these new tables and their predecessors through the use of foreign keys.

Third Normal Form (3NF)

Third normal form (3NF) goes one large step further:
* Meet all the requirements of the second normal form.
* Remove columns that are not dependent upon the primary key.

Fourth Normal Form (4NF)

Finally, fourth normal form (4NF) has one additional requirement:
* Meet all the requirements of the third normal form.
* A relation is in 4NF if it has no multi-valued dependencies.

Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.

If you'd like to ensure your database is normalized, explore our other articles in this series:

* Database Normalization Basics
* Putting your Database in First Normal Form
* Putting your Database in Second Normal Form
* Putting your Database in Third Normal Form

Thursday, April 7, 2011

Spring by examples

A nice to have link for for helping Spring developers get started with different Spring projects:
http://www.springbyexample.org/

Wednesday, April 6, 2011

Java portlets

Portlets are pluggable user interface software components that are displayed in a web portal. For example, a portlet may be a page element showing the wether forecast.

Note how the portlet occupies only a part of the portal page. This is the primary difference between a portlet and a servlet. A portlet is meant to occupy only a part of the web page. And a portal web page consists of multiple, different portlets.

A number of vendors provide commercial implementations of the portlet container. Some of the leading vendors are IBM, Oracle, Vignette Corporation, JBoss, and Software AG. These vendors provide standards-based implementations as well as extensions not yet approved by the standards body. In addition, a number of open-source portal solutions support JSR168, such as Apache's Jetspeed-2 Enterprise Portal

Tuesday, April 5, 2011

Java volatile

volatile keyword is used to indicate that a variable's value will be modified by different threads.

Declaring a volatile Java variable means:
  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
  • Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

We say "acts as though" in the second point, because to the programmer at least (and probably in most JVM implementations) there is no actual lock object involved. Here is how synchronized and volatile compare:

Difference between synchronized and volatile

Characteristic Synchronized Volatile
Type of variable Object Object or primitive
Null allowed? No Yes
Can block? Yes No
All cached variables synchronized on access? Yes From Java 5 onwards
When synchronization happens When you explicitly enter/exit a synchronized block Whenever a volatile variable is accessed.
Can be used to combined several operations into an atomic operation Yes Pre-Java 5, no. Atomic get-set of volatiles possible in Java 5.



An example:
public class StoppableTask extends Thread {
  private volatile boolean stopThread;

  public void run() {
    while( !stopThread ) {
      // do something
    }
  }

  public void stopMe() {
    stopThread = true;
  }
} 
 

Monday, April 4, 2011

Java threads

Important methods
* constructior Thread( ThreadGroup group, Runnable target, String name ) - If the target argument is null, this thread's run method is called when this thread is started.
* static int enumerate( Thread[] tarray ) - Copies into the specified array every active thread in the current thread's thread group and its subgroups.
* int getPriority();* join() - Waits for this thread to die.
* join( long millis ) - Waits at most millis milliseconds for this thread to die.
* run() - If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
* setDaemon( boolean on ) - Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the thread is started.
* sleep(long millis) throws InterruptedException - Causes the currently executing thread to sleep (temporarily cease execution). If any thread has interrupted the current thread, InterruptedException exception is thrown.
* start() - Causes this thread to begin execution. The result is that two threads are running concurrently.
* run() - If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
* stop() - Deprecated!
* interrupt() - If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
* suspend() - Deprecated!
*

The deprecated way:
    private Thread blinker;

    public void start() {
        blinker = new Thread(this);
        blinker.start();
    }

    public void stop() {
        blinker.stop();  // UNSAFE!
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (true) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

The correct way:
    private volatile Thread blinker;

    public void stop() {
        blinker = null;
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    } 
 
There are two ways to create a new thread of execution.
The first one is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.
In all cases, the tread is started with run() method.

Sunday, April 3, 2011

Java API for XML Processing (JAXP)

The Java API for XML Processing, or JAXP, is one of the Java XML programming APIs. It provides the capability of validating and parsing XML documents. The three basic parsing interfaces are:
* the Document Object Model parsing interface or DOM interface
* the Simple API for XML parsing interface or SAX interface
* the Streaming API for XML or StAX interface (part of JDK 6; separate jar available for JDK 5)

In addition to the parsing interfaces, the API provides an XSLT interface to provide data and structural transformations on an XML document.

DOM interface
DOM model parses an entire XML document and constructs a complete in-memory representation of the document. The created objects are from package e org.w3c.dom.

SAX interface
The SAX parser is called the SAXParser and is created by the javax.xml.parsers.SAXParserFactory. Unlike the DOM parser, the SAX parser does not create an in-memory representation of the XML document and so is faster and uses less memory. Instead, the SAX parser informs clients of the XML document structure by invoking callbacks, that is, by invoking methods on a org.xml.sax.helpers.DefaultHandler instance provided to the parser.

The DefaultHandler class implements these interfaces:
* ContentHandler
* DTDHandler
* EntityResolver
* ErrorHandler

StAX interface
StAX was designed as a median between the DOM and SAX interface. In its metaphor, the programmatic entry point is a cursor that represents a point within the document. The application moves the cursor forward - 'pulling' the information from the parser as it needs.

XSLT interface
It allows applying transformations (XSL transformations) to XML files