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

Sunday, 31 May 2020

Run WireMock in standalone mode

Step 1: Go to following location, navigate to the latest version of wiremock and download latest jat file.

https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/

 

At the time of writing this article 2.9.0 is the latest wiremock version.

$ls
wiremock-standalone-2.9.0.jar


Run wiremock in standalone mode by executing the below command.

java -jar wiremock-standalone-2.9.0.jar

$java -jar wiremock-standalone-2.9.0.jar
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
 /$$      /$$ /$$                     /$$      /$$                     /$$      
| $$  /$ | $$|__/                    | $$$    /$$$                    | $$      
| $$ /$$$| $$ /$$  /$$$$$$   /$$$$$$ | $$$$  /$$$$  /$$$$$$   /$$$$$$$| $$   /$$
| $$/$$ $$ $$| $$ /$$__  $$ /$$__  $$| $$ $$/$$ $$ /$$__  $$ /$$_____/| $$  /$$/
| $$$$_  $$$$| $$| $$  \__/| $$$$$$$$| $$  $$$| $$| $$  \ $$| $$      | $$$$$$/ 
| $$$/ \  $$$| $$| $$      | $$_____/| $$\  $ | $$| $$  | $$| $$      | $$_  $$ 
| $$/   \  $$| $$| $$      |  $$$$$$$| $$ \/  | $$|  $$$$$$/|  $$$$$$$| $$ \  $$
|__/     \__/|__/|__/       \_______/|__/     |__/ \______/  \_______/|__/  \__/

port:                         8080
enable-browser-proxying:      false
no-request-journal:           false
verbose:                      false

As you the console output, you can confirm that wiremock stared and listening on port 8080.

 

Open the url 'http://localhost:8080/__admin/recorder/' to see recorder user interface.


Once you start WireMock in standalone mode, you can see that following two folders are created.

 

a.   mappings : It contain request, response json

b.   __files: It contains response messages, errors json

 

$ls
__files       mappings      wiremock-standalone-2.9.0.jar

 

Let’s create an end point /employees/1

Create employeesById.json file in mappings folder.

$tree
.
├── __files
├── mappings
│   └── employeesById.json
└── wiremock-standalone-2.9.0.jar

2 directories, 2 files

employeesById.json

{
  "request": {
    "urlPattern": "/employees/1",
    "method": "GET"
  },
  "response": {
    "status": 200,
    "headers": {
      "Content-Type": "application/json"
    },
    "body": "{ \"id\":1,\"firstName\" : \"Rama\",\"lastName\": \"Gurram\"}"
  }
}

Restart WireMock application.

 

Open the url ‘http://localhost:8080/employees/1’ in browser, you will see following json.

{ "id":1,"firstName" : "Rama","lastName": "Gurram"}


Create an employee

Create ‘createEmployee.json’ file in mappings folder.

 

createEmployee.json

{
  "request": {
    "urlPattern": "/employees",
    "method": "POST",
    "bodyPatterns": [{
      "equalToJson": "{\"firstName\":\"Ram\",\"lastName\" : \"Gurram\"}"
    }]
  },
  "response": {
    "status": 201,
    "headers": {
      "Content-Type": "application/json"
    },
    "body": "{\"id\":1,\"firstName\":\"Ram\",\"lastName\" : \"Gurram\"}"
  }
}

Restart WireMock Service.

 

Open any REST client like postman and hit following request.

 
API: http://localhost:8080/employees
Method: POST
Payload:
{"firstName":"Ram","lastName" : "Gurram"}
 

You will get following response.

{
    "id": 1,
    "firstName": "Ram",
    "lastName": "Gurram"
}





Previous                                                    Next                                                    Home