How do I install Calibri font in Ubuntu?

I need to create a Microsoft Word Mail Merge document in my Java Spring MVC application. But running it in Ubuntu server resulting in a document that missing the default font use in the document, which is the Calibri font. So I need to install the font in Ubuntu to make the document looks as expected.

Here what I need to do to install the font in my Ubuntu box. Starts by updating the repository package list to get latest packages information for upgrades or new package installation.

sudo apt-get update

Then install FontForge in our system. FontForge is a free and open source font editor, but in this case it will help doing the font conversion in the installation script on the upcoming step.

sudo apt-get install fontforge

Install the Microsoft Cabinet file unpacker. This is required for the next script to successfully install the fonts.

sudo apt-get install cabextract

The following script will install Microsoft Vista TrueType Fonts (TTF) in Ubuntu. It includes the following fonts, Calibri, Cambria, Candara, Consolas, Constantia, and Corbel.

wget -q -O - | sudo bash

Run the next command to see if the font successfully installed. You will see the Calibri fonts in the result if the fonts successfully installed.

fc-list | grep Calibri

Here are the list of installed Calibri fonts.

/usr/share/fonts/truetype/vista/calibriz.ttf: Calibri:style=Bold Italic
/usr/share/fonts/truetype/vista/calibrii.ttf: Calibri:style=Italic
/usr/share/fonts/truetype/vista/calibrib.ttf: Calibri:style=Bold
/usr/share/fonts/truetype/vista/calibri.ttf: Calibri:style=Regular

How do I create a generic class in Java?

In this example you will learn how to create a generic class in Java. In some of the previous post in this blog you might have read how to use generic for working with Java collection API such as List, Set and Map. Now it is time to learn to create a simple generic class.

As an example in this post will create a class called GenericMachine and we can plug different type of engine into this machine that will be use by the machine to operate. For this demo we will create two engine type, a DieselEngine and a JetEngine. So let’s see how the classes are implemented in generic.

package org.kodejava.examples.generic;

public class GenericMachine<T> {
    private T engine;

    public GenericMachine(T engine) {
        this.engine = engine;

    private void start() {
        System.out.println("This machine running on: " + engine);

    public static void main(String[] args) {
        // Creates a generic machine with diesel engine.
        GenericMachine<DieselEngine> machine = new GenericMachine<>(new DieselEngine());

        // Creates another generic machine with jet engine.
        GenericMachine<JetEngine> anotherMachine = new GenericMachine<>(new JetEngine());

Now, for the two engine class we will only create an empty class so that the GenericMachine class can be compile successfully. And here are the engine classes:

package org.kodejava.examples.generic;

public class DieselEngine {
package org.kodejava.examples.generic;

public class JetEngine {

The <T> in the class declaration tell that we want the GenericMachine class to have type parameter. We also use the T type parameter at the class constructor to pass the engine.

How do I convert java.util.TimeZone to java.time.ZoneId?

The following code snippet will show you how to convert the old java.util.TimeZone to java.time.ZoneId introduced in Java 8. In the first line of our main() method we get the default timezone using the TimeZone.getDefault() and convert it to ZoneId by calling the toZoneId() method. In the second example we create the TimeZone object by calling the getTimeZone() and pass the string of timezone id. To convert it to ZoneId we call the toZoneId() method.

package org.kodejava.example.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class TimeZoneToZoneId {
    public static void main(String[] args) {
        ZoneId zoneId = TimeZone.getDefault().toZoneId();
        System.out.println("zoneId = " + zoneId);

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone("US/Pacific");
        ZoneId zoneIdUsPacific = timeZoneUsPacific.toZoneId();
        System.out.println("zoneIdUsPacific = " + zoneIdUsPacific);

This snippet prints the following output:

zoneId = Asia/Shanghai
zoneIdUsPacific = US/Pacific

To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId to TimeZone by using the TimeZone.getTimeZone() method and pass the ZoneId.systemDefault() which return the system default timezone. Or we can create ZoneId using the ZoneId.of() method and specify the timezone id and then pass it to the getTimeZone() method of the TimeZone class.

package org.kodejava.example.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class ZoneIdToTimeZone {
    public static void main(String[] args) {
        TimeZone timeZone = TimeZone.getTimeZone(ZoneId.systemDefault());
        System.out.println("timeZone = " + timeZone.getDisplayName());

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone(ZoneId.of("US/Pacific"));
        System.out.println("timeZoneUsPacific = " + timeZoneUsPacific.getDisplayName());

And here are the output of the code snippet above:

timeZone = China Standard Time
timeZoneUsPacific = Pacific Standard Time

How do I get a list of all TimeZones Ids using Java 8?

To retrieve a list of all available time zones ids we can call the java.time.ZoneId static method getAvailableZoneIds(). This method return a Set of string of all zone ids. The format of the zone id are “{area}/{city}”. You can use this ids of string to create the ZoneId object using the ZoneId.of() static method.

package org.kodejava.example.datetime;

import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;

public class GetAllTimeZoneIds {
    public static void main(String[] args) {
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        for (String id : zoneIds) {
            ZoneId zoneId = ZoneId.of(id);
            System.out.println("id          = " + id);
            System.out.println("displayName = " + 
                zoneId.getDisplayName(TextStyle.FULL, Locale.US));

Here are some of zone IDs printed out to the console:

id          = Asia/Aden
displayName = Arabian Time
id          = America/Cuiaba
displayName = Amazon Time
id          = Etc/GMT+9
displayName = GMT-9:00
id          = Etc/GMT+8
displayName = GMT-8:00
id          = Africa/Nairobi
displayName = Eastern Africa Time
id          = Europe/Nicosia
displayName = Eastern European Time
id          = Pacific/Guadalcanal
displayName = Solomon Is. Time
id          = Europe/Athens
displayName = Eastern European Time
id          = US/Pacific
displayName = Pacific Time
id          = Europe/Monaco
displayName = Central European Time

How do I get HTTP headers using HttpClient HEAD request?

The HTTP HEAD method is used for reading the headers information of a resource returned when accessing it using the HTTP GET method. Such request can be done before deciding to download a large resource to save bandwidth. The response to a HEAD method should not have a body, in the code below we use the HttpResponse.BodyHandlers.discarding(), which is a response body handler that discards the the response body.

In the code snippet below we start by creating an instance of HttpClient, in this example we use the HttpClient.newBuilder().build() method. After creating the HttpClient we create the HttpRequest object. We set the HTTP method to HEAD by calling the method method() and pass a string “HEAD” as the method name and HttpRequest.BodyPublishers.noBody() a request body publisher which sends no request body.

The next step in the code below is to send the request and get the response headers from the HttpResponse object using the headers() method. The map() method of the HttpHeaders object give us a key-values of the headers returned by the server.

package org.kodejava.example.httpclient;


public class HeadRequestExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder().build();

        HttpRequest request = HttpRequest.newBuilder()
            .method("HEAD", HttpRequest.BodyPublishers.noBody())

        HttpResponse<Void> response = client.send(request,

        // Returns an unmodifiable multi map view of this HttpHeaders.
        // The map contains key of string, with list of strings as
        // its value.
        HttpHeaders headers = response.headers();, values) ->
            System.out.printf("%s = %s%n", key, values));

Here are the HTTP headers we got and printed out to the console screen:

:status = [301]
alt-svc = [quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,h3-T050=":443"; ma=2592000]
cache-control = [public, max-age=2592000]
content-length = [220]
content-type = [text/html; charset=UTF-8]
date = [Wed, 22 Apr 2020 14:41:49 GMT]
expires = [Fri, 22 May 2020 14:41:49 GMT]
location = []
server = [gws]
x-frame-options = [SAMEORIGIN]
x-xss-protection = [0]

How do I read website content using HttpClient?

The HTTP Client API can be used to request HTTP resources over the network. This new API was introduced as a new API in Java 11. It supports HTTP/1.1 and HTTP/2 and also support both synchronous and asynchronous programming models. The code snippet below show you how to use the new API to read the content of a website page.

In the code below we start by creating a new instance of HttpClient using the newHttpClient() static method. This is equivalent to calling newBuilder().build(). This give us an instance of HttpClient with default settings like using the “GET” request method the as the default. Then we create an HttpRequest object using the newBuilder() method, set the request URI and call the build() method to build the HttpRequest object.

Next we send the request by calling the send() method of the HttpClient object. This will sends the given request, blocking if necessary to get the response. The returned HttpResponse object contains the response status, headers, and body as handled by given response body handler.

package org.kodejava.example.httpclient;

import java.nio.charset.StandardCharsets;

public class ReadWebsiteContent {
    public static void main(String[] args) throws Exception {
        // Creates HttpClient object with default configuration.
        HttpClient httpClient = HttpClient.newHttpClient();

        // Creates HttpRequest object and set the URI to be requested, 
        // when not defined the default request method is the GET request.
        HttpRequest request = HttpRequest.newBuilder()

        // Sends the request and print out the returned response.
        HttpResponse<String> response = httpClient.send(request,

        System.out.println("Status Code: " + response.statusCode());
        System.out.println("Headers    : " + response.headers().toString());
        System.out.println("Body       : " + response.body());

Here is the content of the website that we read using the code snippet above:

Status Code: 200
Headers    : { {:status=[200], cf-cache-status=[DYNAMIC], cf-ray=[5875b78d5df2eb00-LAX], cf-request-id=[023d710c5b0000eb00b738f200000001], content-length=[116], content-type=[text/x-rst;charset=utf-8], date=[Tue, 21 Apr 2020 08:25:53 GMT], etag=["234b9a1fe19f125356a5396c8cc72d54493a2eef"], expect-ct=[max-age=604800, report-uri=""], server=[cloudflare], set-cookie=[__cfduid=d5bdb6d828be3bb85d0f1f4c2ff81041c1587457553; expires=Thu, 21-May-20 08:25:53 GMT; path=/;; HttpOnly; SameSite=Lax]} }
Body       : 

Hello, World! đŸ‘‹

Thank you for trying out HTTPie đŸ¥³

I hope this will become a friendship.

How do I modified the value of LocalDate and LocalTime object?

The easiest way to modify the value of a LocalDate, LocalTime or LocalDateTime object is to use the with() method of the corresponding object. These methods will return a modified version of the object, it doesn’t change the attribute of the original object. All the methods, like withYear(), withDayOfMonth() or the with(ChronoField) of the LocalDate object will return a new object with the modified attribute.

With the LocalTime object you can use the withHour(), withMinute(), withSecond() or the more generic with(ChronoField) method to modified the attribute of a LocalTime object. You can also modified a LocalDateTime object using these with() method. Let’s see the example in the code snippet below.

package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class ManipulatingDateTime {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2020, 4, 21);
        System.out.println("date1 = " + date1);
        LocalDate date2 = date1.withYear(2019);
        System.out.println("date2 = " + date2);
        LocalDate date3 = date2.withDayOfMonth(10);
        System.out.println("date3 = " + date3);
        LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 12);
        System.out.println("date4 = " + date4);

        LocalTime time1 = LocalTime.of(1, 5, 10);
        System.out.println("time1 = " + time1);
        LocalTime time2 = time1.withHour(6);
        System.out.println("time2 = " + time2);
        LocalTime time3 = time2.withMinute(45);
        System.out.println("time3 = " + time3);
        LocalTime time4 = time3.with(ChronoField.SECOND_OF_MINUTE, 25);
        System.out.println("time4 = " + time4);

        LocalDate now1 =;
        System.out.println("now1 = " + now1);
        LocalDate now2 = now1.plusWeeks(1);
        System.out.println("now2 = " + now2);
        LocalDate now3 = now2.minusMonths(2);
        System.out.println("now3 = " + now3);
        LocalDate now4 =, ChronoUnit.DAYS);
        System.out.println("now4 = " + now4);

The output of this code snippet are:

date1 = 2020-04-21
date2 = 2019-04-21
date3 = 2019-04-10
date4 = 2019-12-10
time1 = 01:05:10
time2 = 06:05:10
time3 = 06:45:10
time4 = 06:45:25
now1 = 2020-04-21
now2 = 2020-04-28
now3 = 2020-02-28
now4 = 2020-03-14

These with() methods is the counterpart of the get() methods. Where the get() methods will give you the value of the corresponding LocalDate or LocalTime attribute, the with() method will change the attribute value and return a new object. It didn’t call set because the object is immutable, which means it value cannot be changed.

While with the with() method you can change the value of date time attribute in an absolute way using the plus() or minus() method can help you change the date and time attribute in a relative way. The plus() and minus() method allows you to move a Temporal back or forward a give amount of time, defined by a number plus a TemporalUnit, in this case we use the ChronoUnit enumeration which implements this interface.

How do I created tab delimited data file in Java?

The following code snippet show you how to create a tab delimited data file in Java. The tab character is represented using the \t sequence of characters, a backslash (\) character followed by the t letter. In the code below we start by defining some data that we are going to write to the file.

We create a PrintWriter object, passes a BufferedWritter created using the Files.newBufferedWriter() method. The countries.dat is the file name where the data will be written. Because we are using the try-with-resources the PrintWriter and the related object will be closed automatically when the file operation finishes.


import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class TabDelimitedDataFile {
    public static void main(String[] args) throws IOException {
        List<String[]> data = new ArrayList<>();
        data.add(new String[]{"Afghanistan", "AF", "AFG", "004", "Asia"});
        data.add(new String[]{"Ă…land Islands", "AX", "ALA", "248", "Europe"});
        data.add(new String[]{"Albania", "AL", "ALB", "008", "Europe"});
        data.add(new String[]{"Algeria", "DZ", "DZA", "012", "Africa"});
        data.add(new String[]{"American Samoa", "AS", "ASM", "016", "Polynesia"});
        data.add(new String[]{"Andorra", "AD", "AND", "020", "South Europe"});
        data.add(new String[]{"Angola", "AO", "AGO", "024", "Africa"});
        data.add(new String[]{"Anguilla", "AI", "AIA", "660", "Americas"});
        data.add(new String[]{"Antarctica", "AQ", "ATA", "010", ""});
        data.add(new String[]{"Argentina", "AR", "ARG", "032", "Americas"});

        try (PrintWriter writer = new PrintWriter(
            Files.newBufferedWriter(Paths.get("countries.dat")))) {
            for (String[] row : data) {
                    row[0], row[1], row[2], row[3], row[4]);

The output of the code snippet above are:

         Afghanistan     AF     AFG     004     Asia
       Ă…land Islands     AX     ALA     248     Europe
             Albania     AL     ALB     008     Europe
             Algeria     DZ     DZA     012     Africa
      American Samoa     AS     ASM     016     Polynesia
             Andorra     AD     AND     020     South Europe
              Angola     AO     AGO     024     Africa
            Anguilla     AI     AIA     660     Americas
          Antarctica     AQ     ATA     010     
           Argentina     AR     ARG     032     Americas

How do I use TemporalField to access date time value?

The LocalDate and LocalTime are probably the first two classes from the Java 8 Date and Time API that you will work with. An instance of the LocalDate object is an immutable object representing a date without the time of the day and on the other way around the LocalTime object is an immutable object representing a time without the date information.

The LocalDate object have methods to get information related to date such as getYear(), getMonth(), getDayOfMonth(). While the LocalTime object have methods to get information related to time such as getHour(), getMinute(), getSecond(). Beside using those methods we can also access the value of these object using the TemporalField interface. We can pass a TemporalField to the get() method of LocalDate and LocalTime objects. TemporalField is an interface, one of its implementation that we can use to get the value is the ChronoField enumerations.

Let’s see some examples in the code snippet below:

package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class DateTimeValueTemporalField {
    public static void main(String[] args) {
        LocalDate date =;
        System.out.println("Date = " + date);
        System.out.println("Year = " + date.getYear());
        System.out.println("Year = " + date.get(ChronoField.YEAR));

        System.out.println("Month= " + date.getMonth().getValue());
        System.out.println("Month= " + date.get(ChronoField.MONTH_OF_YEAR));

        System.out.println("Date = " + date.getDayOfMonth());
        System.out.println("Date = " + date.get(ChronoField.DAY_OF_MONTH));

        System.out.println("DOW  = " + date.getDayOfWeek().getValue());
        System.out.println("DOW  = " + date.get(ChronoField.DAY_OF_WEEK) + "\n");

        LocalTime time =;
        System.out.println("Time  = " + time);
        System.out.println("Hour  = " + time.getHour());
        System.out.println("Hour  = " + time.get(ChronoField.HOUR_OF_DAY));

        System.out.println("Minute= " + time.getMinute());
        System.out.println("Minute= " + time.get(ChronoField.MINUTE_OF_HOUR));

        System.out.println("Second= " + time.getSecond());
        System.out.println("Second= " + time.get(ChronoField.SECOND_OF_MINUTE));

        System.out.println("Nano  = " + time.getNano());
        System.out.println("Nano  = " + time.get(ChronoField.NANO_OF_SECOND));

The output of the code snippet above are:

Date = 2020-04-20
Year = 2020
Year = 2020
Month= 4
Month= 4
Date = 20
Date = 20
DOW  = 1
DOW  = 1

Time  = 16:06:11.389185
Hour  = 16
Hour  = 16
Minute= 6
Minute= 6
Second= 11
Second= 11
Nano  = 389185000
Nano  = 389185000

How do I get all Sundays of the year in Java?

You need the create a holiday calendar for your application. One of the functionality is to include all Sundays of the year as a holiday for your calendar. The following code snippet will show you how to get all Sundays of the given year. First we need to find the first Sunday of the year using the first 3 lines of code in the main() method. After getting the first Sunday we just need to loop to add 7 days using the Period.ofDays() to the current Sunday to get the next Sunday. We stop the loop when the year of the Sunday is different to the current year.

package org.kodejava.example.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

import static java.time.temporal.TemporalAdjusters.firstInMonth;

public class FindAllSundaysOfTheYear {
    public static void main(String[] args) {
        // Create a LocalDate object that represent the first day of the year.
        int year = 2020;
        LocalDate now = LocalDate.of(year, Month.JANUARY, 1);
        // Find the first Sunday of the year
        LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));

        do {
            // Loop to get every Sunday by adding Period.ofDays(7) the the current Sunday.
            sunday =;
        } while (sunday.getYear() == year);

The output of this code snippet are:

Sunday, January 5, 2020
Sunday, January 12, 2020
Sunday, January 19, 2020
Sunday, January 26, 2020
Sunday, February 2, 2020
Sunday, February 9, 2020
Sunday, February 16, 2020
Sunday, February 23, 2020
Sunday, December 6, 2020
Sunday, December 13, 2020
Sunday, December 20, 2020
Sunday, December 27, 2020