Friday, 12 June 2020

FreeMarker: Basic Building Blocks

There are 3 basic building blocks in FreeMarker.

 

Interpolations

Interpolations are represented by ${…}, FreeMarker will replace it with the actual value coming from the model object.

 

FreeMarker Template tags

These are instructions given to FreeMarker. Built-in template tags start with # and User defined tags start with @.

 

Example Of Built-in Tags

#if, #else, #list

 

Comments

Comments are used to document your ftl file. Comments are delimited <#-- and -->



Previous                                                    Next                                                    Home

Thursday, 11 June 2020

FreeMarker: Nested Objects example

Using ‘.’ Operator, we can access the nested objects.

 

For example, a User instance has address details nested in it. We can map the user address in template below.

 

street: ${user.address.street}

city: ${user.address.city}

country: ${user.address.country}

 

Find the below working application.

 

Step 1: Create userDetails.ftl file under src/main/resources folder.

 

userDetails.ftl
name: ${user.name}
age: ${user.age}
street: ${user.address.street}
city: ${user.address.city}
country: ${user.address.country}

Step 2: Define Address model class.

 

Address.java

package com.sample.app.templates.model;

public class Address {
	private String street;
	private String city;
	private String country;

	public Address(String street, String city, String country) {
		super();
		this.street = street;
		this.city = city;
		this.country = country;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

}

Step 3: Define UserDetails class.

 

UserDetails.java
package com.sample.app.templates.model;

public class UserDetails {

	private String name;
	private int age;
	private Address address;

	public UserDetails(String name, int age, Address address) {
		super();
		this.name = name;
		this.age = age;

		this.address = address;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

}

Step 4: Define ‘FreeMarkerUtil’ class that take model class and template file as input and merge them.

 

FreeMarkerUtil.java
package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 5: Define ‘UserDetailsPopulator’ class.

 

UserDetailsPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.templates.model.Address;
import com.sample.app.templates.model.UserDetails;
import com.sample.app.util.FreeMarkerUtil;

public class UserDetailsPopulator {
	public static void main(String args[]) throws Exception {
		Map<String, Object> modelObject = new HashMap<String, Object>();

		Address address = new Address("Chowdeswarit Steet", "Bangalore", "India");

		modelObject.put("user", new UserDetails("Krishna", 31, address));

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "userDetails.ftl");

		System.out.println(stringWriter);
	}
}

Output

name: Krishna

age: 31

street: Chowdeswarit Steet

city: Bangalore

country: India



Previous                                                    Next                                                    Home

Wednesday, 10 June 2020

FreeMarker: Interpolations

Interpolations are used to insert the value of an expression converted to text.

 

Syntax

${expression}

 

Interpolation can be used in two places.

a.   Inside the text: Hello ${name}!

b.   Inside String literal: <#include "/header/${org}.txt">

 

The result of interpolated string must be one of these values.

a.   String

b.   Number

c.    Date-time value

 

If you want to use other values like Boolean in interpolation, you should convert them explicitly.

 

Example

${b?string("yes", "no")}

 

Above statement evaluate to "yes" if the variable ‘b’ is true, else  "no".

 

Find the below working application.

 

Step 1: Create ‘interpolations.ftl’ file under src/main/resources/templates folder.

 

interpolations.ftl

<#assign a = 10, b = true, c = false, d = 123.45>

a : ${a}
b : ${b?string("yes", "no")}
c : ${c?string("yes", "no")}
d : ${d}


"a : ${a}"
"b : ${b?string("yes", "no")}"
"c : ${c?string("yes", "no")}"
"d : ${d}"

Step 2: Define ‘FreeMarkerUtil’ class that take model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		FREE_MARKER_CONFIGURATION.setFallbackOnNullLoopVariable(false);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 3: Define InterpolationPopulator.

 

InterpolationPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class InterpolationPopulator {
  public static void main(String args[]) throws Exception {

    Map<String, Object> modelObject = new HashMap<String, Object>();

    StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "interpolations.ftl");
    System.out.println(stringWriter.toString().trim());

  }
}

Output

a : 10
b : yes
c : no
d : 123.45


"a : 10"
"b : yes"
"c : no"
"d : 123.45"


Previous                                                    Next                                                    Home

Tuesday, 9 June 2020

FreeMarker: Hello World Application

In this post, I am going to create 'user.ftl' file which has user template data and merge the template with fields from user object using Freemarker.

 

Step 1: Create user.ftl file under src/main/resources/templates folder.

 

user.ftl

name: ${user.name}
age: ${user.age}
city: ${user.city}

Step 2: Define a model class that holds user information.

 

User.java

package com.sample.app.templates.model;

public class User {

	private String name;
	private int age;
	private String city;

	public User(String name, int age, String city) {
		super();
		this.name = name;
		this.age = age;
		this.city = city;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}

Step 3: Create 'FreeMarkerUtil' class that takes a model object and freemarker template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 4: Define UserPopulator class like below.

 

UserPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.templates.model.User;
import com.sample.app.util.FreeMarkerUtil;

public class UserPopulator {
	public static void main(String args[]) throws Exception {
		Map<String, Object> modelObject = new HashMap<String, Object>();

		modelObject.put("user", new User("Krishna", 31, "Bangalore"));

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "user.ftl");

		System.out.println(stringWriter);
	}

}

Run UserPopulator, you will see below messages in the console.

name: Krishna
age: 31
city: Bangalore

As you see the output, placeholders ${user.name}, ${user.age}, and ${user.city} are populated with actual values from the model object.

 

You can visualize this data model as a tree kind of structure.

(root)
  |
  +- user 
      |
      +- name
      +- age
      +- city



Previous                                                    Next                                                    Home

Monday, 8 June 2020

Introduction to Freemarker

Freemarker is a Java-based template engine.

 

In Freemarker, you can define a template in a text file. That template contains some place holders to populate the data, and some conditional statements, loops etc., 

Once we feed the template, model object to FreeMarker engine, it results in merged output.


Advantage

We can separate the presentation and business logic. Template contains the following sections.

a.   Text: Text to be printed in output

b.   Interpolation: Interpolations are delimited by ${ and } will be replaced with actual value at the time of merging

c.    FLT tags: These are instructions given to FreeMarker, these will not print anything

d.   Comments: Used to document the template. Comments can be placed inside ftl tags and interpolations.

 

Example

<#-- Include Demo -->

<#include "/copyright.ftl">

Hello ${name}, Welcome to the Application.


<#-- Include Demo -->: This is comment

#include: Ftl tag

${name}: Interpolation, replace the variable 'name' with the actual value supplied by model object.

Welcome to the Application: This is text


In which language template file is written?

Template file is written in FTL (FreeMarker Template Language).


Reference

https://freemarker.apache.org/





Previous                                                    Next                                                    Home

Freemarker tutorial


      Introduction to Freemarker
      Hello World Application
      Interpolations
      Nested Objects example
      Basic Building Blocks
      Comments
      Escaping Sequences
      Raw String Literals
      Directives
      if directive
      #else directive
      elseif directive
      #list directive
      Specify list elements in the template
      Items in the list are expressions
      Concatenate lists or sequences
      list or sequence slicing
      #sep directive
      items directive
      #include directive
      Built-ins
      ?int built-in: Get division result as integer
      !: Set default value to missing or null values
      Arithmetic Operators
      Comparison Operators
      Logical Operators
      ??: Check for existence (null) of variable
      Assignment Operator
      Working with Map
      Define a map in template file
      Access map or hash content using index notation
      Concatenate maps or hashes
      Access list/sequence data using index notation
      Working with Ranges
      assign Directive: Define variables
      Working with Strings
            String concatenation
            Access a character in string using index notation
            String slicing
            Load the template from a string
            StringTemplteLoader: Load templates from strings
      Define Custom Directive
            macro: Define Custom Directive
            Define custom directive by implementing TemplateDirectiveModel interface
Previous                                                    Next                                                    Home

How to run WireMock service on different port?

Following options are used to customize http, https ports.

--port, --https-port.

 

Example

java -jar wiremock-standalone-2.9.0.jar --port 8888 --https-port 9999 


Previous                                                    Next                                                    Home