Friday, September 29, 2017

Java 8 Date Time API: LocalTime

With Java 8 Oracle introduced new Date and Time APIs which address the shortcomings of the existing java.util.Date and java.util.Calendar. In this article we will take a look at the Java 8 Date and Time API with few examples of the new LocalTime class introduced by Java 8.

Improvements to Existing Calendar and Date Classes

Thread Safety: The existing API was not designed with concurrency in mind. This meant developers had to come up with custom solutions to handle thread safety. The Java 8 Date/Time API ensures thread safety by making all the new classes immutable. Domain-driven design: The Java 8 date/time API has clear domain boundaries, and defines classes with specific use cases. Support for non-standard Calendars: The Java 8 Date/Time API provides support for non-standard calendaring systems (Japanese calendar for example) without affecting the standard calendar implementation.

Java 8 Date And Time API:Time Zones

In the previous three posts, we took a detailed look at the Java 8 Local Date and Time classes. In this post, we will take a look at the Java 8 provides ZonedDateTime and OffsetDateTime classes.

ZonedDateTime

ZonedDateTime uses ZoneId to represent different time zones. The following example shows how to create a ZoneId for Chicago
ZoneId zoneId = ZoneId.of("America/Chicago");
Following piece of code shows how to obtain a list of all zone ids.
Set zoneIdList = ZoneId.getAvailableZoneIds();
There are many ways to instantiate ZonedDateTime, most of them parallel LocalDateTime as shown in the previous post, with the addition of Zone Id.
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
ZonedDateTime.parse("2015-05-03T10:15:30+01:00[America/Los_Angeles]");
Truncate Time from ZonedDateTime
The truncateTo() method can be used to truncate the time fields. Any Time Unit lesser than the passed parameter will be marked to zero.
// Anything under days is set to zero. Works only for time.
System.out.println(zonedDateTime + " Truncated to  " + zonedDateTime.truncatedTo(ChronoUnit.HOURS));
Convert Time Zone
Converting time from one timezone to another is one of the common requirements. The method of ZonedDateTime can be used to convert a given ZonedDateTime to any timzone. The following example can be used to convert the current time in Chicago timezone to time in Los_Angeles
// Convert Time Zone
System.out.println(zonedDateTime + " in Los Angeles " + zonedDateTime.withZoneSameInstant(ZoneId.of("America/Los_Angeles")));
ZonedDateTime also offers many of the same utility methods offered by LocalDateTime. A few examples are shown below
System.out.println("3 days before today is : " + zonedDateTime.minus(3, ChronoUnit.DAYS));
System.out.println("3 decades before today is : " + zonedDateTime.minus(3, ChronoUnit.DECADES));
System.out.println("3 days after today is : " + zonedDateTime.plus(3, ChronoUnit.DAYS));
System.out.println("3 decades after today is : " + zonedDateTime.plus(3, ChronoUnit.DECADES));

System.out.println("The day of the week is : " + zonedDateTime.getDayOfWeek());
System.out.println("The day of the year is : " + zonedDateTime.getDayOfYear());

OffsetDateTime

OffsetDateTime class can be used to represent DateTime with an Offset. This class stores all date and time fields, to a precision of nanoseconds, as well as the offset from UTC/Greenwich. For example, the value "2nd October 2007 at 13:45.30.123456789 +02:00" can be stored in an OffsetDateTime. OffsetDateTime can be created in the following ways.
// Now
OffsetDateTime offsetDateTime = OffsetDateTime.now();
System.out.println("OffsetDateTime : " + offsetDateTime);

// Get LocalDateTime and apply Offset
LocalDateTime localDateTime = LocalDateTime.of(2017, Month.SEPTEMBER, 29, 5, 30);
ZoneOffset offset = ZoneOffset.of("+02:00");

OffsetDateTime offSetByTwo = OffsetDateTime.of(localDateTime, offset);
System.out.println(localDateTime + " Offset by two " + offSetByTwo);

Full code for this post

import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class ZonedDateTimeExamples {

 public static void main(String[] args) {
  ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("America/Chicago"));
  System.out.println(zonedDateTime);

  // Convert Time Zone
  System.out
    .println(zonedDateTime + " in Los Angeles " + zonedDateTime.withZoneSameInstant(ZoneId.of("America/Los_Angeles")));

  // Anything under days is set to zero. Works only for time.
  System.out.println(zonedDateTime + " Truncated to  " + zonedDateTime.truncatedTo(ChronoUnit.HOURS));

  System.out.println("3 days before today is : " + zonedDateTime.minus(3, ChronoUnit.DAYS));
  System.out.println("3 decades before today is : " + zonedDateTime.minus(3, ChronoUnit.DECADES));
  System.out.println("3 days after today is : " + zonedDateTime.plus(3, ChronoUnit.DAYS));
  System.out.println("3 decades after today is : " + zonedDateTime.plus(3, ChronoUnit.DECADES));

  System.out.println("The day of the week is : " + zonedDateTime.getDayOfWeek());
  System.out.println("The day of the year is : " + zonedDateTime.getDayOfYear());

  // Now
  OffsetDateTime offsetDateTime = OffsetDateTime.now();
  System.out.println("OffsetDateTime : " + offsetDateTime);

  // Get LocalDateTime and apply Offset
  LocalDateTime localDateTime = LocalDateTime.of(2017, Month.SEPTEMBER, 29, 5, 30);
  ZoneOffset offset = ZoneOffset.of("+02:00");

  OffsetDateTime offSetByTwo = OffsetDateTime.of(localDateTime, offset);
  System.out.println(localDateTime + " Offset by two " + offSetByTwo);

 }

}

Java 8 Date And Time API: LocalDate

With Java 8 Oracle introduced new Date and Time APIs which address the shortcomings of the existing java.util.Date and java.util.Calendar. In this article we will take a look at the Java 8 Date and Time API with few examples of the new LocalDate class introduced by Java 8.

Improvements to Existing Calendar and Date Classes

Thread Safety: The existing API was not designed with concurrency in mind. This meant developers had to come up with custom solutions to handle thread safety. The Java 8 Date/Time API ensures thread safety by making all the new classes immutable. Domain-driven design: The Java 8 date/time API has clear domain boundaries, and defines classes with specific use cases. Support for non-standard Calendars: The Java 8 Date/Time API provides support for non-standard calendaring systems (Japanese calendar for example) without affecting the standard calendar implementation.

Java 8 Date Time API: LocalDateTime

With Java 8 Oracle introduced new Date and Time APIs which address the shortcomings of the existing java.util.Date and java.util.Calendar. In this article we will take a look at the Java 8 Date and Time API with few examples of the new LocalDateTime class introduced by Java 8.

Improvements to Existing Calendar and Date Classes

Thread Safety: The existing API was not designed with concurrency in mind. This meant developers had to come up with custom solutions to handle thread safety. The Java 8 Date/Time API ensures thread safety by making all the new classes immutable. Domain-driven design: The Java 8 date/time API has clear domain boundaries, and defines classes with specific use cases. Support for non-standard Calendars: The Java 8 Date/Time API provides support for non-standard calendaring systems (Japanese calendar for example) without affecting the standard calendar implementation.

Java 9 Streams : dropWhile()

In Java 9, comes with a few good additions to the Stream API. For more information on the Java 8 Streams, go to the Java 8 Page. The following new methods were added to the Java 9 Stream API.
  1. dropWhile
  2. dropWhile
  3. iterate
  4. ofNullable
In this post we will take a look at the dropWhile() method.

Thursday, September 28, 2017

Java 9 Streams: iterate() and ofNullable() methods

In Java 9, comes with a few good additions to the Stream API. For more information on the Java 8 Streams, go to the Java 8 Page. The following new methods were added to the Java 9 Stream API.
  1. dropWhile
  2. dropWhile
  3. iterate
  4. ofNullable
In this post we will take a look at the iterate() and ofNullable() methods.

Wednesday, September 27, 2017

Java 9 Streams : takeWhile() method

In Java 9, comes with a few good additions to the Stream API. For more information on the Java 8 Streams, go to the Java 8 Page. The following new methods were added to the Java 9 Stream API.
  1. takeWhile
  2. dropWhile
  3. iterate
  4. ofNullable
In this post we will take a look at the takeWhile() method.

Monday, September 25, 2017

Setup Java 9 in Eclipse Oxygen

This post gives the quick steps to setup Eclipse Oxygen with Java 9. This relies on Java™ 9 support for Eclipse JDT is available now. At this time, the it is not fully functional, and I have faced a couple of issues setting this up. Full support for Java 9 is expected on October 11, 2017 with Oxygen 1a release. Follow these steps to install the support for Java 9.

Sunday, September 24, 2017

Using Comparators with Java 8 Streams

This post gives a few examples of how to use Comparator with Java 8 streams to Sort and to find the Maximum and Minimum elements in a stream.

Comparing Simple types with Comparator.comparing* methods

The Comparator.comparingDouble, Comparator.comparingInt and Comparator.comparingLong etc. methods can be used to do sorting or finding max and min from stream. The following example uses the comparingDouble method to compare and sort a stream of doubles generated using the Stream.generate() method. The Stream.generate has been explained my earlier post "Java 8 Streams"
  // Sort a stream of Doubles
  Stream.generate(Math::random).limit(10).sorted(Comparator.comparingDouble(Double::valueOf)).forEach(System.out::println);

Monday, September 18, 2017

Auto-Restart Spring Boot Application On Code Change With Dev Tools

Spring Boot Dev Tools enables auto-restarting a Spring boot application whenever any class is changed in the class path. This is not comparable in speed with the hot swap functionality offered by Jrebel or Spring Loaded, but this is a very simple and easy way to implement and better than manual restart. In this post, I use a simple Spring boot rest echo service to demonstrate how spring boot dev tools can be used to auto restart the application when using Maven on an IDE or Gradle from command line. In either options, the main trigger for a restart is the change to a class file, which means that the change to a Java file has to be compiled either by the IDE in option 1 or by Gradle in option 2.

Monday, September 11, 2017

Passing System Properties and Arguments With Gradle

When using the Gradle application plugin, Gradle spawns a new JVM on the fly, and does not pass the System Properties or Command-line arguments to the new Java process. This post explains how to pass the System properties and command-line arguments when using Gradle application plugin.

Sunday, September 10, 2017

Load Environment Specific Properties Files Using Spring

One of the more common aspects of enterprise application development involves environment specific properties files. Some examples include Database configurations or external JMS resources etc. The common way to address this problem is to use multiple properties file an build the Application EAR/WAR/JAR at compile time. Although this works, this solution also means that we maintain different build scripts for different environments, or having some file renames etc. while building the application. Spring profiles address this problem in a more efficient way. Like any other property, using Spring profiles, we can inject the environment profile into Spring and Spring will handle the loading of the appropriate configuration files. In this post, I show how to load environment specific properties files using Spring.

Thursday, September 07, 2017

Merge and Paginate PDF files using iText 5

In this post we will see a way to merge multiple PDF files while adding page numbers at the bottom of each page in the format Page 1 of 10. The following steps give a brief description of the steps used to merge and add page number to the merged PDF.

Wednesday, September 06, 2017

Merge PDF files using iText 5

This is an example code for a simple PDF merge using iText 5. We use three InputStreams in a List as input and merged file is written to the file system.

Monday, September 04, 2017

WatchService to monitor Directories for changes

There a many scenarios where you would like to monitor a directory for new files, or changes to existing files or deleted files. Some of the use cases are
  • Files will be dropped into a directory by a third party which have to be processed by your application
  • A file editor which monitors the directory to make sure the files currently being edited are not modified by another concurrent user.
  • You want to start a build and deploy code whenever a source file is changed (In an enterprise application, this is usually done in a source control in conjunction with a tool like Jenkins).
Starting Java 7, the new java.nio.file.WatchService provides a scalable solution to monitor directory for any changes. In this post, we will go over the features of the WatchService service and a simple example for how to monitor a directory for changes and print the name of the file that was affected.

Friday, September 01, 2017

Directory Listing in Java

This post provides a examples of a few ways to list contents of a directory in Java. A couple of examples of how to recursively traverse a directory are also provided. Finally we will see the use of Files.walk() and Files.find() introduced in Java 8, which makes directory traversal even more simple.

Popular Posts