Joda Time - Java date and time API


 Joda Time - Java date and time API

Almost any application we develop, we need to manipulate dates. Always we need convinent methods to manipulate time,format time.

Recently I started using JODA API,a free, open-source Java library for working with dates and times. This API is a replacement for Date and Calendar classes.JODA APU has no dependencies outside core Java classes

The Key concepts in JODA are

Instant
Represents the number of milliseconds from 1970-01-01T00:00Z
Classes represent instant in JODA are Instant,DateTime,DateMidNight


Instant myInstant = new Instant(1000); /* This Means 1 second after 1970*/
myInstant = instant.plus(100);
myInstant = instant.minus(50);


DateTime can be created like

DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
DateTime endDate = new DateTime();


There are convinient methods provided in the API , like 
daysBetween,getYear,getMonthOfYear

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

System.out.println("  Difference between " + endDate);
System.out.println("  and " + startDate + " is " + days + " days.");


Formatting the output is also quite esay in DateTime. The pattern neede can be passed to the toString() method of DateTime

System.out.println(dateTime.toString("y-M-d HH:mm:ss.SSS a")); // Output will be 2010-3-11 10:46:08.994 AM
System.out.println(dateTime.toString("yyyy-MM-dd"));// Output will be 2010-03-11
System.out.println(dateTime.toString("yyyy/MM/dd"));// Output will be 2010/03/11
System.out.println(dateTime.toString("dd/MM/yyyy"));// Output will be 11/03/2010


DateFormatter could also be used for formatted printing
DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
                .appendDayOfWeekText()
                // Week name
                .appendLiteral(' ')
                .appendMonthOfYearText()
                // Month
                .appendLiteral(' ')
                .appendDayOfMonth(2)
                //Day of month
                .appendLiteral(' ').appendYear(4, 4).appendLiteral(' ')
                .appendEraText().appendLiteral(' ').appendTimeZoneName()
                .toFormatter();

        System.out.println(monthAndYear.print(dateTime));
       

       
       
Partial


Some case we need is only the year/month/day, or the time of day, or even just the day of the week. Classes for dealing with time snippets are LocalDate and LocalTime

LocalDate localDate = SystemFactory.getClock().getLocalDate();
LocalTime localTime = SystemFactory.getClock().getLocalTime();

LocalDate localDate = new LocalDate(2010, 3, 10);// March 10, 2010
LocalTime localTime = new LocalTime(09, 30, 20, 0);


To have the Spans of time Joda provides three classes Duration,Period,Interval

The most interseting part of JODA is in Date calculations. For example if we need to add one week to the current time,

DateTime current = SystemFactory.getClock().getDateTime();
DateTime later = current.plusWeeks(1);


To add 50 days
DateTime current = SystemFactory.getClock().getDateTime();
DateTime later = now.plusDays(50);


Add 180 seconds from now:

DateTime current = SystemFactory.getClock().getDateTime();
DateTime later = now.plusSeconds(180);


Example using JODA Interval and Duration

private void intervalAndDuration() {

        DateTime start = new DateTime(1977, 3, 22, 0, 0, 0, 0);
        DateTime end =  new DateTime(2010, 1, 27, 0, 0, 0, 0);

        Interval interval = new Interval(start, end);
        start = interval.getStart();

        Duration duration = interval.toDuration(); 
        Period period = interval.toPeriod();
        // or
        Period weeks = interval.toPeriod(PeriodType.weeks());
        Period years = interval.toPeriod(PeriodType.years());
        Period days = interval.toPeriod(PeriodType.days());

        System.out.println("YEARS " + years.getYears() + " WEEKS "
                + weeks.getWeeks()/54 + " DAYS " + days.getDays()/365);
    }


Another simple AgeCalculator (Don't look for algorithm, method just to show useful methods in JODA API)

public void findAge(DateTime dateOfBirth, DateTime ageAsOn) {

        if (ageAsOn.isBefore(dateOfBirth.getMillis())) {
            System.out.println(" Wrong Dates !!! ");
            System.exit(0);
        }
        int startMonth, endMonth, startYear, endYear;
        int months, years;
        int totalDays = 0;

        startMonth = dateOfBirth.getMonthOfYear();
        endMonth = ageAsOn.getMonthOfYear();
        startYear = dateOfBirth.getYear();
        endYear = ageAsOn.getYear();

        //First calculate  the year
        if (endMonth >= startMonth)
            years = endYear - startYear;
        else
            years = endYear - startYear - 1;

        //Now calculate the months
        if (endMonth >= startMonth)
            months = endMonth - startMonth;
        else {
            if (ageAsOn.getDayOfMonth() > dateOfBirth.getDayOfMonth())
                months = (12 - startMonth) + endMonth - 1;
            else
                months = (12 - startMonth) + endMonth - 2;
        }

        //Now calculate the days
        if (endMonth != startMonth
                && ageAsOn.getDayOfMonth() != dateOfBirth.getDayOfMonth()) {
            if (ageAsOn.getDayOfMonth() > dateOfBirth.getDayOfMonth()) {
                totalDays = ageAsOn.getDayOfMonth()
                        - dateOfBirth.getDayOfMonth();
            } else {
                totalDays = (ageAsOn.getDayOfMonth() - 1)
                        - dateOfBirth.getDayOfMonth() + ageAsOn.getDayOfMonth();
            }
        }

String strAge = "Age as on " + ageAsOn.toString("dd-MM-yyyy") + " is "+ years + " years " + months + " month(s) " + totalDays+ " day(s)";
        System.out.println(strAge);

    }


 Useful Links
http://joda-time.sourceforge.net/
http://www.ibm.com/developerworks/java/library/j-jodatime.html

Technology Radar 2010

ThoughtWorks has released the Technology Radar 2010 (PDF) this month, a whitepaper containing ThoughtWorks’ technology strategy and trends in four major domains: Techniques, Tools, Languages, and Platforms.

PDF is available here ...
http://www1.vtrenz.net/imarkownerfiles/ownerassets/1013/Technology%20Radar%20Jan%202010.pdf

Java in 2009


Today the last day of 2009, people say time to look back on the year passed by and prepare to  welcome a new year.For me a New Year day is just like any other day.. I feel and live the day of New Year just like all other days.

For Java Community, the year 2009 was major acquisitions like,
Oracle buying Sun,
Terracotta took over the Quartz and ehCache open source frameworks,
SpringSource acquire G2One and Hyperic, 
VMWare acquire SpringSource.

Other interesting development is happening in JVM languages. Groovy, Scala, Clojure, and JRuby gained more popularity this year. JVM is getting remodelled as a platform for other languages.

The fight of dominance in the world RIA is continiuing with Java FX, Flex. Microsoft Silverlight is alos in the race. I feel Adobe has the upper hand in the RIA world.

Cloud Computing continued be discussed in 2009 . Cloud got prominence as IT world start thinking of ways to reduce cost. Google is the most prominent player in this area.Sun, Microsoft recent joined this arena. Microsoft with Azure Platform. Google currently not supporting Java , but urges developer to go with Python.

2010 we may see the languages other Java getting more acceptance.But Java will continue to be strong and will be the most powerful of all. OSGI world seems to busy with projects like Gemini.

Have a great year ahead !!!.


REST - Building Better Systems

REpresentational State Transfer (REST) in short is a simple solution for invoking Web Services through URL's

REST defines a set of architectural principles to design Web services. The RESTful Web Services focus on the system's resources, including how resource states are addressed and transferred over HTTP by a wide range of clients written in different languages.

REST is now a predominant Web service design model. REST is much simpler that the SOAP- and WSDL-based interface design.

REST style of Web Service invokes HTTP methods explicitly. The basic CRUD (create, read, update, and delete) operations are mapped with HTTP methods POST,GET,PUT,DELETE respectively.

In bad designs there is a chance of using these HTTP methods for unintended purposes, For example;

GET /addemployee?name=Chris HTTP/1.1

addemployee is a state changing operation over HTTP method ,GET. If the above request is successful, it will an employee to the database.

HTTP Servers are designed to respond to GET method to retrieve information for the data store. So from the view of HTTP servers the above usage is wrong.

Similar to Create or operations like update ,delete can be invoked in a similar way, which will cause a state change in the server.

The other side of the problem is , this will cause sever side changes if the link is crawled even un intentionally.

To overcome this, the parameter name and values can be represented as XML tags and sent as a body of the HHTP POST request.











The receiver of this request will process this and add the resource in the body as a child of the resource identified in the request URI. In the above example the employee is the resource in the request URI, and Chris will be added under employee.

This is an example for RESTful service.

To update the name of an employee, the RESTful way of doing is to send a PUT request.













The key concept behind defining Restful interface is reusing the “verbs” defined the protocol. For example, employee, parts, machine all are nouns, think of what we can do with theses nouns, it could be get employee, get parts etc. “GET” is the common verb for all the nouns. GET is already defined in the protocol. The service should not define new verbs or remote procedures.

To be more clear, instead of defining services like getemployee, getpart use the universal verb , “GET” to define these services. POST for the services like addemployee, addpart etc. For Update use the PUT request.

The URL will define the resource on which the action needs to be taken ex, employee in the case of the URL, POST /employee HTTP/1.1

The other important design concept in REST is that the body part of HTTP request should carry only the state of the resource and not to carry any name of the remote method or remote procedure.
REST design reduces dependency with the application server than the SOAP- and WSDL-based kind.

Domain Driven Design (DDD)

Domain-Driven Design (DDD) is a collection of principles and patterns that help developers to create software abstractions called domain models. These models highly expressive and encapsulate business logic.These models will  bridge the gap between business and code . These models that is understandable by all the stake holders involved in the project and not just software developers.

For non technical people, the models can be represented in different ways. Typically, a model of a domain can be depicted as a UML diagram, as code, and in the language of the domain.

As an example of using language,
A user wants to order a book online. He searches for the book based on Author, Title. This book is available, user can purchase the book. An order number is issued which the user can use to track the order status.
The language used has to do more with the concepts. It has to explain what the intention is. How the it is implemented is not significance. This helps in better interaction with the developers and the domain experts.

As an example,
A user wants to order a book online. He searches for the book based on Author, Title. If this book is available, user can purchase the book. The user Credit Card is validated by calling a Web Service offered by a third party vendor. Once validated, an order number is issued which the user can use to track the order status.

Here the validating credit card is important. But the Web Service is the implementation, which is insignificant.
So the language used to model the concept must be in line with those of the domain experts.
To have a better understanding the concepts can be explained as "Stories" or "Scenarios". This is the key in Behavior-Driven Development (BDD). What is in story , http://dannorth.net/whats-in-a-story is an interesting article.

Story usually tells about a user wants to do an action, so that he will be benefited. So the above model can be rephrased as,

Story about Buying a Book.
I want to search for a book on Java. I want to buy that. This will help to improve my Java Knowledge.
As the story develops, it will have turning points or scenarios.
Scenarios for the story will be like, 'When' the book is out of print, 'Then' add this book to my wish list and send me a mail when book is available. 'When' describes and event, and 'Then' explains what is the outcome of that event.
Lot of discussion happens around DDD. Some good resources
http://msdn.microsoft.com/en-us/magazine/dd419654.aspx
http://dddstepbystep.com/

Trap with System Properties

Recently I had developed a file upload module in a Portlet application. The module was tested and working perfectly in Windows.When the application was delpoyed in an AIX server, this fuctionality stopped working.
The fix was simple , though it took hours to debug.

To get the header of the multipart content I had code like this,
final int headerIndex= requestContent.indexOf(System. getProperty("line.separator") +System.getProperty("line.separator"));

Using this index I was trying to get the conetent and do the manipulation.

The server where the application was deployed "line.separator" was not set and System. getProperty("line.separator") was returning EMPTY STRING !!!.

This caused my logic to break in the server. So finally I had to put a empty string check (IF condition) for for the property ,line.separator and hard code as '\r\n' as i have no cotrol over the server setting.

This article is a good one for such traps while porting from Windows to AIX, http://www.ibm.com/developerworks/aix/library/au-aix-javatraps/index.html

Facelet - Flushing component

When deploying a new EAR created from a machine with time settings different from that of the server where application is deployed, flushing of the JSF components can happen.

Logs will show the following error.

INFO: Facelet[/pages/menu.jspx] was modified @ 11:45:04 AM, flushing component applied @ 11:41:30 AM

The reason being, when ever a new request is made, server sees the page as modifed in future time stamp and starts compiling again. This causes the component tree to be created again, causing to lose all the state stored by the component.

To fix this add facelets.REFRESH_PERIOD to the web.xml.

REFRESH_PERIOD indicates, When a page is requested, what interval in seconds should the compiler check for changes. If you don't want the compiler to check for changes once the page is compiled, then use a value of -1. Setting a low refresh period helps during development to be able to edit pages in a running application.

web.xml, should look like this,




-1 indicates not to check for changes, since production servers it is safe to set this value.

For more,
https://facelets.dev.java.net/nonav/docs/dev/docbook.html#config-webapp-init