Re: FileTemplateLoader doesnt close reader ?

Daniel Dekany <[email protected]> Tue, 12 Mar 2013 21:30:17 +0100
Newsgroups gmane.comp.web.freemarker.user
Message-ID <[email protected]>
Tuesday, March 12, 2013, 8:20:18 AM, Albert Kam wrote:

> I took a peek at FileTemplateLoader.java and notices that the
> closeTemplateSource() is empty method.
> Is it okay not to close the Reader returned from getReader() ?

The Reader is closed by whoever has called getReader() by calling
java.io.Reader.close(), not with a TemplateLoader method. The
closeTemplateSource() just closes the "template source", which in the
case of FileTemplateLoader is a File, and hence there's nothing to
close in it.

> I am asking this because i am trying to mimic the best practice
> when creating a custom TemplateLoader.
>
> In my case, when following the instruction to auto-escape in here : 
> http://watchitlater.com/blog/2011/10/default-html-escape-using-freemarker/ :
>
> - I found out that closing the reader returns an empty page after
> the process. Commenting the IOUtils.closeQuietly() solves the empty page problem.

That sounds impossible. By the time IOUtils.closeQuietly() is called,
the StringReader and the String it reads is already done. Maybe
IOUtils.closeQuietly() throws an exception that's improperly handled,
gibing an empty page?

> - So i thought maybe i should close the reader (maybe through a
> ThreadLocal storing the reader) in the closeTemplateSource()

You should not close the Reader that you return to the caller. But in
this case you have a Reader that you don't return to the caller or to
anybody, so of course you have to close it yourself, but that you
should do right where it's done on that blog.

> - So i peeked the FileTemplateLoader for an example, and thus this post to clarify.
>
> Please share your thoughts.

That implementation is not very good, because:

- It can't handle the case when the template already has an #ftl
  header

- That it pre-loads the template, instead of creating a wrapping
  Reader that appends and prepends what's needed right in the
  character stream. Although it's not a big deal in practice, it's not
  very nice.

You may look into the source code of FMPP, and there
Engine.wrapReader. (I was substantially younger when I wrote that, but
let's hope it's OK... :) )

> Thank you,
> Albert Kam

-- 
Best regards,
 Daniel Dekany


------------------------------------------------------------------------------
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_d2d_mar