Monday, 29 June 2020

FreeMarker: Logical Operators

Logical or: ||

Logical and: &&

Logical not: !

 

Below table summarizes the behaviour of logical operators.

a

b

a && b

a || b

!a

false

false

false

false

true

false

true

false

true

true

true

false

false

true

false

true

true

true

true

false

 

Find the below working application.

 

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

 

logicalOperators.ftl
<#assign a=true, b=false >

${b?string} && ${b?string} : ${(b && b)?string}
${b?string} && ${a?string} : ${(b && a)?string}
${a?string} && ${b?string} : ${(a && b)?string}
${a?string} && ${a?string} : ${(a && a)?string}

${b?string} || ${b?string} : ${(b || b)?string}
${b?string} || ${a?string} : ${(b || a)?string}
${a?string} || ${b?string} : ${(a || b)?string}
${a?string} || ${a?string} : ${(a || a)?string}

!true = ${(!a)?string}
!false = ${(!b)?string}

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

 

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

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

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

  }
}

Output

false && false : false
false && true : false
true && false : false
true && true : true

false || false : false
false || true : true
true || false : true
true || true : true

!true = false
!false = true


Previous                                                    Next                                                    Home

FreeMarker: Comparison Operators

== : Test for Equality

!= : Test for Inequality

< : Less Than Operator

<= : Less than or equal to

> : Greater than operator

>= : Greater than or equal to operator

 

Note

Freemarker can interpret >, >= are end of the tags. To prevent this use gt instead of > and gte instead of >=. You can even use lt instead of <, lte instead of <=,

 

Find the below working application.

 

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

 

conditionalOperators.ftl

<#assign a = 10, b = 11>

a : ${a}
b : ${b}

is a equals to a :  ${(a==a)?string}
is a equals to b : ${(a==b)?string}
is a not equals to a : ${(a!=a)?string}
is a not equals to b : ${(a!=b)?string}
is a less than a : ${(a<a)?string}
is a less than b : ${(a<b)?string}
is a less than or equal to a : ${(a<=a)?string}
is a less than or equal b : ${(a<=b)?string}
is a greater than a : ${(a>a)?string}
is a greater than b : ${(a>b)?string}
is a greater than or equal to a : ${(a>=a)?string}
is a greater than or equal to b : ${(a>=b)?string}

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 ‘ConditionalOperatorsPopulator.java’.

 

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

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

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

  }
}

Output

a : 10

b : 11

 

is a equals to a :  true

is a equals to b : false

is a not equals to a : false

is a not equals to b : true

is a less than a : false

is a less than b : true

is a less than or equal to a : true

is a less than or equal b : true

is a greater than a : false

is a greater than b : false

is a greater than or equal to a : true

is a greater than or equal to b : false



Previous                                                    Next                                                    Home

Saturday, 27 June 2020

FreeMarker: Arithmetic Operators

Arithmetic operator is used to perform an arithmetic operation between operands.

 

Following basic Arithmetic operators are supported in FreeMarker.

 

a.   Addition: +

b.   Subtraction: -

c.    Multiplication: *

d.   Division: /

e.   Modulus of integer operands: % : The sign of the result of % is the same as the sign of the left-hand operand.

 

Find the below working application.

 

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

 

arithmeticOperators.ftl

<#assign a = 10, b = 3, c = -3 >

a : ${a}
b : ${b}
c : ${c}

a + b : ${a + b}
a - b : ${a - b}
a * b : ${a * b}
a / b : ${a / b}
a % b : ${a % b}
a % c : ${a % c}

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

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

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

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

	}
}

Output

a : 10

b : 3

c : -3

 

a + b : 13

a - b : 7

a * b : 30

a / b : 3.333

a % b : 1

a % c : 1







Previous                                                    Next                                                    Home

FreeMarker: !: Set default value to missing or null values

A non-existent variable and a variable with null value is same for FreeMarker. By default, FreeMarker throws an error whenever it encounters a missing or null value. If you want to handle these null values, you should convey to FreeMarker explicitly.

 

We can specify default value to a variable using !

 

Syntax

unsafe_expr!default_expr

unsafe_expr!

(unsafe_expr)!default_expr

(unsafe_expr)!

 

For example, see the below snippet.

Welcome ${name!"visitor"}!

 

If the default value is omitted, then it will be empty string and empty sequence and empty hash at the same time.

 

When the field 'name' is missing from data model, template will behave like if user name is the string "visitor". When user name isn't missing, this template behaves exactly like ${name}

 

Similarly, we can set an empty list, if the list variable is null or not present.

 

<#list hobbies![]>

         Your Hobbies are

         <#items as hobby>

                  ${hobby}

         </#items>

</#list>

 

defaultValues.ftl
Welcome ${name!"visitor"}!

<#list hobbies![]>
	Your Hobbies are
	<#items as hobby>
		${hobby}
	</#items>
</#list>

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;
	}

}

Define DefaultValuesPopulator.

 

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

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

	}
}

Output

Welcome visitor!

 

Default value vs non-top level variable

user.name!"no_name"

This will handle if ‘name’ is missing inside user (and returns "no_name" if so), but will not handle if user is missing. That is, the user variable itself must exist, otherwise the template processing will die with error.

 

(user.name)!"no_name"

This will handle if user.name is missing. That is, if ‘user’ is missing, or ‘user’ exists but it does not contain ‘name’, the result will be "no_name", and no error will occur.



Previous                                                    Next                                                    Home

Wednesday, 24 June 2020

FreeMarker: ?int built-in: Get division result as integer

?int built-in is used to get the integer part of the result of a division.

 

Find the below working application.

 

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

 

intBuiltin.ftl

<#assign x = 21>

x/2 -> ${(x/2)?int}

1.1 -> ${1.1?int}
1.99 -> ${1.99?int}
-1.1 -> ${-1.1?int}
-1.99 -> ${-1.99?int}

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

 

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

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

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

	}
}

Output

x/2 -> 10

 

1.1 -> 1

1.99 -> 1

-1.1 -> -1

-1.99 -> -1




Previous                                                    Next                                                    Home

FreeMarker: Built-ins

Built-ins are just like methods in java. Freemarker provide lot of built-ins you can use while constructing the template files.

https://freemarker.apache.org/docs/ref_builtins.html

 

How to access built-ins?

Using ?, we can access built-ins.

 

For example, userName?upper_case will give the uppercase version of the user name.

 

builtIns.ftl

Hello ${name?upper_case}, your name has ${name?length} characters.

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;
	}

}

Define BuiltInPopulator.

 

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

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

	}
}

Output

Hello KRISHNA, your name has 7 characters.

 

You can see list of all Built-ins from the below link.

https://freemarker.apache.org/docs/ref_builtins.html

 



Previous                                                    Next                                                    Home

Free Marker: #include directive

‘include’ directive is used to insert the content of other file into the template.

 

Syntax

<#include path>
or
<#include path options>

copyright.ftl

---------------------------------------------------------------------------------
All these examples are owned by https://self-learning-java-tutorial.blogspot.com/
You can use these examples and share to others also

Author: Krishna
Date: ${today}
---------------------------------------------------------------------------------

includeDemo.ftl

<#include "/copyright.ftl">

Hello ${name}, Welcome to our Application.

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);
	}

	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;
	}

}

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

		Map<String, Object> modelObject = new HashMap<String, Object>();
		modelObject.put("name", "Krishna");

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

	}
}

Output

---------------------------------------------------------------------------------
All these examples are owned by https://self-learning-java-tutorial.blogspot.com/
You can use these examples and share to others also

Author: Krishna
Date: Fri May 22 23:51:28 IST 2020
---------------------------------------------------------------------------------
Hello Krishna, Welcome to our Application.



Previous                                                    Next                                                    Home