Wednesday, June 24, 2015

Java 8 Date and Time API

Any experienced Java programmer would agree that the Date/Calendar API before Java 8 was confusing and inconsistent. It also has some design flaws. I have found myself in confusing situations like whether to use java.util.Date or java.util.Calendar API. Most of the cases, I used to google for code snippet and quickly get rid of the problem. And in some other cases which required lot of date/time manipulation, I used third-party libraries (like Joda-time API).

It's pleasing to see that, Java designers finally addressed this pain point and introduced a new set of API. I have tried to quickly cover major API and their usage with simple examples. This post will give you quick start to understand new classes added in package java.time.

java.time.LocalDate

An instance of this class is an immutable object which just stores date information, i.e. year, month and day. It doesn't store the time and time zone. LocalDate provides factory methods to fetch the system current date or refer a specific date.

LocalDate independenceDay = LocalDate.of(1947, 8, 15); //15th Aug 1947
LocalDate parsedDate  = LocalDate.parse("2015-01-31");

LocalDate today = LocalDate.now();       //2015-06-24
int day        = today.getDayOfMonth();  //24
int month      = today.getMonthValue();  //6
Month mon      = today.getMonth();       //JUNE
int year       = today.getYear();        //2015
DayOfWeek days = today.getDayOfWeek();   //WEDNESDAY
int len        = today.lengthOfMonth();  //30

java.time.LocalTime

Similar to LocalDate, LocalTime represents just the time without any date and time zone information. 

LocalTime specificTime = LocalTime.of(12, 45, 59);
LocalTime parseTime = LocalTime.parse("13:45:20");
LocalTime now =  LocalTime.now();
int hour      = now.getHour();
int minute    = now.getMinute();
int seconds   = now.getSecond();

int nanoSec = now.getNano();  //gets nano of second

java.time.LocalDateTime

As the name suggests, LocalDateTime represents both date and time, without any time zone information. It can also be created by combining LocalDate and LocalTime. 

LocalDateTime NowDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now());   //2015-06-24T17:58:29.557
LocalDateTime specificDateTime = LocalDateTime.of(2015, Month.JANUARY, 18, 13, 45, 20); //2015-01-18T13:45:20
LocalDateTime aTime = LocalDate.now().atTime(13, 45, 20);   //2015-06-24T13:45:20

Date and Time for machines

All approaches discussed above are more suitable for humans, but machines will prefer a unique number which abstracts date and time information (similar to the way it was done in java.util.Date API). 

java.time.Instant represents the number of seconds passed since the Unix epoch time (midnight Jan 1, 1970, UTC). The Instant class also provides a now factory method to capture current timestamp. This API also supports nanoseconds precision which was not there in previous date/time/calendar API.

Instant timeStamp = Instant.now();   //2015-01-18T13:45:20
long second = timeStamp.getEpochSecond();  //1435149943
long nano = timeStamp.getNano();  //341000000, total number of nano seconds since getEpochSecond


Thursday, June 18, 2015

Running a class from a Jar file

This post talks about executing a jar file and the jar could have one or more than one class with the main method.  Remember that, you need a main method in the class to be called from outside.  So if you want to run a class contained inside jar file:
Either it should have a main method or Other class have the main method which calls appropriate method of your target class.

Pre-condition 
Make sure that java and jar are on your PATH. This is how you set on Linux/Unix systems:

export PATH=$PATH:/full_path_java_bin_directory

Otherwise, you will have to run below command from bin directory inside the Java installer. I am covering here only Unix/Linux system (windows will be similar, though).



Running a Particular Class

$java -cp <jar_path> <className> [OPTIONAL_PARAMS]

The first argument JAR_PATH should give the fully qualified path of the jar file. Similarly, class name should be complete. One quick way is, check out the package name of the class which you want to run. If the package name is com.blogger then the class name should be com.blogger.ClassName. 

$java -cp lib/my.jar com.blogger.PostDetails   //no param

$java -cp lib/my.jar com.blogger.PostDetails postName   //main expects param with name postName
$java -cp my.jar PostDetails  //running from jar directory, and class is in default package

You can also use -classpath instead of -cp 


If the jar is executable

$java -jar <jar_path> [OPTIONAL_PARAMS]

If the jar is executable (i.e. it has manifest file inside META-INF directory and specifies the name of the class file which has main method), the command to run it is slightly different. 

$java -jar lib/my.jar

So basically we don't specify the class name in the command (as it's implicitly understood).

You can check if the jar has a manifest file by running below command:
$java -jar my.jar


--
keep coding !!!

Sunday, June 14, 2015

Object Oriented vs Relational Model relationship


Object Oriented world abstracts data in form of objects (and provides method to read/manipulate) whereas Relational world abstracts data in form of (table) records. Both are quite different approaches and hence bringing them together is not so trivial. There have been different approaches but will discuss here from the perspective of object relational mapping. 

Entity is a well designed middle ground between two orthogonal concepts, object and table. To understand entity relationship, it's better to understand how objects relate with other object and similarly how tables relate with other tables. Let's dive deeper into both-

Object Relationship

In object oriented world, different classes associate among each other. This enables object of one type to perform some action on object of other type(i.e. obj.performAction(...)). Object Oriented uses UML to show the relationship and one of the most fundamental relationship is association which gets realized using object references. Association relationship between two classes has a direction as well as ownership. 

Unidirectional association between two classes (UML, class diagram)
Unidirectional relationship also has owner, in above diagram Employee class is owner of the relationship. It also shows multiplicity(or cardinality), which says that 1 instance of Employee class can have 0 or more instances of Address class. In Java, above relationship will be implemented by having attribute of Address class inside Employee. 

public class Employee{
      private String id;
      private List<Address> addresses = new ArrayList<>();
     ...
}

List of Address class enables you to have 0 or more address for a given employee. Java also supports bidirectional association which gets shown in UML diagram either by showing no arrow (just a plain line without any head) or arrow at both ends. Association is most fundamental relationship, and usually association relationship gets evolved into other relationship like(Generalization, Aggregation/Composition etc). For the scope of this post, I have considered only association relationship.


Relationship in relational DB

Relational world has tables which is collection of relations (among its columns). Tables don't have list/map or even concept of attributes to refer one table in another table. The reference here is modeled bit differently and uses below two approaches:

  1. By using foreign key (i.e. a join column)
  2. By using a join table
So in relational world, it would get implemented by having an EMPLOYEE table pointing to ADDRESS table either through a foreign key or through a join table as shown below:

Table relationship (foreign key vs join table)

So in first case, ADDRESS_ID is foreign key in EMPLOYEE table; but in second case (i.e. join table),  EMPLOYEE table doesn't store any reference for ADDRESS. In fact the relationship is stored in a separate table which just maps the primary keys of both the tables. 
Join tables are not ideal for one-to-one relationships. You should use them when you have one-to- many or many-to-many relationships. 

Final Note

Object references are inherently directional. The association is always from one object to the other. They're REFERENCES ( or POINTERS as called in C/C++). On the other hand, foreign-key association aren't directional by nature. Navigation has no meaning in relational world. 
Java associations can have many-to-many multiplicity, whereas table associations are always one-to-many or one-to-one. 


Saturday, June 13, 2015

Synthetic key vs Natural key in DB world

One of the decade old debates in SQL world:
                        Which is preferred primary key- synthetic or natural?

Both have their own pros and cons, so choosing one over other is not trivial. But you can definitely do one thing to make your life easier, whichever approach you (and your team) decides; let's stick to that and try to avoid mixing these two strategies.

Natural Key

The word relational used in DB/SQL world basically means that while designing tables your need to consider how the columns relate to each other. This way all columns together will define one entity. So conceptually it makes sense to have one or more than one column from the entity to make rows unique. But sometime over a period it becomes difficult to maintain this condition and we are forced to changed the schema of table to ensure that primary or composite key(primary key composed of multiple columns)  really remain unique.

Synthetic/Surrogate/Made-Up/Artificial Key

Synthetic is a generated unique value that is used as primary key of a database table. So it's one of the columns of the table but it doesn't have any logical relationship with the rest. But good thing is that a single synthetic key can ensure that all rows have a unique key.  It's a sequence generated by an algorithm which ensures its uniqeness. This is definitely better than managing multiple columns for a key. 


References
http://www.dbta.com/Columns/DBA-Corner/Surrogate-Keys-or-Natural-Keys-84892.aspx
http://stackoverflow.com/questions/4960263/sql-primary-key-column-artificial-id-column-vs-natural-columns

Monday, June 8, 2015

Brief overview of JPA

JPA(Java Persistence API) came into the picture to bring object-oriented and relational model together. It's basically an abstraction on top of JDBC (and is part of EJB 3.0 specification); to let you deal with tables without using SQL. Before this, the persistence model of Java was called as Entity Bean and was part of Enterprise Java Beans specification. Entity Bean wasn't lightweight, and hence got replaced by this new (new age) API.

Relational databases store data in tables in form of rows and columns. So dealing with tables directly was not very convenient in Java where objects rule. JDBC bridged the gap a bit but wasn't able to remove SQL altogether. JPA consists of two broad components to solve the full problem - first is the mapping of objects to tables and second is providing the ability to query. Let's cover them briefly:

Mapping (ORM): JPA maps Java objects to relational database tables. Mapping is achieved through ORM metadata. The metadata describes the mapping between table and objects (and attributes and columns). It was initially achieved by a descriptor XML file, but it got further simplified and now annotations are preferred approach (Use of annotations brought convention over configuration technique). So, just put annotations at Class, field/method level and boy you are done with mapping.

A common confusion is that hand-coded SQL queries are going to be as fast as one automated by ORM tool or maybe even better. So is it recommended to use ORM tools?

Yeah, it's safe to assume that hand-coded SQL/JDBC can be easily analyzed and optimized. But, ORM tools like Hibernate gives much more optimizations like automated queries and caching out of the box. It hides a lot many details and allows the programmers to focus on core business problems. Also, these tools abstract your underlying database as well. 

Querying: Mapping will not make much sense if we still have to write SQL queries so JPA tweaked SQL to come up with its own query language, JPQL(Java Persistence Query Language). JPQL queries entity objects.  JPQL doesn't understand underlying row/columns and tables, it queries objects so uses familiar notation i.e. dot (.). 

Evolution of JPA

JPA 1.0 (May 2006, EJB 3.0) brought the object-oriented and relational model together. It was bundled as part of J2EE 1.3 and then later J2EE 1.4 as well.

JPA 2.0 (Dec 2009, Java EE 6) It extended JPQL, added second-level cache, pessimistic locking (criterial API)

JPA 2.1(Apr 2013, Java EE 7) supports schema generation (persistance.xml), converters, CDI, stored procedures, bulk update and delete queries, enhanced criteria API (update and delete)
more here - http://www.thoughts-on-java.org/jpa-21-overview/

* From version 5, J2EE is known as Java EE, and similarly J2SE is know as Java SE.


Entity

Objects which get persisted through JPA provider(like hibernate) is referred to as Entity. Entities live shortly in memory and persistently in a database. So you basically perform all operations on Entity which are POJO and it typically represents a row of a table. Entity class should satisfy below conditions:
  • Entity class must be annotated with @javax.persistance.Entity
  • The class must have public or protected no arg constructor (it can have other constructors as well)
  • The class must not be declared as final. No method or persistent instance variable must be declared as final
  • The class must not be enum or interface 
  • If the instance has to be passed by value as the detached object, the entity class must implement Serializable interface
@Entity
public class Employee{..}

@Entity annotation converts the Employee class into an entity (in above snippet).  Also going by convention over configuration rule, the table name is same as class name (i.e. Employee).


JPA Frameworks/Implementation

  • Hibernate open source implementation, supports JPA from version 3.2, influenced JPA specification
  • TopLink commercial implementation
  • Java Data Objects (JDO)
  • EclipseLink also supports object XML mapping. Reference implementation of JPA. 

Note: Persistence provider or provider refers to JPA implementation. 

Friday, June 5, 2015

Testing Websocket Service from Browser

Move aside HTTP, WebSocket is the new kid in the block. So typical request-response cycle initiated always from HTTP clients (like a browser) is gone. Websocket brings in more responsive communication to the web. But, you can't test WebSockets directly from the browser (the way we do for HTTP). This post, I will provide some hacks to simplify your WebSocket development by enabling easier testing.

Does your browser supports WebSocket

Not all browsers support WebSockets, so before testing the service make sure your browser has support for it. One quick way is, ping a WebSocket hosted on the public web from your browser.  How about testing a public WebSocket service from your browser? Launch below URL and just test it out (Make sure you have internet connectivity):


simple, if you are able to ping the service; you have support in your browser!
You can also check your browser support over, here.   

Test a WebSocket service 

You have written a WebSocket service, now how do you know if it's all good and working. You might end up writing a client in your favorite language (Java / JavaScript). This is overhead!

To make testing easier without writing much code we can use browser plugins. Chrome provides a plugin for testing web socket (there might be an equivalent plugin for other browsers as well). Just install the plugin in chrome and you are all set to test your service. Once it's installed you will notice a small icon (ws) next to search text field. 

Click that link and you have a client for testing WebSockets. Enter your WebSocket URL as shown below and open connection. Once the connection is opened you can keep sending messages to the server and receiving the message from the server. I have shown my own WebSocket service named as helloWebSocket. 



That's it!
---
Live WebSocket echo server: http://www.websocket.org/echo.html