You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tiles.apache.org by Nicolas LE BAS <ma...@nlebas.net> on 2012/08/29 20:00:58 UTC

Implementing Tiles Request (2/3): Calling an alien API

... Continued from previous message

* Calling an alien API through the Request interface.

  This happens when you are implementing a Renderer or a tag library.
The renderer receives a Request parameter and has to adapt it into
whatever API is required by the underlying technology. The difficult
part is passing the appropriate scopes from the request to the
underlying API.

  First of all, there are two algorithms to do it. The first and most
natural one may not be the best:
{code}
  List<String> scopes = r.getAvailableScopes();
  for (int i = scopes.size() -1; i >= 0; --i) {
     Map<String, Object> scope = r.getContext(scopes.get(i));
     for(Entry<String, Object> attr: scope.entrySet()) {
        // add attribute to the underlying context
     }
  }
{code}
The better alternative is to write an adapter:
{code}
  underlyingContext = new UnderlyingContext() {
    public Object getAttribute(String name) {
      Object result = null;
      List<String> scopes = r.getAvailableScopes();
      for (String scopeName: scopes) {
        Map<String, Object> scope = r.getContext(scopeName);
        result = scope.get(name);
        if(result != null) break;
      }
      return result;
    }
  };
{code}

  Why is it better? The first algorithm accesses all attributes from all
scopes exactly once. The second one only accesses the attributes you
actually use in the template. Even if it may access them several times,
a typical template only does it once, while a typical session may
contain many attributes in a large application (session scoped beans in
spring/JSF, theme-related parameters, ...) that are not used in a
specific template.

  This is especially true when using tiles, because your web page is
divided into many small templates that shall each require a separate
call to the renderer.


  Another, more serious difficulty is when the underlying API is not
providing all the features of the Request. You may want to pass the
original Request "through" the underlying API, in order to retrieve it
later in a taglib, for instance.

  Two schools here: setting an attribute in the underlying API (like
most web-centric technologies: JSP, tomcat, struts, tiles, liferay, ...)
or using a ThreadLocal (like Spring MVC or Spring Security or JSF). I
don't think I've seen a third way, and I really don't know which one is
better.

  The ThreadLocal option has the advantage of being "clean": it does not
invade the namespace of the request. But it requires careful coding with
regard to exception management (use try...finally), or if the renderer
in some way has to call itself (i.e. a freemarker template includes
another freemarker template). The ThreadLocal must be restored to its
initial state upon exit from the renderer, no matter what happened. It
may also become awkward when you're trying to implement some
asynchronous processing (comet-like), Spring has had a hard time with that.

  The attribute option is inherently safe for asynchonous environments,
and easy to code, but needs to be addressed in a different
implementation for each technology even if the name of the attribute is
standard (I'm using Request.class.getName()), and thus a little more
coding is involved, and maybe some kind of code duplication.

  I'd like it if we could choose a single way of doing it here at apache
tiles. What do you think?

TBC...

Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Nicolas LE BAS <ma...@nlebas.net>.
On 12-09-04 03:43 AM, Mck wrote:
>> And/or about implementing
>> a tiles-like framework on the client side? Could you provide a basic
>> example? 
> 
> On the client side you can override how the loading of partials works,
> and implement lambdas yourself in javascript.

> So a mustache template renders either on the server or the client.
> The idea then could be to write two new autotag implementations, one for
> Google Functions (which mustache server uses), and one for javascript.

Autotag is currently focused on java. It could generate javascript code
easily instead of java, but the generated code is only some glue between
the alien API and the actual implementation of the tags (see
tiles-template). I have a hard time thinking how we could compile those
into javascript.

> Whether the javascript implementation is built upon the autotag or is
> just a standalone library mimicing what's needed i'm still unsure of.
> The javascript library will require certain URLs against the server.
> Like give me a template, give me a Definition/AttributeContext, etc. In
> practice we will also want to bundle much of this all into one URL so
> the client-side tiles doesn't become too chatty. Of course this these
> URLs must be implemented by all from scratch even if we can provide good
> example and/or helper classes/servlets.

I think you've been describing the solution in some detail, but the
problem that it solves is still fuzzy in my head.

>From an architect's point of view, the minimal list of inputs of the
Tiles engine is short enough:
- A set of templates
- A set of definitions
- A path
- A set of scoped "Request" attributes

It looks easy enough to send a copy of the templates and definitions to
the browser. Providing the path is no issue.

The set of attributes is another matter, and raises a number of concerns:
- Do we want the whole process to happen in the browser, i.e. the
initial rendering and the reloading of a fragment? Or only the
reloading, and then we need two identical rendering stacks in java and
javascript?
- Can we (technically) expose all the attributes to the browser?
- Do we dare to expose them ? (security concern: how do we handle roles?)
- If we're only reloading a fragment, how do we deal with the attributes
that are cascaded from the enclosing definition?
- If we use attributes from multiple scopes (for instance, session), how
do we keep them up to date? (for instance, what if the user opens
multiple tabs to the webapp?)

We likely can answer the questions above by limiting the use cases. Just
how limited would they be, that is the question...

Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Mck <mc...@apache.org>.
> > Maybe i'm blind
> Wow wow wow...

;)
just a friendly way to ask if i was missing something...


> Could you explain a bit? Is this about replacing a part of the web page
> dynamically after an AJAX call, for instance? 

Yes.

> And/or about implementing
> a tiles-like framework on the client side? Could you provide a basic
> example? 

On the client side you can override how the loading of partials works,
and implement lambdas yourself in javascript.

So a mustache template renders either on the server or the client.
The idea then could be to write two new autotag implementations, one for
Google Functions (which mustache server uses), and one for javascript.

Whether the javascript implementation is built upon the autotag or is
just a standalone library mimicing what's needed i'm still unsure of.
The javascript library will require certain URLs against the server.
Like give me a template, give me a Definition/AttributeContext, etc. In
practice we will also want to bundle much of this all into one URL so
the client-side tiles doesn't become too chatty. Of course this these
URLs must be implemented by all from scratch even if we can provide good
example and/or helper classes/servlets.

~mck


Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Nicolas LE BAS <ma...@nlebas.net>.
On 12-09-01 01:36 AM, Mick Semb Wever wrote:>
> Maybe i'm blind [...] visitor pattern [...] add a context to
MustacheFactory [...]

Wow wow wow... Just because my one-liner explanation is missing an
example doesn't mean you're blind. Forget about MustacheFactory for a
while, the point is to implement the algorithm in PartialCode, because
it doesn't require the addition of anything.

But I agree that lambdas may be the way to go, especially since partials
look awkward and invasive in mustache.js, so let's focus on that.

> Our first attempt is simply to dump all attributes as a
> Map<String,Object> into the request scope under the name "tiles" (in a
> subclass of the MustacheRenderer). But this might not work so smoothly
> client side.

Looks like it's doing the job, though.

But I'm not sure exactly what you're trying to achieve with all that
"client-side" thingies... you're months ahead of me on that subject.

Could you explain a bit? Is this about replacing a part of the web page
dynamically after an AJAX call, for instance? And/or about implementing
a tiles-like framework on the client side? Could you provide a basic
example?


Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Mick Semb Wever <mc...@apache.org>.
> > It's some extra work at coding, but it doesn't interfere with the
> > loading of the initial template, so the testing and debugging should be
> > easier. 
> 
> It sounds about right yes. I'll take a closer look at
> DeferringMustacheFactory.

Maybe i'm blind but i can't see any satisfactory solution here.
The visitor pattern provides the "deferring" functionality, and that is
only for the rendering of the partial, not the load/compile of it.

What we are trying to do is add a context to MustacheFactory where one
previously doesn't exist, a hint that lambdas are better suited.
It would be better if the definition name was also explicit in the
partial, eg {{>definitionName/attributeName}} but in practice often you
would want definitionName to be relative, ie the current definition.


> > We're still working our way through things (it's important that
> > including partials by tiles attribute names works both client and server
> > side), it may well be that we use lambdas instead of partials... and
> > that leads to implementing an autotag implementation against lambdas.
> 
> I was thinking of implementing something (a DefinitionRenderer?) that
> evaluates all the definition attributes first, and delivers the results
> as request attributes (through a RequestWrapper, and possibly an extra
> scope "definition") before calling the definition template.

Indeed we're working on that problem.
AttributeContext provides what we want.

Our first attempt is simply to dump all attributes as a
Map<String,Object> into the request scope under the name "tiles" (in a
subclass of the MustacheRenderer). But this might not work so smoothly
client side.

Which brings us back to lambdas, as they might be easier to implement
with one javascript library than to provide examples on how to make the
client-side stuff compatible…
(lambdas weren't our first approach as they were in mustache java 0.6).

Either way the server must provide a url that returns a json object
holding all tiles attributes. But that is easy enough to demonstrate how
to do.

~mck


-- 
"A mind that has been stretched will never return to its original
dimension." Albert Einstein 

| http://github.com/finn-no | http://tech.finn.no |

Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Nicolas LE BAS <ma...@nlebas.net>.
On 12-08-31 10:47 AM, Mick Semb Wever wrote:
> We're still working our way through things (it's important that
> including partials by tiles attribute names works both client and server
> side), it may well be that we use lambdas instead of partials... and
> that leads to implementing an autotag implementation against lambdas.

I was thinking of implementing something (a DefinitionRenderer?) that
evaluates all the definition attributes first, and delivers the results
as request attributes (through a RequestWrapper, and possibly an extra
scope "definition") before calling the definition template.

I think that would cover the "lambda" scenario for mustache (on the
server side), and it would be useful if we want to add caches and
decorators into the tiles framework, too. And we've had users calling
for evaluating the attributes in a specific order.

> But regardless of the partials we do want a way where resource loading
> goes through the application context, and we also don't create a very
> specific set of mustache classes that can only be used. But this relates
> back to your discussion in (3/3) where often only one use-case can be
> supported.

that part looks easy enough to me:

public class ContextMustacheFactory extends DefaultMustacheFactory {
   private ApplicationContext context;
   public ContextMustacheFactory(ApplicationContext context) {
     this.context = context;
   }

  @Override
  public Reader getReader(String resourceName) {
    // TODO check for NPEs and actual resourceName syntax
    return new BufferedReader(new
InputStreamReader(context.getResource(resourceName).getInputStream(),
Charset.forName("utf-8")));
  }
}

Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Mick Semb Wever <mc...@apache.org>.
On Fri, 2012-08-31 at 10:14 -0400, Nicolas LE BAS wrote:
> It's some extra work at coding, but it doesn't interfere with the
> loading of the initial template, so the testing and debugging should be
> easier. 

It sounds about right yes. I'll take a closer look at
DeferringMustacheFactory.

We're still working our way through things (it's important that
including partials by tiles attribute names works both client and server
side), it may well be that we use lambdas instead of partials... and
that leads to implementing an autotag implementation against lambdas.

But regardless of the partials we do want a way where resource loading
goes through the application context, and we also don't create a very
specific set of mustache classes that can only be used. But this relates
back to your discussion in (3/3) where often only one use-case can be
supported.

~mck

-- 
“The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself. Therefore, all
progress depends on the unreasonable man.” - George Bernard Shaw 

| http://github.com/finn-no | http://tech.finn.no |

Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Nicolas LE BAS <ma...@nlebas.net>.
On 12-08-31 02:53 AM, Mck wrote:
> It's actually the resource loading functionality that i'm after in an
> override of DefaultMustacheFactory.getReader(String path).

The resource loading itself goes through ApplicationContext, and is
unrelated to the Request instance or to the tiles-framework in any way.

> This is tiles-framework code, where a path can be interpretted as a
> tiles attribute name and so from the request i can obtain the
> attributeContext and then do the resource loading.

So you want to map {{>body}} into <tiles:insertAttribute
name="body"/>... while MustacheFactory has no knowledge of any
Request-related object (which sounds normal since DefaultMustacheFactory
is basically the template compiler, not the template itself).

I suppose the way to do it as intented by the author of mustache is to
create a new subclass of PartialCode in a subclass of
DefaultMustacheVisitor like they do in DeferringMustacheFactory. There
you would have access to everything.
It's some extra work at coding, but it doesn't interfere with the
loading of the initial template, so the testing and debugging should be
easier.

Hope this helps,
Nick

Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Mck <mc...@apache.org>.
On Thu, 2012-08-30 at 15:20 -0400, Nicolas LE BAS wrote:
> > My preference is for the first approach, and particularly standardising
> > on using Request.class.getName() as the key in foreign contexts.
> > 
> > But there often isn't a foreign context that is loose enough to put a
> > request object into. I would rather have taken the first approach in
> > tiles-request-mustache but it doesn't seem possible. Using a ThreadLocal
> > should be a frowned upon last-available option to use. 
> 
> How about:
>     protected Map<String,Object> buildScope(Request request) {
>         [...retrieve attributes...]
>         scope.put(Request.class.getName(), request);
>         return scope;
>     }
> Wouldn't it fit the bill? 

You're quite right – i didn't do a decent job of explaining what's
actually required.

It's actually the resource loading functionality that i'm after in an
override of DefaultMustacheFactory.getReader(String path).

This is tiles-framework code, where a path can be interpretted as a
tiles attribute name and so from the request i can obtain the
attributeContext and then do the resource loading.

I could have done a brand new implementation of MustacheFactory to make
easier access to the servlet Request object, but at these stage i'd
rather say close to the default classes mustache comes with.

But maybe 
 scope.put(Request.class.getName(), request);
should also be done here and documented as preferred?

~mck


-- 
"This above all: to thine own self be true. It must follow that you
cannot then be false to any man." Shakespeare 

| http://github.com/finn-no | http://tech.finn.no |



Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Nicolas LE BAS <ma...@nlebas.net>.
On 12-08-30 12:59 PM, Mick Semb Wever wrote:
> My preference is for the first approach, and particularly standardising
> on using Request.class.getName() as the key in foreign contexts.
> 
> But there often isn't a foreign context that is loose enough to put a
> request object into. I would rather have taken the first approach in
> tiles-request-mustache but it doesn't seem possible. Using a ThreadLocal
> should be a frowned upon last-available option to use. 

How about:
    protected Map<String,Object> buildScope(Request request) {
        [...retrieve attributes...]
        scope.put(Request.class.getName(), request);
        return scope;
    }
Wouldn't it fit the bill?

Hope this helps.
Nick

Re: Implementing Tiles Request (2/3): Calling an alien API

Posted by Mick Semb Wever <mc...@apache.org>.
> The renderer receives a Request parameter and has to adapt it into
> whatever API is required by the underlying technology. The difficult
> part is passing the appropriate scopes from the request to the
> underlying API.
>  [snip]
>   Which is it better? 

My preference is to leave this decision up to each implementation.
Accessing everything in all scopes for most implementations has no
noticeable cost. For implementation that do, or for any other valid
reason, they can/should go for the UnderlyingContext approach.

>   Two schools here: setting an attribute in the underlying API (like
> most web-centric technologies: JSP, tomcat, struts, tiles, liferay, ...)
> or using a ThreadLocal (like Spring MVC or Spring Security or JSF). I
> don't think I've seen a third way, and I really don't know which one is
> better.
>   [snip]
>   I'd like it if we could choose a single way of doing it here at apache
> tiles. What do you think? 

My preference is for the first approach, and particularly standardising
on using Request.class.getName() as the key in foreign contexts.

But there often isn't a foreign context that is loose enough to put a
request object into. I would rather have taken the first approach in
tiles-request-mustache but it doesn't seem possible. Using a ThreadLocal
should be a frowned upon last-available option to use. 

( i didn't use try…finally as the threadLocal.remove() is but
house-cleaning )

~mck


-- 
"All stable processes we shall predict. All unstable processes we shall
control." John von Neumann 

| http://github.com/finn-no | http://tech.finn.no |