Thursday, 2 July 2020

FreeMarker: Working with Ranges

Ranges are used to define sequences. Ranges can be defined by specifying what ranges of whole numbers it contains.

 

Ranges are specified using .. operator.

 

Example.

2..5 gives [2, 3, 4, 5]

 

Below table specifies different ways to specify ranges.

 

Range Expression

Description

Example

start..end

Range from star number to end (inclusive)

1..4 gives [1, 2, 3, 4]

4..1 gives [4, 3, 2, 1].

start..<end or start..!end:

Range from start number to end (exclusive)

1..<4 gives [1, 2, 3]

4..<1 gives [4, 3, 2]

start..*length

Range from start to length number of items.

10..*4 gives [10, 11, 12, 13],

10..*-4 gives [10, 9, 8, 7]

start..

Unbounded range.

1.. gives [1, 2, 3,... ], up to infinity.

 

Find the below working application.

 

Step 1: Define range.ftl file under src/main/resources/templates folder.

 

range.ftl
${"Printing 1..4"}

<#list 1..4 as item>
Value of element is : ${item}
</#list>

${"Printing 4..1"}

<#list 4..1 as item>
Value of element is : ${item}
</#list>

${"Printing 1..<4"}

<#list 1..<4 as item>
Value of element is : ${item}
</#list>

${"Printing 4..<1"}

<#list 4..<1 as item>
Value of element is : ${item}
</#list>

${"Printing 10..*4"}

<#list 10..*4 as item>
Value of element is : ${item}
</#list>

${"Printing 10..*-4"}

<#list 10..*-4 as item>
Value of element is : ${item}
</#list>

Step 2: Define ‘FreeMarkerUtil’ class that takes model object 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 RangePopulator.

 

RangePopulator.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 RangePopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "range.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

Printing 1..4

Value of element is : 1
Value of element is : 2
Value of element is : 3
Value of element is : 4

Printing 4..1

Value of element is : 4
Value of element is : 3
Value of element is : 2
Value of element is : 1

Printing 1..<4

Value of element is : 1
Value of element is : 2
Value of element is : 3

Printing 4..<1

Value of element is : 4
Value of element is : 3
Value of element is : 2

Printing 10..*4

Value of element is : 10
Value of element is : 11
Value of element is : 12
Value of element is : 13

Printing 10..*4

Value of element is : 10
Value of element is : 9
Value of element is : 8
Value of element is : 7






Previous                                                    Next                                                    Home

FreeMarker: Access list/sequence data using index notation

You can access elements of list/sequence using index notation.

 

Example

<#assign primes=[2, 3, 5, 7, 11] >

 

primes[0] return the value at index 0 which is 2

primes[1] return the value at index 1 which is 3

 

Find the below working application.

 

Step 1: Define listIndexNotation.ftl file under src/main/resources/templates folder.

 

listIndexNotation.ftl

<#assign primes=[2, 3, 5, 7, 11] >

Value at 0th index ${primes[0]}
Value at 1st index ${primes[1]}
Value at 2nd index ${primes[2]}
Value at 3rd index ${primes[3]}
Value at 4th index ${primes[4]}

Step 2: Define ‘FreeMarkerUtil’ class that takes a model object 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 ListIndexNotationPopulator.

 

ListIndexNotationPopulator.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 ListIndexNotationPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "listIndexNotation.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

Value at 0th index 2

Value at 1st index 3

Value at 2nd index 5

Value at 3rd index 7

Value at 4th index 11





Previous                                                    Next                                                    Home

FreeMarker: Concatenate maps or hashes

Using ‘+’ operator, you can concatenate maps or hashes.

 

What if hashes contain the same key?

The hash on the right-hand side of the + takes precedence.

 

Example

<#assign countryCapitals = {"India":"New Delhi", "Nepal":"Khatmandu"} + {"Armenia":"Yerevan", "Brazil":"Brasilia"}>

 

- Capital of India is ${countryCapitals.India}

- Capital of Brazil is ${countryCapitals.Brazil}

 

Find the below working application.

 

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

 

hashConcatenation.ftl
<#assign countryCapitals = {"India":"New Delhi", "Nepal":"Khatmandu"} + {"Armenia":"Yerevan", "Brazil":"Brasilia"}>

- Capital of India is ${countryCapitals.India}
- Capital of Brazil is ${countryCapitals.Brazil}

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 HashConcatenationPopulator.

 

HashConcatenationPopulator.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 HashConcatenationPopulator {
	public static void main(String args[]) throws Exception {

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

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

	}
}

Output

- Capital of India is New Delhi

- Capital of Brazil is Brasilia







Previous                                                    Next                                                    Home

FreeMarker: Access map or hash content using index notation

In my previous post, I explained how to access nested properties using ’.’ notation, you can even use [] notation to access the value associated with the key.

 

For example, below map define employee details.

 

<#assign empDetails={ "id" : 1, "name": "krishna", "address" : { "city": "Bangalore", "country" : "India"} } >

 

Now you can access id and name property like below.

id : ${empDetails["id"]}

name : ${empDetails["name"]}

 

You can access nested property city in either of below notation.

city : ${empDetails["address"]["city"]}

city : ${empDetails["address"].city}

city : ${empDetails.address["city"]}

 

Find the below working application.

 

Step 1: Define ‘mapIndexNotation.ftl’ file under src/main/resources/templates folder.

 

mapIndexNotation.ftl

<#assign empDetails={ "id" : 1, "name": "krishna", "address" : { "city": "Bangalore", "country" : "India"} } >

id : ${empDetails["id"]}
name : ${empDetails["id"]}

city : ${empDetails["address"]["city"]}
city : ${empDetails["address"].city}
city : ${empDetails.address["city"]}

country : ${empDetails["address"]["country"]}
country : ${empDetails["address"].country}
country : ${empDetails.address["country"]}

Step 2: Define ‘FreeMarkerUtil’ class that takes a model object 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 MapIndexNotationPopulator.

 

MapIndexNotationPopulator.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 MapIndexNotationPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "mapIndexNotation.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

id : 1
name : 1

city : Bangalore
city : Bangalore
city : Bangalore

country : India
country : India
country : India



Previous                                                    Next                                                    Home

FreeMarker: Define a map in template file

We can define a map in template file by listing the key/value pairs separated by commas and put the list into curly brackets.

 

Example

{ "id" : 1, name": "krishna", "city": "Bangalore"}

 

Find the below working application.

 

Step 1: Define ‘mapDefinition.ftl’ file under src/main/resources/templates folder.

 

mapDefintion.ftl
<#assign empDetails={ "id" : 1, "name": "krishna", "city": "Bangalore" } >

<#list empDetails as key, value> 
${key} = ${value} 
</#list>

<#list { "id" : 1, "name": "krishna", "city": "Bangalore" } as key, value> 
${key} = ${value} 
</#list>

Step 2: Define ‘FreeMarkerUtil’ class that takes a model object 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 MapPopulator.

 

MapPopulator.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 MapPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "mapDefinition.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

id = 1 
name = krishna 
city = Bangalore 

id = 1 
name = krishna 
city = Bangalore

Previous                                                    Next                                                    Home

Wednesday, 1 July 2020

FreeMarker: Working with Map

‘list’ directive can be used to access the elements of a map.

 

Syntax1

<#list map?keys as key>

    ${key} = ${map[key]}

</#list>

 

Syntax2

<#list map as key, value>

    ${key} = ${value}

</#list>

 

Step 1: Define template file.

countryCapitals.ftl

Approach 1
-------------
<#list countries?keys as key> 
    ${key} = ${countries[key]} 
</#list> 

Approach 2
-----------
<#list countries as key, value> 
    ${key} = ${value} 
</#list>

Step 2: Define ‘FreeMarkerUtil’ class that takes a model object 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 ‘CountryCapitalsPopulator’ class.

 

CountryCapitalsPopulator.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 CountryCapitalsPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, String> countriesMap = new HashMap<>();
		countriesMap.put("India", "New Delhi");
		countriesMap.put("Nepal", "Khatmandu");
		countriesMap.put("Italy", "Vienna");
		
		Map<String, Object> modelObject = new HashMap<> ();
		modelObject.put("countries", countriesMap);
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "countryCapitals.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

Approach 1
-------------
    Italy = Vienna 
    Nepal = Khatmandu 
    India = New Delhi 

Approach 2
-----------
    Italy = Vienna 
    Nepal = Khatmandu 
    India = New Delhi



Previous                                                    Next                                                    Home

FreeMarker: Assignment Operator

Assignment Operator (=) is used to assign some value to a variable.

 

Example

<#assign a=10, b=11, c=true >

<#assign d = a + b>

 

Find the below working application.

 

Step 1: Define ‘assignmentOperator.ftl’ file under src/main/resources/templates folder.

 

assignmentOperator.ftl
<#assign a=10, b=11, c=true >

<#assign d = a + b>

a : ${a}
b : ${b}
c : ${c?string}
d : ${d}

Step 2: Define ‘FreeMarkerUtil’ class that takes model object 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 AssignmentOperatorPopulator.

 

AssignmentOperatorPopulator.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 AssignmentOperatorPopulator {
  public static void main(String args[]) throws Exception {

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

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

  }
}

Output

a : 10

b : 11

c : true

d : 21



Previous                                                    Next                                                    Home