Sunday, 22 February 2015

JSON Read & Write with Java (part II)

There are 2 API to perform JSON processing:

  • Object model ( JsonReader/JsonWritter)
  • Streaming (JsonParser/ JsonGenerator)

In the previous post we reviewed the use of JSON processing using object model : create objects with JsonBuilder, and I/O actions with JsonReader and JsonWritter.

Today, we will take a look to the other alternative of processing JSON with JsonParse and JsonGenerator.

Remember that working with Json processing requires to import the package javax.json.* (Available if we are working with Java7 enterprise edition). 

Write with JsonGenerator

StringWriter sw = new StringWriter();
JsonGenerator jGenerator = Json.createGenerator(sw);
jGenerator
.writeStartObject()
.write("type", "cheeseburguer")
.write("drink", "coke")
.writeStartArray("sides")
.write("chips")
.write("salad")
.writeEnd()
.writeEnd()
.close();
System.out.println(sw);
//{"type":"cheeseburguer","drink":"coke","sides":["chips","salad"]}
The output will be:
{"type":"cheeseburguer","drink":"coke","sides":["chips","salad"]}

Read with JsonParse

JsonParser jParser = Json.createParser(new StringReader(sw.toString()));
while (jParser.hasNext()) {
Event event = jParser.next();
if (event.equals(Event.KEY_NAME)) {
System.out.println(jParser.getString());
}
if (event.equals(Event.VALUE_STRING)) {
System.out.println(jParser.getString());
}
}
view raw JsonParse.java hosted with ❤ by GitHub
The output will be:
type
cheeseburguer
drink
coke
sides
chips
salad



Saturday, 21 February 2015

JSON Read & Write with Java


JSON processing in Java is a new specification in JavaEE7 (JSR353).

Overview:
The acronym JSON means Javascript Object notation, and is a format for data interchange, as XML.

Below there is an example of a object : burguermenu represented in both JSON and in XML syntax:

Json syntax
{"menu":  {"type":"cheeseburguer", 
 "drink":"coke",
 "side":["chips","salad"]    
 }
}
XML syntax
<menu>
<type>cheeseburguer</type>    <drink>coke</drink>    <side>chips</side>    
<side>salad</side>
</menu>


To be able with deal with Json directly in Java we will need to import the package javax.json.* (Remeber this package is included in javaEE 7, and is not available in previous version). Alternatively you can download this library from https://jsonp.java.net/

There are two ways to perform I/O actions : ObjectModel and Streaming model
In this post we will explore the first one, with simple examples of reading and writing.

Create Json object in Java:

In the example a json object menu is created with JsonObjectBuilder:

JsonObjectBuilder menuBuilder = Json.createObjectBuilder();
menuBuilder.add("menu", Json.createObjectBuilder()
.add("type", "cheeseburguer")
.add("drinks", "coke")
.add("side", Json.createArrayBuilder()
.add("chips")
.add("salad")
));
JsonObject result = menuBuilder.build();
view raw JsonDemo.java hosted with ❤ by GitHub

Write a JsonObject --> obtain Json text

The method write the above object using JsonWriter
public String writeJson(JsonObject result){
StringWriter sw = new StringWriter();
try (JsonWriter writer = Json.createWriter(sw)) {
writer.writeObject(result);
}
System.out.println(sw.toString());
//{"menu":{"type":"cheeseburguer","drinks":"coke","side":["chips","salad"]}}
return sw.toString();
}
view raw JsonWrite.java hosted with ❤ by GitHub
The output will be:
{"menu":{"type":"cheeseburguer","drinks":"coke","side":["chips","salad"]}}

Read Json text --> obtain a JsonObject

This method read the above output string using JsonReader and it will obtain a JsonObject
public void readJson(String jsonLine){
JsonReader jr = Json.createReader(new StringReader(jsonLine));
JsonObject jsonObject = jr.readObject();
jr.close();
JsonObject objectMenu = jsonObject.getJsonObject("menu");
String typeValue = objectMenu.getString("type");
JsonArray sideArray = objectMenu.getJsonArray("side");
System.out.println(objectMenu.toString());
//{"type":"cheeseburguer","drinks":"coke","side":["chips","salad"]}
System.out.println(typeValue.toString());
//cheeseburguer
for (JsonValue sideValue : sideArray){
System.out.println(sideValue);
//chips
//salad
}
}
view raw JsonRead.java hosted with ❤ by GitHub
The output will be:
{"type":"cheeseburguer","drinks":"coke","side":["chips","salad"]}
cheeseburguer
chips
salad


Monday, 16 February 2015

Java8 Method Enhancements

Add a body to a method in a interface?
No, because all methods in an interface are abstract.

Add a static method to an interface?? 
No, because static methods cannot be abstract and be overridden in subclasses. 

...but it was before Java8

In Java8 interfaces can contain abstract method, static methods an default methods. 

  • Static and default methods contain implementation.
  • All abstract, default, and static methods in an interface are implicitly public

Default method:

A default method has the word default and it includes a body with the implementation as we can see the method isAvailable in the following example:
package testJava8;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/*
* Example in Java8 : Method enhancements
*/
public interface Agenda {
String dateFormat = "dd-MM-uuuu";
void addPhone(Integer number, String name);
void deletePhone(Integer number);
default boolean isAvailable(LocalDate date){
boolean available = true;
LocalDate now = LocalDate.now();
if (date.isBefore(now))
{
available = false;
}
return available;
}
static String formatPhone(Integer number){
String phoneNumber = String.valueOf(number);
String formatNumber = phoneNumber.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)-$2-$3");
return formatNumber;
}
static String formatDate(LocalDate date){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
String dateText = date.format(formatter);
return dateText;
}
}
view raw Agenda.java hosted with ❤ by GitHub


When you extend an interface that contains a default method, you can do the following:

- Override : default boolean isAvailable(LocalDate date){//new implementation}
- Make it abstract: boolean isAvailable(LocalDate date);
- Inherit the default method: not including nothing in the extended interface

In the following example the above interface Agenda is extended in the interface WorkAgenda. The default method is overriden because a new implementation is included.  

package testJava8;
import java.time.DayOfWeek;
import java.time.LocalDate;
/*
* Example in Java8 : Method enhancements
*/
public interface WorkAgenda extends Agenda{
void addTask(LocalDate date, String task);
void deleteTask(String task);
//overriding isAvailable method from interface Agenda
default boolean isAvailable(LocalDate date)
{
boolean available = true;
LocalDate now = LocalDate.now();
if (date.isBefore(now)){
available = false;
}
//includes a validation depending on dayOfWeek
if (date.getDayOfWeek().equals(DayOfWeek.SUNDAY))
{
available = false;
}
return available;
}
}
view raw WorkAgenda.java hosted with ❤ by GitHub
In case we would prefer to make it abstract we could write the method signature but without body. A class that implements an interface must implement all the abstract methods declared in the interface.


Static Methods
Including static methods in interfaces replaces the idea of defining utilities in separate Utility class.

The static method is part of the interface and not of the implementing class. So the way to call the method is using the interface name. In the following example the static method formatDate is used in the main method. As formatDate is defined in the interface Agenda, the notation is Agenda.formatDate(Date date);

package testJava8;
import java.time.LocalDate;
/*
* Example in Java8 : Method enhancements
*/
public class TaskPlanning implements WorkAgenda{
@Override
public void addTask(LocalDate date, String task) {
// TODO Auto-generated method stub
}
@Override
public void deleteTask(String task) {
// TODO Auto-generated method stub
}
public static void main(String args[])
{
//Date after currentDate, but day of the week is sunday
LocalDate date = LocalDate.of(2015, 02, 22);
//use static method defined in interface Agenda
String result1 = Agenda.formatDate(date);
System.out.println(result1);//return 21-02-2015
//use default method overriden in WorkAgenda interface
TaskPlanning tp = new TaskPlanning();
boolean result2 = tp.isAvailable(date);
System.out.println(result2);//return false
}
}
view raw Task.java hosted with ❤ by GitHub
And remember that when an interface is modified to add a new default or static method, the classes that already implemented the interface do not need to be modified.



Sunday, 15 February 2015

Java8 DateTime: Conversion and Formatter

We have seen in a recent post how to deal with the new API DateTime in Java8. 
In this post we will explore the formatting options and how to do the conversion from LocalDate (Java8) to Date (legacy API) and viceversa

Example1- How to convert from legacy to new API 
The following examples are the conversion from Date and Calendar to LocalDate.
//Convert from Date to LocalDate
Date dateNow = new Date();
Instant instant = dateNow.toInstant();
ZonedDateTime zDate = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDateTime ldt = zDate.toLocalDateTime();
LocalDate date1 = zDate.toLocalDate();
LocalTime time = zDate.toLocalTime();
System.out.println("date" + date1);//2015-02-15
//Convert from Calendar to LocalDate
Calendar cal = Calendar.getInstance();
LocalDate date2 = LocalDate.of(cal.get(cal.YEAR), cal.get(cal.MONTH), cal.get(cal.DAY_OF_MONTH));
System.out.println("date" + date2);//2015-02-15
view raw CovertDate.java hosted with ❤ by GitHub

Example2- How to convert from new API to legacy
Conversion from LocalDate to Date.
//Convert from LocalDate to Date
LocalDateTime now = LocalDateTime.now();
Instant instantNow = now.toInstant(ZoneOffset.MIN);
Date date3 = Date.from(instant);
System.out.println("date" + date3);//Sun Feb 15 23:37:36 GMT 2015


Example3- Use of formatter
How to convert from LocalDate to String and viceversa.
It is supported by class Formatter (equivalent of SimpleDateFormat for the legacy API).
//Format
//SimpleDateFormat --> format Date
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String dateFormatted = sdf.format(date);
System.out.println("dateFormatted" + dateFormatted);//15-02-2015
//DateTimeFormatter --> format LocalDate
// from LocalDate to text
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
String dateText = localDate.format(formatter);
System.out.println("dateText" + dateText);//15-02-2015
// from text to LocalDate
String text = "31-12-2014";
LocalDate localDateFromText = LocalDate.parse(text, formatter);
System.out.println("localDateFromText" + localDateFromText);//2014-12-31

Saturday, 7 February 2015

Java8 New API Date Time: Overview

The new API Date Time for java 8 is included in the package java.time.

  • Class LocalDate --> date
  • Class LocalTime --> time
  • Class LocalDateTime --> timestamp

The new date and time classes are thread safe (they are not mutable and can be used in multithread). This is an advantage respect from the previous API (Date and Calendar classes).

Now, let's see some easy examples about how to apply this new DateTime classes.

Examples with dates (LocalDate class)
    • get current date
    • set date methods of/with
    • dayOfWeek, yearMonth, year
    • parsing dates
    • calculations (plus/minus)
    • comparing dates
    • Period class


/*
* get current date
*/
LocalDate today = LocalDate.now();
System.out.println("today" + today);//returns in format yyyy-mm-dd
/*
* Setting dates: methods of/with
*/
LocalDate date1 = LocalDate.of(2015, 01, 26);
System.out.println("date1" + date1);//returns 2015-01-26
LocalDate date2 = today.withYear(2014).withMonth(12).withDayOfMonth(31);
System.out.println("date2" + date2);//returns 2014-12-31
/*
* DayOfWeek/yearMonth/year
*/
LocalDate date3 = LocalDate.of(2015, Month.APRIL, 23);
int month = date3.getMonthValue();
Month month2 = date3.getMonth();
System.out.println("Month selected: " + month + month2);//Month selected: 4APRIL
System.out.println("Day of week : " + date3.getDayOfWeek());//Day of week : THURSDAY
/*
* Parsing dates
*/
DateTimeFormatter df = DateTimeFormatter.BASIC_ISO_DATE;
LocalDate formated = LocalDate.parse("20150203", df);
System.out.println(formated);//2015-02-03
/*
* calculations (add- plus/substract -minus/by)
*/
LocalDate dateNext = date1.plusWeeks(2);
System.out.println("dateNext " + dateNext);
LocalDate datePrevious = date1.minusDays(5);
System.out.println("datePrevious " + datePrevious);
/*
* Comparing dates (equals/compareTo/isAfter/isBefore)
*/
Boolean isEquals = date2.equals(date3);
int compare = date2.compareTo(date3);
System.out.println("isEquals "+isEquals);//false
System.out.println("compare "+compare);//-1
Boolean isAfter = date2.isAfter(date3);
Boolean isBefore = date2.isBefore(date3);
/*
* Period
*/
//calculate a period between dates
Period p = Period.between(date1, date2);
System.out.println("period" + p.getDays());//26
Period p1 = Period.ofDays(15);
Period p2 = Period.ofMonths(3);
Period p3 = Period.ofYears(2);

Examples with time (LocalTime class)
    • LocalTime current time, constants
    • Duration : calculation with times
    • LocalDateTime : obtain timestamp

/*
* LocalTime
*/
LocalTime t1 = LocalTime.now();
LocalTime t2 = LocalTime.NOON;
/*
* Duration
*/
//calculate duration between times
Duration duration = Duration.between(t1, t2);
//return duration in milliseconds: 42641477
System.out.println("Duration"+duration.toMillis());
//return duration in nanoseconds: 42641477000000
System.out.println("Duration"+duration.toNanos());
Duration gap = Duration.ofSeconds(10);
System.out.println(gap.toMillis());
//10000
/*
* LocalDateTime
*/
LocalDateTime timestamp = LocalDateTime.now();
System.out.println("current timestamp : " + timestamp );
//2015-02-08T00:09:18.523