POLITECHNICA UNIVERSITY OF BUCHAREST FACULTY OF AUTOMATIC CONTROL AND COMPUTERS COMPUTER SCIENCE DEPARTMENT DIPLOMA PROJECT Graphical FreeMarker… [603297]

POLITECHNICA UNIVERSITY OF BUCHAREST
FACULTY OF AUTOMATIC CONTROL AND COMPUTERS
COMPUTER SCIENCE DEPARTMENT

DIPLOMA PROJECT
Graphical FreeMarker Editor

Thesis supervisor :
Prof. Magnificus Academicus

Author:
Adelina – Gabriela Chelcea

BUCHA REST
2017

Graphical FreeMarker Editor

Table of Contents

1. Introduction ………………………….. ………………………….. ………………………….. ………………………….. …… 4
2. The FreeMark er Template Engine ………………………….. ………………………….. ………………………….. ……. 6
2.1 Description ………………………….. ………………………….. ………………………….. ………………………….. 6
2.2 Concepts ………………………….. ………………………….. ………………………….. ………………………….. … 6
2.3 FreeMa rker Template Language features ………………………….. ………………………….. ……………….. 8
2.4 Related languages and similarities ………………………….. ………………………….. …………………………. 9
2.5 FreeMarker versus Velocity ………………………….. ………………………….. ………………………….. …… 10
2.6 Software Projects which use FreeMarker ………………………….. ………………………….. ………………. 11
3. Existing editors and re lated work ………………………….. ………………………….. ………………………….. …… 12
3.1 FreeMarker -based file PreProcessor ………………………….. ………………………….. …………………….. 12
3.2 FreeMarker IDE ………………………….. ………………………….. ………………………….. ………………….. 13
3.3 TextMate ………………………….. ………………………….. ………………………….. ………………………….. 13
3.4 Emacs ………………………….. ………………………….. ………………………….. ………………………….. ….. 13
3.5 Online FreeMarker Template Tester ………………………….. ………………………….. …………………….. 14
3.6 Netbeans ………………………….. ………………………….. ………………………….. ………………………….. 14
3.7 Graphical FreeMarker Editor ………………………….. ………………………….. ………………………….. ….. 14
4. Editor architecture ………………………….. ………………………….. ………………………….. ……………………… 16
4.1 Programming languages ………………………….. ………………………….. ………………………….. ……….. 16
4.2 The architectural model ………………………….. ………………………….. ………………………….. ……….. 16
4.3 Packages structure ………………………….. ………………………….. ………………………….. ………………. 23
5. Implementation details ………………………….. ………………………….. ………………………….. ……………….. 24
5.1 FreeMarker Editor as a plugin ………………………….. ………………………….. ………………………….. … 24
5.2 FreeMarker User Interface ………………………….. ………………………….. ………………………….. ……. 27
5.3 Business logic implementation ………………………….. ………………………….. ………………………….. .. 30
5.4 Design Patterns ………………………….. ………………………….. ………………………….. ………………….. 31
6. Use case ………………………….. ………………………….. ………………………….. ………………………….. ………. 34
6.1 Featur es ………………………….. ………………………….. ………………………….. ………………………….. .. 34
6.2 Unit tests ………………………….. ………………………….. ………………………….. ………………………….. 39
7. Conclusions and Future Work ………………………….. ………………………….. ………………………….. ……….. 40

Graphical FreeMarker Editor

The idea of creating a temp late that can be used in the generation of dynamic output text
has become more and more widespread. Originally, the focus was on creating dynamic web
pages, but nowadays any output format can be generated with the aid of a specialized language
for writing templates and an engine able to interpret them.
Graphical FreeMarker Editor is a Java Netbeans plugin designed to build FreeMarker
templates using graphical components mapped to the actual FreeMarker syntax . Besides the
FreeMarker language, it also prov ides support for programming languages like: C, C#, C++, Java,
HTML and can be easily extended.
This editor proves to be very useful when the user needs to create custom templates
containing source code written in one of the supported programming language s. Apart from the
built -in FreeMarker functions provided by this tool, custom function s that are language specific
can be defined an d used afterwards in the creation of the template.

Graphical FreeMarker Editor

Chapter 1
Introduction

The need of creating output text based on dyna mic data has increased over the last few years.
Templating is a concept used for represent ing data in readable and attractive forms . The templating
solutions consist of a document, which is the template, and the data, typically represented by
placeholders. The final output is a combination between the template and the information
referenced by the placeholders and it is usually produced with the aid of a template engine . A
template engine allows developers to generate output files, s uch as HTML, source code files, emails,
etc., by replacing variables in a template file with the actual values.
Nowadays, the most used Java -based template engines are FreeMarker, Velocity and Java Server
Pages (JSP) . Whilst JSP is web oriented, FreeMarker and Velocity can genera te any output format
such as source code, emails, configuration files, HTML web pages, etc. FreeMarker is the newest
technology and it is focused on keeping separated the rendered data from the business logic which
lies behind the template . The dynamic dat a is processed in a programming language and then
passed to the template to display it. The data is referenced from the template using placeholders,
therefore changes in the data processing would not affect the template appearance.
Slowly but steadily, Fr eeMarker attempts to replace the old templates by providing new features
and increased performance. For migration purposes, FreeMarker can convert Velocity templates into
FreeMarker templates. With the increasing ly usage of this language, the need of havin g editors for
creating or modifying a template also appears. Already existent editors like TextMate, Emacs or
other plugins available in Eclipse or NetBeans IDE, offer support for syntax highlighting or content
assist.

Graphical FreeMarker Editor

Graphical FreeMarker Editor is a tem plate editor which makes use of graphical components from
JavaFX mapped to the actual FreeMarker syntax in order to generate FTL templates . It was
developed as a module for the NetBeans platform and it can be used for creating custom templates
in an intera ctively way. Although the main template language used is FreeMarker and the scope is to
generate a n FTL template, the editor also provides support for programming languages like C, C#,
C++, Java, HTML. This support resides in the possibility of adding bloc ks of code from the mentioned
programing languages inside the FreeMarker template. Thus, the combination between FreeMarker
template language and a real programming language will result in a n FTL template which can be
interpreted by the FreeMarker engine. The user is allowed to create new language -specific
functions depending on the selected programming language. These functions are stored for a
subsequent usage and they can also be deleted.
As a result, the generation of source code files becomes easier taking the advantage of the custom
templates created using the Graphical FreeMarker Editor. Moreover, designing a FreeMarker
template which contains language -specific functio ns is much handier using an interactive graphical
interface.

Graphical FreeMarker Editor

Chapter 2
The FreeMarker Template Engine

2.1 Description
FreeMarker is a Java -based Template Engine, a powerful library used for generating outputs based
on predefined templates and changing data coming from outside the templates.
Originally, this engine was focused on generating dynamic web pages in MVC web application
frameworks. Due to the fact that it has no dependency on servlets or HTML, it proves useful for non –
web application environments too. Taking into consideration this characteristic, FreeMarker turns to
be a general -purpose template engine which generates any output format , such as: source code, e –
mails, HTML web pages, configuration files.
FreeMarker Template Language (FTL) is a specialized language used for writing the template files.
The changing data is prepared in a real programming language and passed to t he template to display
it. The job of the FreeM arker template engine is to replace the tags from the source file with the
data received. This separation between processing data and rendering it gives the possibility to avoid
introducing complicated logic in the templates. Another advantage would be that you can change
the code that processes data without affecting the template and the appearance of the template can
also be modified without producing an y effect on the data.
2.2 Concepts
There are two c entral concepts in FreeMarker: t emplate and ModelRoot . Any text file which
contains FreeMarker tags can be considered a template. The ModelRoot is the root of the data

Graphical FreeMarker Editor

model and it is represented as a recur sive tree structure. Generally speaking, objects are placed into
the ModelRoot and they are extracted by the controller and passed to the view.
There are four categories of objects that can be distinguished by FreeMarker engine .
TemplateScalarModel , TemplateListModel , TemplateHashModel and
TemplateMethodModel interfaces render the shape of the objects that can be int erpreted b y
the engine. FreeM arker provides implementations for all of them. The SimpleScalar is an
implementation for TemplateScalarModel and represents single -valued objects like String
or boolean . HashTable java object is represented in FreeMarker Template by SimpleHash , an
implementation for TemplateHashMod el. It has the same role as in J ava, to keep associative
arrays represented by a uniqu e key. The SimpleList class is similar to java.util.List ,
including some extra methods like “rewind”. T he TemplateMethodModel interface has a
mechanism through which you can call methods from the mo del layer by passing arguments from
the presentation layer .
Complex data models can be designed in FreeMarker due to the orthogonality of the elements. For
example, you can create a list of lists by having a SimpleList whose elements are other
SimpleLists . The ModelRoot can contain any number of nested lists, ha shes and methods. The
leaves of the ModelRoot must be scalars. They cannot contain other type of objects. The object
serving as a ModelRoot has to be an instance of a TemplateModelRoot interface.
SimpleHash implements this interface, thus being the most co mmonly used as a ModelRoot .

Graphical FreeMarker Editor

The following diagram can represent a possible ModelRoot tree structure:

The ModelRoot , whose instance is a TemplateHashModel , more exactly a SimpleHash
object, contains a TemplateListModel object. The elements of this list a re
TemplateHashModel objects and each object contains key -value pairs where the key is a String
(a TemplateScalarModel ) and the value is a list of TemplateScalarModel objects
(scalars). The root interface that all FreeMarker objects must implement is calle d
TemplateModel . TemplateScalarModel objects implement this interface.

2.3 FreeMarker Template Language features
FTL is considered a powerful template language. It can define conditional blocks, assignments,
formatting strings and arithmetic operations, funct ions, macros and it can use a rich library with
predefined directives in order to iterate data collections. It also offers internalization and
localization -aware through sensitive number and date/time formatting, localized template variation
and it has XML processing capabilities. Any template can be loaded from any place in an .ftl file and Figure 1 – Model Root Example

Graphical FreeMarker Editor

any output format can be generated. It supports a versatile data -model. The way in that the
templates see the data is decided by a tree of variables containing Java obj ects which is exposed to
the template through pluggable adapters.
The FreeMarker syntax is very easy to comprehend, but it has the disadvantage of containing a long
list of established syntax. The main components used in a FreeMarker template in order to
dynamically create an output text are:
 interpolations: ${expression} – FreeMarker takes the actual value of the
expression inside the curly brackets and displays it in the output
 FTL tags (directives): these are instructions which will not be printed in t he output
and they are similar to HTML tags; The name of every tag should start with # or @
(for user -defined FTL tags)
 Comments: they are also similar to the HTML comments, except to the fact that they
are delimited by <#– and –> and they won’t be displ ayed in the output because
FreeMarker skips them.
FreeMarker will not be able to interpret anything that is not a comment, an interpolation or an FTL
tag. As a consequence, the remaining content of the template will be considered static text and it
will be printed to the output as -it-is.

2.4 Related languages and similarities
FTL (FreeMarker Template Language) is similar to JSP (Java Server Pages), but much cleaner. JSP is a
technology used in the java web development. As in FreeMarker Template Language, it al lows you to
add dynamic content to the web pages. Without JSP, a developer would have to update manually
the content of plain static HTML pages.
There are some key points that differentiate FTL fr om JSP language though. While you can use JSP to
write an e ntire application, FTL does not allow you to do this because of the restriction of being a

Graphical FreeMarker Editor

view -only technology. Taking the example of displaying data from a database, FTL requires having
the data collected in a model object, while JSP can make database ca lls. The biggest difference is
that FreeM arker does not require a servlet container. It has zero dependencies, therefore the
application becomes much more maintainable and every text -based output can be rendered.
Moreover, taking the case when you want to include other files, FreeM arker takes the content and
processes it as if the content were inline, whilst JSP needs to go through the servlet, which comes
with an extra over head. Another advantage of FreeM arker templates is that they are not required to
be located in any certain place and they can be packaged with jars, opposed to the .jsp files which
have to be placed in the WEB -INF directory.
Similar to the case of JSP files, when a Free Marker template is read for the first time, a sl owdown is
encountered. But FreeM arker keeps the template for further use and checks periodically for
updates. If the data is changed, Free Marker will reload the template. Anot her improvement brought
by FreeM arker is the <#compress> directive which removes any extra space from the output, this
being considered a problem in the JSP output.

2.5 FreeMarker versus Velocity
Another template engine with a widespread use is Velocity. Both of them can generate any output
format. Although Velocity seems to be more flexible than FreeMarker , it can also generate altered
output text. It allows references to non -existing properties, whilst FreeMarker generates a null
pointer exception. Macros can be called recursively in FreeMarker, while Velocity tries to keep the
template as simpler as possi ble. FreeMarker has more functionality, such as comparing date and
time values, breaking out of loops or detecting if the current it eration is the last in a loop.
Moreover, it allows the usage of multiple namespaces for variables.
Both FreeMarker and Velo city support resource loaders , which are classes used for loading
templates or other resources from locations like the file system or an HTTP server. The two template
engines follow the same usage pattern: instantiate an engine or template , put dynamically data into
it and call a parse function to create the output. Usually , the data provided to the template engine is

Graphical FreeMarker Editor

a collection or a container, such as a HashMap . Template engines provide special classes for feeding
data. They are usually called context or model . As mentioned before, FreeMarker provides a
SimpleHash class (among others) and Velocity a VelocityContext class.
For the purpose of migration to the newest technology, FreeMarker can convert Velocity templates
to FreeMarker templates. Velocity can execute embedded Java code if the objects are available in
the context supplied to Velocity, while FreeMarker keeps a strict separation between the actual view
logic and the rendered view.
Regarding the performance of the template engines, it also depends on the surrounding application.
Both FreeMarker and Vel ocity are very capable template engines and offer good performance on
small templates. For the parsing of larger templates, FreeMarker engine proves to be faster than the
Velocity engine.
Software Pr ojects which use FreeMarker
There are many software projects that incorporate Freemarker, such as: APT-Jelly, EnvGen, JCopist,
LiferayPortal, MessageGears, NetBeans, TrackStudio, etc. APT -Jelly is an engine that generates
artifacts from Java source code us ing a template -oriented approach. EnvGen is an Ant task that uses
FreeMarker in order to generate different versions of the same file , parameterized for different
environments. LiferayPortal is one of the most widely adapted portal solutions. It uses FreeM arker
for themes, page layout, fragments of structured content, email, portlet views, and code generation.
NetBeans uses Free Marker for source code templates. TrackStudio is an issue and bug tracking
system used by sof tware development companies. It uses F reeMarker to format the e -mail
notification messages.
As a conclusion to this chapter, FreeMarker proves to be a powerful template language, easily
extensible and with an increasingly usage in generating output text with dynamic content.

Graphical FreeMarker Editor

Chapter 3
Existing editors and related work

FreeMarker has been increasingly widely used in the recent years, thus more and more tools make
use of its features. Not only integrated development env ironments like NetB eans and Eclipse
provide support for FreeMarker templ ate language. Standalone applications like graphical text
editors or even web applications use the template language to generat e output text or provide
support for it. Some of them are briefly described in this chapter.

3.1 FreeMarker -based file PreProce ssor
FMPP (FreeMarker -based file PreProcessor) is a text file preprocessing tool used for generating
source code, websites, configuration files, etc. It is based on FreeMarker templates and it is useful to
process entire directories recursively. Not only can processing be done recursively, but also the
processing mode can be chosen for each file. Using patterns, a file can be executed as template or
parsed as XML and even ignored if it is a bad source file. Apart from this, the order of the processed
files can be guaranteed in the bulk file processing. Not to mention the fact that data from different
sources can be inserted in the generated files. Some unusual supported data sources are: XMLs, CSV,
JSON, System clock, Ant properties, Java properties file a nd even plain text file.
With reference to FreeMarker as the preprocessor language, FMPP uses all the usual template
constructs, macros, variables. It allows complex expressions, being also extensible with custom
functions and number and date/time formatti ng using patterns. It is capable of capturing block of
output into variable or transforming/filtering these blocks. Furthermore, automatic and manual
escaping can be used.

Graphical FreeMarker Editor

Similar to the typical XSLT usage pattern, FMPP is able to render/transform XML fil es using
FreeMarker templates. Another advantage of this tool is the possibility of generating multiple
output files from a single source file and to query the size or the existence of source files.
FreeMarker -based file PreProcessor is a Java application and it requires the installation of Java. Apart
from this, Ant is needed for the FMPP Ant task.

3.2 FreeMarker IDE
FreeMarker IDE is an Eclipse plugin developed as part of JBoss Tools. The main features of this plugin
consist in syntax highlighting, outline v iew and content assist. Regarding the content that
FreeMarker IDE is able to handle, besides the variable that are Object aware, other components
such as directives, macros and macro parameters are found.

3.3 TextMate
TextMate is a powerful graphical text ed itor for Mac OS which includes support for all major
programming languages. Apart from declarative customizations, recordable macros, opening
documents tabs, snippets and shell integration, TextMate also offers an extensible bundle system.
TextMate -FreeMar ker-Bundle is a very simple package that provides a part of the FreeMarker
language definition and some basic snippets. It proves useful when it comes to syntax highlighting.
3.4 Emacs
Emacs, described as “the extensible, customizable, self -documenting, real -time display editor”,
provides an autonomous major -mode for editing web templates, called web -mode.el. This part of
Emacs family offers compatibility with many template engines among which FreeMarker is included.
Syntax highlight, block folding, indentation , code navigation are the main features of this editor.

Graphical FreeMarker Editor

3.5 Online FreeMarker Template Tester
Online FreeMarker Template Tester is a web application which performs evaluation of FreeMarker
expressions by inserting a data model and a template. It does not need a development environment
and it allows the usage of the built -in functions, directives and all the other features of the
FreeMarker Template Language. Moreover, this application allows the user to set the output format,
the locale and the time zone. It h as support fo r more than forty languages and the output format
can be: XML, RTF, HTML, XHTML, plain text or undefined.

3.6 Netbeans
FreeMarker has also support for Netbeans. The features available are mostly focused on syntax
(coloring, error highlighting, aut odetection, tags matching), but also on code completion of
directives, ftl -tag parameters, built -ins functions and configuration of embedded language, such as
HTML, which is the default.

3.7 Graphical FreeMarker Editor
Graphical FreeMarker Editor brings the p ossibility of customizing your own template using not only
build -in FreeMarker functions, but also user -defined functions for the supported languages . The
main feature of this editor is to generate custom templates that can be interpreted by the
FreeMarke r engine. The generated template can contain pieces of code written in programming
languages such as C, C++, Java, HTML and it can be easily extended.
What differentiates the FreeMarker Editor from the other text editors is the possibility of creating
new custom functions depending on the programming language selected and using them afterwards
in the creation of the template. The created functions are stored for a subsequently usage, but they
also can be deleted if the user wants. The custom template is v alidated against the errors that can
be thrown by generating the output file using the FreeMarker template engine.

Graphical FreeMarker Editor

FreeMarker Editor is designed as a module for the NetBeans IDE and offers a user -friendly interface
that allows the user to create interactiv ely a custom template. It is focused on the creation of
templates that generates source code files. The content of the template depends on the
selected programming language for which the user intends to create the sources.

Graphical FreeMarker Editor

Chapter 4
Editor architecture

4.1 Prog ramming languages
FreeMarker Editor is a Java based application. For the implementation of this editor, the backend is
written in Java and the graphical user interface is designed in JavaFX.
Java is one of the most popular programming languages designed t o have as few implementation
dependencies as possible. It is object -oriented and it supports concurrency. The biggest advantage of
the Java programming language is given by the characteristic of being a cross platform. A compiled
Java program can run on an y platform for which a Java Virtual Machine exists, regardless of
computer architecture.
JavaFX is a Java API which enable s developers to create client applicatio ns with a consistent behavior
across platforms. It offers sets of graphic and media packages, thus facilitating the creation of a
complex graphical user interface. The graphical components can be customized using Cascading
Style Sheet (CSS), thus a separation between the declaration of the components and the stylization
can be done.
4.2 The architec tural model
The FreeMarker Editor’s architecture tries to follow the MVC (Model -View -Controller) pattern. MVC
is a software architecture designed to separate business logic from the user interface. To provide
this separation, the application is divided in three big parts: model, view and controller.

Graphical FreeMarker Editor

The model is defined by the internal representation of information and it is the central component
of the MVC pattern. A view is the component which facilitates the interaction between the user and
the applicat ion. The controller takes over the input received from the user through the view and
transforms it to commands for the model or for the view.
In the following image, we try to emphasize the separation between the MVC components within
the Graphical FreeM arker Editor implementation.

Apart from the division of the application, the model -view -controller design also defines the
interactions between the components. There are two big concepts of how this interaction should be
done. They are presented in the following diagrams:
Figure 2 – FreeMarker Editor with MVC Architecture
Figure 3 – MVC Model 1 Figure 4 – MVC Model 2

Graphical FreeMarker Editor

In Figure 3, the basic MVC architecture is illustrated. As it can be seen, the interaction is circular. The
user sends commands to the controller in order to manipulate the data stored in the model. When
the model is modifie d, the view is notified and the updated data is presented to the user. This
architecture is closely linked to the Struts Framework which encourages the use of model -view –
controller architecture. Struts is an open -source framework used for developing Java E E web
applications.
The interaction presented in the figure 4 is usually used in the Spring -based web applications. It
defines the Spring MVC architecture and it has the advantage of decoupling the data access and
business logic from the user interface. S pring is an open -source application framework with
extensions for building web applications.
Both frameworks rely on Java technologies, such as Java beans, Java servlets, Java Server Pages and
XML. The main difference between Spring MVC and Struts MVC in t erms of the architectural model
adopted comes from the fact that Spring MVC is a loosely coupled framework, whilst Struts is tightly
coupled. In order to have a reusable, robust and distributed application, the Spring MVC
architecture is recommended. Another advantage of the Spring MVC architecture is the
characteristic of being view -agnostic. In comparison with the original Struts (not Struts 2) that uses
JSP for the view implementation, Spring MVC may use many technologies, such as: Velocity,
FreeMarker , XSLT, JSP. Furthermore, if a custom view mechanism is needed, Spring MVC offers the
possibility of integrating it in the view interface.
FreeMarker Editor was conceived using the Spring MVC architecture, the view being implemented
using JavaFX framewor k. The user interface is loosely coupled with the business logic, therefore it
can be easily replaced by any other technology.
As mentioned above, the MVC architecture is designed around three components: the model, the
view and the controller.The model is the representations of the data and manages the fundamental
behaviors. In addition to the role of providing information when a request is made by the controller
and of updating its state, in an event -driven system, the model also notifies the observers when
information changes.

Graphical FreeMarker Editor

The view is the component directly exposed to the user. The information stored in the model is
rendered into a user -friendly form. Furthermore, it retrieves the input from the user and sends it to
the controller in order to be pro cessed.
The controller receives the input from the view and processes it. This component can ask the model
for information, which can be delivered to the view in order to serv e the needed data to the user.
Moreover, it can make requests for updating the m odel if the user input appeals it. When the model
changes, the controller sends commands to its associated view, therefore the correct data is
presented to the user.
In the following diagram, a bigger picture of the FreeMarker Editor architecture is prese nted :

Figure 5 – FreeMarker Editor Architecture
The picture above shows the splitting between the model, view and controller within the
FreeMarker Editor implementation.

Graphical FreeMarker Editor

The view consists of three TopComponents and two Stages . Both TopComponent and Stage
are part of the Wi ndows API. The TopComponent is a subclass spec ialized in working with the
NetB eans window system. A Stage is a specific sort of Window which inherits some methods and
parameters from the Window class.
The picture below presents how each window is populate d with elements defined in a
correspondent file with the aid of a file loader.

All these windows containing visual components with which the user can interact compose the
presentation layer. It does not contain business logic and it is used only to expos e the data and to
get the user input.
The model is a representation of the data retrieved from the input files or from the user through the
controller when it comes to generating the templates. The information stored in the model consists
of the built -in and other user -defined functions and they are displayed in the view in a user -friendly
manner. All the functions are loaded from XMLs files and the templates are stored in a different
repository as it can be seen in the following diagram. Figure 6 – FreeMarker Editor View

Graphical FreeMarker Editor

Figure 7 – FreeMarker Editor Mode l
The controller incorporates many classes that make requests to the model or send data to the view.
Every window exposed to the user has an associated controller from which receives commands to
update the view. Each controller is responsible for providing specific functionalities like creating a
new function, deleting a function, handling the generation of a template.
Depending on the user input, there are cases when the controllers have to communicate with each
other. This interaction is not done direct ly, so as not to insert complicated logic hard to maintain. An
application state object is used to notify the ri ght controller if any change occurred. Thus, the
modularity of the application is preserved. Any information that a controller wants to forward to
another controller is saved in the application state object. When a controller is notified, if it needs
some extra information to send to the view, it takes it from the model or from the application state
in the case of data processed by other controlle rs.
The following diagram is a representation of the interaction between the classes that define the
controller component of the MVC architecture. The interaction with the other components of the
MVC architecture is also conceptually illustrated.

Graphical FreeMarker Editor

Figure 8 – FreeMarker Edito r Controller

Graphical FreeMarker Editor

4.3 Packages structure

As it can be seen in the image above, the structure of the project also tries to follow the MVC
architecture. The view component consists of two packages: windows and gui . The top
components , representative for a plugin , are found in the windows package. The gui package
contains all the needed FXML files where the elements of the user interface are declared. In the
controllers package, we can find all the java classes, together representing the controller
component of the MVC architecture. Each controller is bind to an FXML file. The model package
consists of classes that define the model of data used within the application. The input files and the
generated templates are located in the repository package. Figure 9 – Project structure

Graphical FreeMarker Editor

Chapter 5
Implementation details

5.1 FreeMa rker Editor as a plugin
FreeMarker Editor was implemented as a module for the NetBeans Platform, a Java framework used
in the development of large desktop applications. A module is managed by the NetBeans Module
System, which is responsible for creating th e class loader, loading modules and
activating/deactivating them. It is comparable to a plugin and it can be defined as being a set of Java
classes which provides an application with a specific feature. A module is packed into a simple JAR
archive, includ ing meta information that enables the Runtime Container to manage it. It consists of a
manifest and a layer file, class files and other resources such as icons, properties bundles, etc. The
manifest file identifies the module by its description and its env ironment, which makes it a
mandatory file. This specific file contains the module description and dependencies on other
modules and it is the first file read by the module system during the loading of the modules. A
manifest file can contain a multitude of attributes used for defining versions and dependencies,
certain service provider interfaces and implementations and even the visibility of modules within the
plugin manager.
Information about the name, version, the location of the module and how it is loa ded can be found
in an XML configuration file. The xml represents a declaration for the module in the module system
and it is located outside the module, in the directory config/Modules .
In addition to the listed files, a module can also contain a Layer fi le, responsible for creating a virtual
image of what the module adds to the Platform. This file can be seen as an interface between the

Graphical FreeMarker Editor

module and the NetBeans Platform, describing the integration between them. It has a hierarchical
structure and it contai ns folders, files and attributes.
A module has a life cycle which can be accessed via annotations. As a consequence, some blocks of
code can be executed when a module starts, shuts down and when the window system initializes.
The window system is responsib le for the administration and display of all application windows,
providing the opportunity to customize the layout of the user interface.
The window system consists of modes that are containers in which windows can be displayed like a
tab. WindowManager class is in charge of managing all the displayed windows. Configurations
about windows, modes and groups are stored in the layer file. As a result, a module can set its
available windows, group them and also associate them with modes.
FreeMarker Editor consists of five windows, three of them being displayed when the application
starts and the other two windows being invoked by the user. The windows that appear when the
application starts are subclasses of TopComponent and they are managed by the
WindowMa nager . A TopComponent is a visual component which is displayed in the Netbeans
IDE. It usually corresponds to a single window, but it may also be a tab in a window. One of the most
important features provided by the Window System is the so -called “Floatin g Windows” feature. A
window can be docked or undocked by using the context menu in order to provide a flexible
position. Due to the fact that a TopComponent exists inside a mode, it is automatically managed
by the WindowManager and it is dockable. By set ting a mode in which a top component is
supposed to be displayed, the window position is defined. NetB eans Platform provides standard
modes, but also self -defined modes can be used. A top component can have several states, such as:
opened, closed, visible, invisible, active or inactive.
Three types of window modes are defined in the NetBeans Platform Window System: editor, view
and sliding. Editor and view are the modes in which the windows used in FreeMarker Editor are
displayed. Editor mode is the only one that cannot be minimized and it takes the biggest part of the
window frame. The window displayed in this mode is responsible for the main features provided by
this application. Selecting the programming language used in the template, loading a template from

Graphical FreeMarker Editor

disk and generating a FTL template are the main functionalities that can be accessed through this
window.
The other two top components used in the FreeMarker Editor are the Output Window and the
Palette Window displayed in the view mode. Output Wind ow is used to notify the user about
succeeded or failed actions done within the application. The Palette Window has the role of
displaying the built -in FreeMarker functions and the existent user -defined functions that
corresponds to the selected programmin g language from the editor window. Moreover, the user can
create a new user -defined function by invoking the appearance of a new window through which the
necessary information can be entered.

Figure 10 – FreeMarker Editor Windows
Any window from this application contains a JavaFX panel which extends the JComponent (a
Swing -based container). All the graphical components used in the application are defined in this
panel.

Graphical FreeMarker Editor

5.2 FreeMarker User Interface
5.2.1 JavaFX Framework
JavaFX is a framework used to design, create, debug, test and deploy cross platform client
applications. It consists of graphics and media packages and it is known as the third GUI framework
defined by Java after Abstract Window Toolkit (AWT) and Swing. It provides all the features of Swing
with a substantially updat ed and improved approach, such as a set of modern GUI controls which
support special effects. It also tolerates the use of CSS and FXML in order to style and build the GUI.

5.2.2 FXML and Scene Builder
FXML is a declarative markup language based on XML. The com ponents of the GUI can be defined in
an FXML file or they can be added interactively using Scene Builder. Scene Builder was designed to
work with the JavaFX ecosystem. It is a tool used to design the application user interface by dragging
and dropping UI c omponents to the work area. In addition, the properties of the elements can be
modified and stylized and they can be linked to the application logic. By adding components onto
the JavaFX scene, the FXML source code which defines the layout is automaticall y generated.

Graphical FreeMarker Editor

Figure 11 – Scene Builder
Then, the FXML files can be ported to an IDE and the developer can add the business logic. All the
components from the .fxml file can be stylized using standard Web technologies such as CSS.
Both JavaFX and Swing can be used in an app lication, therefore a smooth transition from Swing to
JavaFX can be done. Although JavaFX is very similar to Swing, it has many particularities, For
instance, the way in that the components are organized and the relationship between them is
different in co mparison with either Swing or AWT.

5.2.3 JavaFX components
JavaFX is defined as a Java library which contains classes and interfaces written in native Java code.
All the packages in which the JavaFX framework is c ontained begin with the javafx prefix. Some of
the multitudes of packages are : javafx .application , javafx .stage , javafx .scene , and
javafx .scene .layout .

Graphical FreeMarker Editor

A JavaFX application contains at least one Stage and one Scene . A Stage defines a space and the
correspondent Scene defines the components that go in that space. The Stage is a top -level
container called primary stage and it is provided by the runtime system. The Scene is a container
for all the GUI elements and it is attached to the Stage . A component from the scene is a node. It
can have a child nod e and it is called branch node or parent node. If it does not have children, it is a
terminal node and it is named leaf. All the nodes defined in a scene build a scene graph, which
comprises a tree. The root of this tree is a node without parent and it is the top -level node.
As mentioned before, FreeMarker Editor consists of five windows. Every window has a stage with an
attached scene where are defined all the GUI components. Placing elements in a scene is done using
one of the following layout panes: FlowPane , GridPane , BorderPane , AnchorPane . Each
layout inherits the Node class and it is packaged in javafx .scene .layout . The most used
layouts in FreeMarker Editor are the GridPane and the AnchorPane . GridPane is a layout
used to display its components in a flexible grid of row and columns. AnchorPane is similar to the
BorderPane and it allows positioning the children nodes relative to the edges of the pane. In
addition to these panels , an Accordion is used in order to display the build -in functions and the
user -defined functions. The Accordion is a group of TitlePanes that can contain any node.

Figure 12 – Accordion Control

Graphical FreeMarker Editor

Even though the components of the scene are defined in the . fxml file, the parent of the scene has
to be created and passed to the stage. In order to do this, an FXMLLoader is used. Its role is to
load the graphical components into the scene and to return the root javafx .scene .Parent . The
UI elements are instantiated using the information provided in the . fxml files and they are injected
into the controll er mapped to the correspondent . fxml file. The dependency injection is done using
the @FXML annotation. Any public method annotated with @ FXML can play the role of an event
listener. A controller is referenced from the . fxml file in order to enable JavaFX to know which class
to instantiate and where to inject all the GUI components.
Any window displayed in the FreeMarker Editor has a stage with an attached scene whose
components are defined in an . fxml file. Any .fxml file has a reference to a controller wh ere the UI
elements are injected and action listeners are defined for the different actions that can be
performed using the GUI components. The controller is responsible for dealing with the business
logic and to send commands to the view in order to updat e the existing UI elements.

5.3 Business logic implementation
The business logic is implemented using the controllers and other helper classes. The controllers
have to interact with each other, depending on the user input. The interaction is not done direct ly.
An application state object is used. It is the only one that stores information received from all the
windows and it is responsible for notifying the controllers about the changes made on its state .
Depending on the type of the event that a controller receives, it will have to make some local
changes or to send to the view the updated information. The notification system is implemented
using a PropertyChangeSupport which is a utility class that manages a list of listeners and
sends PropertyChangeEvents to them. The ApplicationState object contains a
PropertyChangeSupport object that can notify the listeners when something changes within
the current instance. A PropertyChangeListener is registered for every controller, thus every
modification of the ApplicationState object can be seen in any controller.

Graphical FreeMarker Editor

Each controller needs to communicate with the model in order to send the required information to
the view. The data retrieved from the input files is passed to the controller which processes it and
sends it to th e view. The input files are XMLs which contain lists of functions. Every xml is specific to
a programming language supported by the FreeMarker Editor. In addition to these files, another xml
with built -in FreeM arker functions is provided. The XML s are parsed using a DOM Parser provided by
the javax .parsers package. The data loaded from the input files is mapped to the model and
sent to the controllers. The Document Object Model (DOM) is a standard used for dynamically
accessing and updating the stru cture, the content and the style of a document. It usually proves
useful when the manipulation of HTML or XML files is needed. With the aid of the DOM Parser, an
XML document is presented as a tree -structure, therefore getting, changing, adding or deleting XML
elements becomes easier.
The programming languages supported by the FreeMarker editor are declared in an enum which
also represents a model. Information about the name of the programming language, the input file
where are stored the specific function s and the output directory where the templates will be stored
are provided in this enum .
Another model used within the application is the template model which contains the name of the
template and the content entered by the user. It is used when a user wan ts to create a template by
introducing a valid content and a name for the template. Along with the submitting of the request to
generate the desired template, the controller mapped to the editor view creates an instance of the
template model, which will be written in a file eventually. The validation of the template is done
before enabling the user to perform a request for generating it. With reference to the validation of
the template, a freemarker .template package is used by importing it from the FreeMark er API.

5.4 Design Patterns
In order to have a unique state of the application which coordinates actions across the system, the
Singleton Pattern is used. Within the application, there is only one instance of the
ApplicationState class. It defines the curren t state of the application at any moment and it

Graphical FreeMarker Editor

suffers from changes depending on the user input. The Singleton Pattern is a software design
pattern that ensures the existence of a unique instance of a class, providing a global point of
accessing this inst ance.

Figure 13 – Singleton
Due to the fact that the ApplicationState class follows the Singleton pattern, every controller
will handle the same data and they will send the same information to the view. Therefore, no
discrepancies between the displayed data in different wi ndows will appear. This case can be seen if a
user selects a programming language and then wants to create a new function for the selected
language. The same functions will appear both in the “ Functions Window ” and in the “Create
new function Window ”.
Anot her design pattern used in the implementation of the FreeMarker Editor is the Dependency
Injection. It is widely used in the development of modern software. The advantages of this design
pattern are the loosely coupling of the program components and the po ssibility of testing the
components in isolation. It can be used both on Java server -side software development and in GUI
applications, especially the ones that use JavaFX framework. The latter is also the case of
FreeMarker Editor. The components defined in the .fxml file are injected into the controller
referenced from this file. In order to do this, the @ FXML annotation is used. The component
declared in the . fxml file must have the “ fx:id” specified. The name of the attribute from the
binded controller has to be identical to the fx:id and the type of the attribute must be the same as
the component declared in the . fxml file. The injected elements in the controllers are objects from
the javafx .scene .control package and they contain methods that can modify the properties

Graphical FreeMarker Editor

and the state of the UI components. For instance, when a user wants to insert a function from the
already user -defined functions listed in the Function Window , after clicking on a function, a method
from the controller that takes the name o f the function is called. The controller searches for the
content of the function and displays it in the editor text area by setting its text as being the content
of the function.

Graphical FreeMarker Editor

Chapter 6
Use case

6.1 Features
As presented in the previou s chapters, FreeMarker Editor gives the possibility of creating and
generating a custom FreeMarker template containing blocks of code written in a specific
programming language.
Once the application started, only the FreeMarker built -in functions are disp layed in the Functions
Window. The creation of a new user -defined function is disabled due to the fact that this
functionality is available only when the user selected a programming language to create a specific
language -based template.

Figure 14 – Application Start

Graphical FreeMarker Editor

The sc ope of this tool is to create a template containing FreeMarker specific code mixed with one of
the supported programming languages: C, C#, C++, Java or HTML.
In order to do this, a selection tab whose role is to let the user select the desired programming
language is placed in the Editor Window. By making this selection, the state of the application is
changed and any view that needs to be updated receives a notification from the correspondent
controller.

The communication between controllers is made vi a an ApplicationState object. This fact is
illustrated in the figure 15 . The selection of the programming language is sent to the
FXMLEditorController which update s the state of the application. By modifying the value of
the selec ted language in the ApplicationState , an event is sent to the controllers which act
like listeners. Each controller that knows how to handle this event will send requests for updating
the view from which it is referenced to. Dep ending on the role of each controller , some of them
must send commands to the model in order to receive the data that has to be displayed in the view.
For instance, the list of user -defined functions h as to be shown in the Functions Window . As it
can be seen, even the EditorView , from where the selection was made, is updated due the
notifications received from the ApplicationState object. This is a result of the fact that not Figure 15 – Select language – flow diagram

Graphical FreeMarker Editor

only the selection tab will show another value, but also will the input area be cleared every time the
selection of another language is made.
After the selection of one of the supported progr amming languages, the Functions Window is
updated and the already user -defined functi ons for the selected language are displayed . Moreover,
now the user is allowed to create a new function that can be used afterwards to personalize the
template.
By pressing the “Add new user -defin ed function” from the Functions Window , a new window is
displayed.

Figure 16 – Add function Window
The role of this window is to offer the possibility to create a new function using the built -in
FreeMarker functions or other language -oriented functions that already exists within the
application. By inserting the content and a name, the function can be saved and the changes will be
propagated to the entire application. Not only the pane containi ng functions will be updated, but
also will the declaration and the implementation of the function be saved in the corresponding xml
file.

Graphical FreeMarker Editor

As it can be seen in the image above, by pressing the Save button, the name and the content of the
function are injected in the corresponding controller and the controller has to update the application
state and to use the model in order to save the data in the proper xml file. Depending on the
programming language selected previously, the XML file will be differen t. Every programming
language has its own XML file assigned where the user -defined functions are stored. Due to the fact
that the ApplicationState object suffers modifications, an event will be sent to the controllers
and they will have to notify the view for updates. The status of this act ion will be shown in the
OutputView .
The user can create a function, but he can also delete existing user -defined functions. The build -in
FreeMarker functions cannot be deleted or modified. By pressing the trash icon lo cated next to the
function, a new window is shown. It has the purpose of getting a confirmation from the user that the
selected function should be deleted. Figure 17 – Add Function – flow diagram

Graphical FreeMarker Editor

Figure 18 – Delete Function Window
If the user confirms the deletion of the selected function, the changes will be ap plied both to the
user interface (the function will not appear anymore in the FunctionsWindow ) and to the model.
Otherwise, no changes will be made.

As in the creation of a new function, the controller mapped on the DeleteFunction View
updates the state which will notify the controllers to make the necessary updates to the view.
Moreover, it will use an Util class in order to delete the function from the XML file where it is
stored. Figure 19 – Delete Function flow diagram

Graphical FreeMarker Editor

Not only can the user create a template from scratch, but he also has t he possibility to customize a
template which already exists on his local disk. In order to do this, another dialog is invoked. A dialog
is a top -level window used to take some input from the user, in this case a template file with the .ftl
extension. If th e user selects a template, the input area will be filled with the content of the selected
file.

6.2 Unit tests
In order to test all the functionalities provided by the Graphical FreeMarker Editor, we used JUnit
tests. A unit test can be described as being a piece of code written by a developer that executes a
functionality of the application and asserts a certain behavior or state. The target is to test small
pieces of code, f or example a method or a class. This is the case of the helper classes used for
acce ssing the data from the repositories.
Even though unit test are not recommended for testing the user interface, JavaFX is more flexible
and facilitates unit testing. Using JavaFX to create the user interface results in having a loosely
coupled interface , thus testing the interface becomes feasible.

Graphical FreeMarker Editor

Chapter 7
Conclusions and Future Work

The Graphical FreeMarker Editor aims to ease the generation of source code files by letting the user
to customize his own template. Not only can a new templat e be created, but also an existing one can
be imported and modified in order to obtain the desired result. The application was designed to be
language specific, the programming languages supported by this editor being: C, C#, C++, Java,
HTML.
The possibi lity of creating user -defined function s depending on the programming language selected
proves to be very useful when the same function is used in many templates or in many places within
one template. At the same time, if a function becomes useless, it can be deleted , thus not being
available for a subsequent usage.
A bigger improvement on th e current functionalities offered by this editor would be the
implementation of a mechanism for validating a function when the user wants to create it.
Depending on the selected programming language , a set of rules against which the function should
be verified can be defined. This could be done using the JFlex library.
JFlex is a Java library and it is known as a scanner generator. It is a lexical analyzer generator whi ch
takes as input a set of regular expressions and corresponding actions and generates a lexer . A lexer is
a java program that reads an input, in our case a function, matches the input against the regular
expressions defined and runs the corresponding acti ons. Thus, the correctness of a function can be
verified before storing it and the creation of an invalid function can be avoided. As a consequence,
the template created using valid functions will generate source code files without lexical mistakes.

Graphical FreeMarker Editor

A mor e complex validation can be implemented also in order to verify the correctness of the
template and to display in real time in the output window the errors encountered in the template.
Another feature that can be added to the current functionality is the possibility of importing/
exporting language -based functions. Therefore, they can be stored for a later use on different
machines.
In conclusion, Graphical FreeMarker Editor comes with the basic features for creating a language
specific template that ca n be used in the generation of a source code file. Other functionalities like
parameterized functions, text highlighting, content assist can transform the editor in a professional
tool.

Graphical FreeMarker Editor

BIBLIOGRA PHY:

 David Salter, Mastering NetBeans , Publisher: Packt Publishing Release Date:
August 2015
 Charles Forsythe , Instant FreeMarker Starter, Publisher: Packt Publishing Release
Date: April 2013
 Michael Yawn, J2EE™ and JAX™: Developing Web Applications and Web
Services , Publisher: Prentice Hall Release Date: September 2002
 Heiko Böck, The Definitive Guide to NetBeans™ Platform 7 , Publisher: Apress,
Release Date: December 2011
 Herbert Schildt, Introducing JavaFX 8 Programming, Publisher:McGraw -Hill,
Release Date: June 2015

Graphical FreeMarker Editor

Similar Posts