Choosing the right template engine - java

since today - I always used simple JSP Tags and JSTL which works but now I'm looking for a little bit more features and maybe more usability.
With googling I've found Freemaker, Velocity and Tiles which seem to be very famous. Does someone of you has some further experiences with some of these and can give me a short brief about it.
Or are there other frameworks which are worth to look into?

In my opinion, with templating engines, less is more. That is, you want fewer features, not more, to promote re-usability of the templates.
One templating engine that provides only the functionality that a templating engine strictly needs, and no more is StringTemplate. It's not something I've personally used in a production system, but am planning to the next opportunity I get.
If you're interested in learning more on the subject/philosophy, please read Enforcing Strict Model-View Separation in Templating Engines by the creator of StringTemplate.
If you read only one section in that paper, read chapter 7, which includes the following rules I try to enforce (even when using something like JSP, that's arguably "too powerful" an engine):
the view cannot modify the model either by directly altering model
data objects or by invoking methods on
the model that cause side-effects.
That is, a template can access data
from the model and invoke methods, but
such references must be side-effect
free. This rule arises partially
because data references must be
order-insensitive. See Section 7.1.
the view cannot perform computations upon dependent data
values because the computations may
change in the future and they should
be neatly encapsulated in the model in
any case. For example, the view cannot
compute book sale prices as
“$price*.90”. To be independent of the
model, the view cannot make
assumptions about the meaning of data.
the view cannot compare dependent data values, but can test the
properties of data such as
presence/absence or length of a
multi-valued data value. Tests like
$bloodPressure<120 must be moved to
the model as doctors like to keep
reduc- ing the max systolic pressure
on us. Expressions in the view must be
replaced with a test for presence of a
value simulat- ing a boolean such as
$bloodPressureOk!=null Template output
can be conditional on model data and
com- putations, the conditional just
has to be computed in the model. Even
simple tests that make negative values
red should be computed in the model;
the right level of abstraction is usu-
ally something higher level such as
“department x is losing money.”
the view cannot make data type assumptions. Some type assumptions are
obvious when the view assumes a data
value is a date, for example, but more
subtle type assumptions ap- pear: If a
template assumes $userID is an
integer, the pro- grammer cannot
change this value to be a non-numeric
in the model without breaking the
template. This rule forbids array
indexing such as colorCode[$topic] and
$name[$ID] The view further cannot
call methods with arguments be- cause
(statically or dynamically) there is
an assumed argu- ment type, unless one
could guarantee the model method
merely treated them as objects.
Besides graphics designers are not
programmers; expecting them to invoke
methods and know what to pass is
unrealistic.
data from the model must not contain display or layout information.
The model cannot pass any display
informa- tion to the view disguised as
data values. This includes not passing
the name of a template to apply to
other data values.

Velocity is the old man of java template engines, and it shows it. The design is a bit crusty (lots of static methods), and it's a bit limited and not very extensible. It works perfectly well, though, and integrates well with Spring MVC.
Freemarker started where Velocity left off. It's got a lot more functionality, it's very extensible, it integrates very nicely with Spring MVC. On the downside, I find the template expression language to be highly peculiar.
Tiles I have no experience with, although any association with Struts makes me suspicious.
When it comes to view rendering, I still use JSP and JSTL. For all their flaws, they still give the best range of options, in my opinion.
When it comes to rendering dynamic textual documents outside the scope of the web layer (e.g. SMS or email templates), Freemarker wins hands down, for me.

If you like the Scala programming language you might like Scalate as it allows you to use powerful Scala expressions instead of the limited JSP/JSF/JSTL EL expression language - while being completely statically typed so that templates are checked at edit/compile time for errors.
The Scaml templates in Scalate let you write really DRY templates which are particularly good for XML/HTML (Rails fans tend to love Haml and Scaml is the Scala port of Haml) - though if you're used to JSP you'd probably be better off starting with Ssp templates in Scalate which are JSP-like.

I have worked with both Velocity and FreeMarker along with Spring MVC. Although Velocity is really light-weight and easy-to-use, it is somehow limited. I prefer FreeMarker for web page rendering because of large existing macro libraries and JSP inclusion support.
I also recommend SiteMesh for web page decoration to avoid a template file mixing content with decoration.
So, if you do not need the fantasy of AJAX pages, the result is: Freemarker+SiteMesh+Spring MVC. But if you are wondering whether to use AJAX or not, I recommend you to take a look at GWT showcase.

Related

DRY Principle: Angular2/Typescript and Java back end object duplication

I'm a Java developer but I've recently begun learning Angular2/Typescript. I've worked with Angular 1.x before so I'm not a complete noob :)
While working through a POC with a RESTful Spring Boot back end and Angular2 front end I noticed myself duplicating model objects on both sides a lot e.g.
Java Object
public class Car {
private Double numSeats;
private Double numDoors;
.....
}
Now in interest of Typescript and being strongly typed I'd create a similar object within my front end project:
export interface PersonalDetailsVO {
numSeats : number;
numDoors : number;
}
I'm duplicating the work and constantly violating the DRY (Don't Repeat Yourself) principle here.
I'm wondering is there a better way of going about this. I was thinking about code generation tools like jSweet but interested to hear if anyone else has come across the same issue and how they approached it.
There are two schools of thought on whether this is a violation of the DRY principle. If you're really, really sure that there's a natural mapping you would always apply to bind json in each language, then you could say that it is duplicate work; which is (at least part of) the thinking behind IDL-type languages in technologies like CORBA (but I'm showing my age).
OTOH maybe each system (the server, the client, an alternate client if anyone were to write one) should be free to independently define the internal representations of objects that is best suited to that system (given its language, what it plans to do, etc.).
In your example, the typescript certainly doesn't contain all of the information needed to define the Java "equivalent". ('number' could map to a lot of things; and the typescript says nothing about access modifiers...) Of course you can narrow that down by adopting conventions, but my point is it's not self-evident that there'd be a 1-to-1 mapping.
Maybe one language handles references more gracefully than another. Maybe one can't deal with circular references but the other can. Maybe one has reason to prefer a more flat view of the object. Maybe a lot of things.
All of that said, it certainly is true that if you modify the json structure of an object, and you're maintaining each system's internal representation independently, then you likely have to make code changes in multiple places to accommodate that single underlying change. And pragmatically, if that can be avoided it's a good thing.
So if you can come up with a code generator that processes the more expressive language's representation to create a representation for the less expressive language, and maybe at least use that by default, you may find it's not a bad thing for your project.

Does the use of ObservableList in JavaFX go against Model-View-Controller separation?

I am attempting a study of JavaFX because I want to use it as the GUI of my program. My question is essentially a conceptual one:
To date my program is mostly the "Model" part of the MVC pattern; that is, almost all of my code is the OO-representation of abstractions in the sense of classes, and all of that code is logical code.
Since I do not want to be the only user of my program, I want to add the "View" part of MVC so that people can easily use and manipulate the "Model" part of my program. For this, I want to use JavaFX.
In my "Model" classes I obviously use various Lists, Maps, and other classes from the Java Collections API. In order to let the users of my program manipulate these underlying Lists and Maps I want to use the Observable(List/Map) interfaces in JavaFX.
A concrete example to bring clarity to the situation:
Let's say that I have a MachineMonitor class that every 3 minutes checks certain properties of a Machine, such as if the connection is still good, the speed that the gears are turning, etc. If certain inequalities are met (say that the speed of the gears has fallen to a rate of 1 turn/sec) the MachineMonitor fires a RestartMachineEvent.
Currently I use an ArrayList<MachineMonitor> to keep track of all of the individual MachineMonitor's. Now extending to the "View" part of MVC, I want the User to be able to manipulate a TableView that displays the list of MachineMonitors so that they can, for instance, create and remove new MachineMonitor's to monitor various Machines.
So that I can keep track of what the user of my program wants to do (say, create a MachineMonitor for Machine #5 that checks to see if the turn/sec of the gears falls below 0.5) I use an ObservableList<MachineMonitor> as the underlying List for the TableView.
The easiest way to link the "Model" and "View" of my program would simply be to change the "Model" class to have an ObservableList<MachineMonitor> and not an ArrayList<MachineMonitor> but (getting to the topic of the question) I feel that this is very messy because it mixes "Model" and "View" code.
A naïve approach would be to use an ObservableList<MachineMonitor> for the TableView and retain the use of my ArrayList<MachineMonitor>. However, changes made to the ObservableList<MachineMonitor> do not affect the underlying List as per the JavaFX specifications.
Given this, is the best way to solve this conundrum to make a ChangeListener for the ObservableList<MachineMonitor> that "propagates" the changes made to the ObservableList<MachineMonitor> to the underlying "Model" ArrayList<MachineMonitor>? Perhaps put this in a class called MachineMonitorController?
This ad-hoc solution seems very messy and non-ideal.
My question is: What is the best way to retain nearly complete separation between the "Model" and "View" in this scenario?
Briefly, I don't think use of ObservableList breaks the MVC contract.
The rest, you may read or not as you wish, as it is quite annoyingly long.
Architectural Pattern Background
Observables are useful in MVC style architectures because they provide a way of feeding data back and forth between the MVC components through loose couplings where the model and view classes don't need to refer directly to each other, but can instead work with some shared data model which communicates data flow. It's not a coincidence that the Observable pattern and the MVC style architecture concept both originated around the same time at Xerox PARC - the things are linked.
As noted in Martin Fowler's GUI architectures, there are numerous different approaches to building GUIs. MVC is just one of these, kind of the granddaddy of them all. It is nice to understand MVC well (it is often misunderstood) and MVC concepts are applicable in many places. For your application you should use the system which feels best for you rather than rigidly following a given pattern (unless you are using a particular framework which enforces a given pattern) and also be open to adopting different patterns within an application rather than trying to shoehorn everything into a single conceptual framework.
Java Beans are a fundamental part of almost all Java programs. Though traditionally often only used in client apps, the observer pattern, through PropertyChangeListeners, has been, for good reason, a part of the Java Bean specification since it was created. The observable and binding elements of JavaFX are a rework of that earlier work, learning from it to build something that is both more convenient to work with and easier to understand. Perhaps, if the JavaFX observable and binding elements had existed ten or twelve years ago as part of the JDK, such concepts would be more generally used in a wider variety of libraries and frameworks than a couple of pure GUI frameworks.
Advice
I suggest considering the MVVM model and other GUI architectures.
If you want a dead-easy framework which follows a model, view, presenter style, definitely give afterburner.fx a spin.
I think the correct choice of architecture depends on your application, your experience and the size and complexity of the problems you are trying to solve. For instance, if you have a distributed system, then you could follow REST principles rather than (or in addition to) MVC. Whichever you choose, the architecture should aid you in solving the problem at hand (and possibly future problems) and not the converse. Over-architecting a solution is a common trap and is very easy to do, so try to avoid it.
Caveat
One caveat to consider is that observables necessarily work via side-effects which can be difficult to reason about and can be antithetical to the concept of isolation. JavaFX features some good tools, such as ReadOnlyObjectWrapper and ReadOnlyListWrapper, to help limit the impact (damage control if you like) on observables so they don't run amok in your system. Use such tools (and immutable objects) with reckless abandon.
Learn from Examples
For a simple JavaFX application which is built using observables, refer to tic-tac-toe.
For a good way to structure a large and complex JavaFX application with FXML based components, refer to the source code for SceneBuilder and SceneBuilderKit. The source code is available in the JavaFX mercurial source tree, just check it out and start learning.
Read up on the JavaFX UI controls architecture. Examine the JavaFX controls source code (e.g. Button and ButtonSkin or ListView and ListViewSkin) to see how concepts such as MVC can be applied using JavaFX structures. Based on that learning, try creating some of your own custom controls using the architecture that the JavaFX controls framework provides. Often, when you are building your own application you don't need to create your own controls (at least ones which derive form JavaFX Control). The JavaFX Controls architecture is specially crafted to support building libraries of reusable controls, so it is not necessarily generally suitable for all purposes; instead it provides a concrete demonstration of one proven way to get certain things done. Adopting and adapting proven solutions goes a long way to ensuring you don't reinvent stuff needlessly and allows you to build on a solid base and learn from the trials of others.
Regarding your Concrete Example
I advise you to go with:
The easiest way to link the "Model" and "View" of my program would simply be to change the "Model" class to have an ObservableList and not an ArrayList
Maybe use a ReadOnlyListWrapper to expose the ObservableList from the MachineMonitor to the outside world, so that nothing can modify it unduly.
Setup some other structure which encapsulates the view (for example a ControlPanel and ControlPanelSkin) and provide it a reference to the read only observable list of MachineMonitors. The ControlPanelSkin can encapsulate a TableView, a graph or whatever visual knobs and widgets you want to use for the user to monitor the machines.
Using such a structure effectively isolates your view from the model. The model really doesn't know anything about the UI at all and ControlPanelSkin implementation could be changed out to a completely different visual representation or technology without changing the core MachineMonitor system at all.
The above just outlines a general approach, you'll need to tweak it for your specific example.
I disagree that using an ObservableList in your "model" class violates MVC separation. An ObservableList is purely data representation; it is part of the model and not part of the view. I (and others) use JavaFX properties and collections in model representations in all tiers of my applications. Among other things in there, I point out how I use JavaFX properties that are (or can be, at least) bound to JSF. (I should mention that not everyone agrees with the approach of using FX properties on the server side; however I don't really see any way to make the argument that they are somehow part of the view.)
Also, if you do
List<MachineMonitor> myNonObservableList = ... ;
ObservableList<MachineMonitor> myObservableList = FXCollections.observableList(myNonObservableList);
myObservableList.add(new MachineMonitor());
the observable list is backed by the non-observable list, so the change occurs in myNonObservableList too. So you can use this approach if you prefer.

using jsp/taglibs versus template engine

I've done some php dev and the big trend in this language is using things like smarty or other template engine.
It usually roughly runs as follows :
load the template as a regular string,
look for its {tags}
replace each {tag} with the result of some code.
cache page with input parameters
render resulting page.
(sometimes add some OO principles such as template becomes an object...)
When I look at jsp, I see usage of scriplets, taglibs with complicated things like
<%# taglib uri="/tags/struts-logic" prefix="logic" %>
<%# page import="ghhghjjgj"%>
then :
<logic:if>some html </logic:if>
or worse :
<%= if (blabal) {%>
some html
<%}else ...%>
and so forth.
Okay, tiles enables me to glue together some jsp pages together which is really handy (like the include in php, sort of)
It seems to me that the php approach is much better in the way that :
It totally separates gui and model processing.
-It's easier to change the pages content when you are working on the behind part,
you're in a real java class with no complicated stuff like % # <%=. (who said
code behind ala C# ;) ?)
The C# approah is very interesting as well but I just want to adress the template part in my question and not start any C# Vs Java Troll war.
I do not also want to say php is better.
I just want to know why there is not a well installed templating engine in java and why we still use scriplets/taglibs.
So I guess I must be missing something.
Can some Java EE Web expert show me the flaws of my reasoning?
J2EE became Java EE a long time ago. Drop the "2".
No one should use scriptlets. It's 1999 technology. If you're seeing it in books, it's because the books are old. There's not a lot of good reasons for writing another servlet/JSP book now.
Custom tag libraries have fallen out of favor. JSTL is the standard. It's unlikely that you'll need more than that.
Templating is common - have a look at Velocity. One project I'm working on uses it exclusively for streaming HTML to the browser.
There are many template engines for Java, Velocity, for example. JSP compiles to Java bytecode. It allows for very fast execution. Whether this factor is important for you or not, depends on your task, for most web sites template processing won't be an issue.
I don't really understand the implications why it's great to write
{if blabal} some html{/if}
and not so good to write
<logic:if test="blabal"> some html</logic:if>
and it's worse to write
<% if (blabal) { %> some html <% } %>
but it's good to write
#if ( blabal )
some html
#end
I personally like to write my logic in java.
Type save
I know the syntax
However, to me it's not a matter of syntax wheter mixing template code and logic is a good or a bad thing. Thus I prefer Snippetory. I gets the logic out of the template while keeping the responsibility for consistence (ecaping stuff and the like), the look (formatting...) and internationalization in the template. The binding logic gets testable, easy to organize and reuse. The data model can be used as is and there's no need to translate it into a model sufficient for some kind of alien technology. In this case the template is rather a kind of a model where you copy the necessary data into rather than a process that self-services from a context.
Now, in this case we'll need to peaces of software to express the same thing, as it always happens as one uses the principles of separation of concerns to get software more maintainable.
Template:
<t:named-region> some html with a {v:value} </t:named-region>
Logic:
if (blabal) {
template.get("named-region").set("value", value).render();
}
Now as we look at this, it's quite a bit more code. Again this is typical to serparation of concerns. However, a quick look on the steps might make sense:
Access to the region is aquired.
Data is bound to the template. This happens fine grained, just like filling in a from.
The completed form is bound to the output.
The last step seems kind of dispenseable. I fill data to it, so it's clear I want to use it. But you have to be aware, render()is a short cut for render(template, "named-region"). So it's a discription how it is used. Thanks to this mechanism you can easily combine the building blocks of one file or even several files to an output of your choise. This leads to an surprisingly convenient re-use of those blocks.
And it gains me focus: When I'm fighting to get html, css and javaScript right I don't have to deal with 'how is the exact path to access the data?' or 'what are the exact case this button is displayed?'. It's just about 'there is logic, so it gets a name'. Very simple, very clean.
Of course there are some other engines this support for separation of template and logic like jByte (I used it for a while) or JTPL just to name a view. However, all of them seem to lack some functionality though, I decided to write Snippetory.

Decorating a multi-client webapp

I have a web-app in Java, Spring, Struts 2 and Hibernate, that servers multiple clients. Each client with multiple users. To create a personal feel for each client, i would like to customize the header for each client.
I'm using sitemesh as decorator, and am looking for tips or examples or someone who can point me in the right direction as to how to acomplish this in the best practice.
What would you think? Should i just code it direct in the header.jsp? Extracting the info about the logged in user and from that create a custom header by code? Or is there a more clever solution out there?
Thanks!
Update:
To further clearify what i want:
Different properties-files for each client is not an option. We are looking at potentionally hundreds of clients. It needs to be database-driven. But thats the easy part. There is no problem storing the information in db and extracting it when needed.
What im trying to figure out is if there is some sort of standard way of doing this. Some sort of filter or Action that is run before the sitemesh decorator that will provide the decorator with the correct info?
Struts2 provides application scope, for variables which are global to the application.
Load all the customer specific strings into #application scope (I would use spring to do this when the application starts up). From there referencing the strings would be pretty obvious: #application.greeting I don't like the idea of using an interceptor because there is nothing to intercept. I would say for what you are doing application scope is the perfect place. If it is a single client system I can see no reason why anything would be stored in application scope.
Aside: Tiles uses a different template paradigm than site mesh, and they have slightly different purposes. As such the two can be complimentary. Tiles relying on XML definitions can have it's definitions stored in a DB and is definitely less computationally intensive, however where there is interplay between different UI components... or disparate elements appearing on the page you need to use sitemesh. So for basic template needs tiles does everything and is quite easy to understand but say you wanted to make add a certain widget in the middle of the page which relies on JS which needs to be added to the header it would be tricky to do this in Tiles (although the obvious solution is to just roll the JS functionality into one JS file for all possible uses in a particular part of the site).
Asside 2: By using a view technology such as velocity or freemarker in conjunction with tiles it is conceivable to move the entire view layer into a database. I just thought I would mention that as for some maintenance issues that could be extremely beneficial.
Sitemesh makes it's decisions about what decoration to use based upon the requested URL string, so unless you have a reference to the client in every url - either as part of the main url string or as a known parameter, then Sitemesh out of the box is not going to help.
This leaves a few possibilities to achieve what you want;
1) Write a filter that runs before Sitemesh that adds, for example, "&clientId="xx" to every incoming request.
2) Dive into the source code for Sitemesh & look for where Sitemesh finally makes it's decision about which decorators to use and override it. I've never tried this so I don't know how practical this might be.
3) Make the style sheet definition in your jsp pages an OGNL expression and provide that information in a base action class that all your actions extend. In this way you end up with (potentially) a different CSS file for each client and you provide your customisation via CSS.
Hope that this helps.

Why do people use Velocity and/or NVelocity?

Over the past year I have heard alot about Velocity and NVelocity. Reading their documentation and doing searches on the net hasn't given me the answers I was looking for.
In what situation would I use this library in my development? What problem does it solve that didn't already have a solution?
Since the dawn of web apps, people started to think about separation of concerns in many applications, including web applications. The challenge is to separate what is view code from what is business code, or logic code. When jsps first arrived, many people where coding lots of logic in jsps directly (stuff like db access and other), breaking the basic principle of separation of concerns (jsps should be responsible for the presentation, not for the logic).
Velocity, Freemarker and others are templating engines that allows the separation of UI logic and business logic, thus facilitating changes in the presentation while minimizing the changes on the business side. These template engines have facilities for doing common UI tasks such as showing a block of html if some condition holds true, or iterating over a list while maintaining logic code outside of the view. This is fundamental for maintaining a complex application in the long run.
I think it's important to point out that compared to JSP/ASP.NET as a templating mechanisim, Velocity/NVelocity really 'ENFORCE' the seperation of concern.
With <% .. %> of JSP/ASP.NET, any Java/.NET code is allowed. Which is why sometimes you do see business logic code in these files.
With Velocity/NVelocity you can't embed long series of code. Instead you are really forced to pass in computed values, which Velocity/NVelocity picks up and displays them according to the way the template is designed.
Another point would be that they can work outside of a Web Container environment (at least Velocity can AFAIK). Imagine that you had designed a report template with JSP/ASP.NET. It works fine from the web. And then suddenly there is a change request to have it be done from a Desktop application. Rather than embed a Web Container in it, you could initialize Velocity/NVelocity, compute the values, then render the template.
It's a template engine. If you have a lot of static text with variable content mixed in, templates are a great way to reduce the amount of work you have to do.
It's a whole lot better than String.Format or loads of concatenation because it's not as repetitive or error prone, and far more maintainable since you can figure out exactly what your template does just by looking at it.
We use templating to generate configuration files for production, UAT, system test, contingency systems etc.
We have a master Spring configuration file into which we inject a property file. We have a master property file that is parsed by Velocity and this allows us to keep all system settings in one file.
As a bonus, for the ones interested, I recommend reading the following:
http://www.artima.com/lejava/articles/stringtemplate.html
http://www.cs.usfca.edu/~parrt/papers/ST.pdf
These are links about StringTemplate, a templating engine by Terence Parr who wrote antlr, a parser that's been used everywhere (ex: hibernate uses antlr).
1 - Velocity engine actually merges the real time data with the xyz.vm file which holds the static information 2 - The vm file uses Velocity Template Language(VTL)
(It can iterate over the java iterable java objects placed on the context , can call the methods accessible by the objects placed on the context) Situations to use Velocity - Brings the power of java to html not only to html 1-When you have to generate report mails often with varying data and constant style.(foreach support)
2-When you want to merge a real time data with dummy place-Holder in deeply nested contents
3-When you want to decide style information based on the value of the data (if else support)and many more
Refer - http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html

Categories