Technology


26
Dec 11

Using dust.js with Scala SBT

If you’ve been living under a rock for the past few weeks you might have missed LinkedIn bloging about their usage of dust.js. This idea of client-side templating is certainly a very interesting one, and something that is in all likelihood very useful for many large-scale applications currently in production. dust.js is quite nice in that it has no dependencies on any javascript library such as JQuery or YUI. This is really rather handy is it means no prescription on your style of implementation.

However, whilst the dust.js documentation has a wide range of examples demonstrating how to use the templating engine, what it does not have is any examples of how one might actually wrap it up and use it. So, with that I wanted to just write up a quick post to explain some of the things that might not be immediately obvious. Before getting to the meat of the article, it’s worth bearing in mind some terminology:

  • Template: The source dust.js template
  • Compiled template: A pre-compiled version of the template; essentially some generated JavaScript that is created at build-time (it’s also possible to create the JavaScript at runtime, but this is heavily discouraged)
  • Context: Each template can only be rendered with a context. More regularly we can think of this as the data that populates the template variables

In short, the developers writes a source template which is then compiled to JavaScript at build time and then rendered at runtime with a given context; which is likely a dynamic JSON payload.

When I first go going with dust.js I was unsure how to handle this build-time compilation. Frankly, the support for everything that isn’t JavaScript or Node was (and is still mostly) non-existent. This was problematic as I certainly didn’t want to be compiling templates on each and every request for a given HTML page. With that, I set about writing an SBT plugin for dust.js template compilation. This then allows you to have SBT build the dust.js templates into JavaScript that you can simply reference directly from your HTML (more on this later). The plugin itself takes templates it finds in src/main/dust and compiles them to the resource managed target whenever you invoke the dust task from the SBT shell. It’s also super easy to redirect the compilation output to the webapp directory during development so that you can simply use the local Jetty server to tryout your app:

(resourceManaged in (Compile, DustKeys.dust)) <<= (
  sourceDirectory in Compile){
    _ / "webapp" / "js" / "view"
}  

But I digress. For more information about the plugin, see it’s README file in the github repo.

After making my own tooling for SBT to work with dust.js, I then got to thinking about how one would actually wrap the dust.js rendering system. Curiously, the examples I found online suggest making an AJAX call to fetch the context, or template data. This strikes me as quite sub-optimal as it would mean creating the following requests:

  • fetching the general html for the page in the first instance
  • another request for the dust.js runtime
  • another request for the dust template
  • and then another for the context data

All that, just to render one template and add unnecessary lag to the page load whilst the ancillary request for context data takes place (after the initial page load has already completed!). For general page rendering, this seems somewhat bizarre. That is to say, requesting context data via AJAX for say, a single page application could well be a reasonable use-case, but for general pages that render “in full”, it seems silly.

Assuming you’re just rendering regular page content, we can make the separation between things one would want to load and cache locally in the browser, and things that need to be dynamic. For the most part, the context is the only thing you’d want to be dynamic and the more general plumbing code for rendering would probably be reusable throughout your rendering call sites. Consider a simple sample:

The dust template (lets call it home.dust in src/main/dust):

<div>
  <h2>Hey {name}</h2>
</div>  

This template will then be compiled to home.js and placed in the resource managed output location (as per your build config). The other thing to probably think about is if had several pre-compiled template files needed on a given page it would make sense to merge and minify them into a single JS file. Alternatively, if you were building a single-page application it might be nice to use a client-side loading framework like LABjs to pull in the template files lazily (i.e. as you needed them). Getting back tot eh example, and considering the aforementioned, lets assume a HTML page that loads the DOM skeleton and the static libraries needed for rendering:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script type="text/javascript" src="js/dust.min.js"></script>
  <script type="text/javascript" src="js/view/home.js"></script>
</head>
<body>
  <h1>Home</h1>
</body>
</html>

Now, as it stands this page would display the heading “Home” and load the dust library along with the compiled template; otherwise it is essentially static. In order to render the dust template one would have to add something like the following to the page <head>:

<script type="text/javascript">
//<![CDATA[
dust.render("home", { name: "Fred" }, function(err, out) {
  document.getElementById('whatever').innerHTML = out;
});
//]]>
</script>

This simple bit of JS would render the content into the element with the “whatever” ID attribute. Now then, this will work, and prove the concept for sure. What it does not do however is provide a dynamic context, which almost certainly most users would want to do. In this way, I can see why people might see that it made sense to make an AJAX request to a pure JSON backend service to get the context dynamically, but as above, this would be a bit slow and cumbersome. Instead, I think it would probably make more sense to dynamically deliver a call to a rendering function with the desired context. Let’s qualify that: when the page loads, the template has been loaded and so has the dust library, so all that is actually required is have a call site that starts the rendering. I think this need can quite nicely be served by a server-side helper function. In essence, when the page is loaded, the server generates a <script> tag. Here’s an example:

<body>
  ...
  <script type="text/javascript" src="/view/home"></script>
</body>

Which in turn would deliver something like:

draw("home", { name: "Whatever" });

That is, where the draw function wraps the dust rendering system. This is just an example though as the point is that this could be any kind of JavaScript. For instance, it could be a backbone.js view or something along those lines: you deliver the rendering code along with the context. This at least seems more optimal than making a fuckton of JavaScript requests for context objects as other blogs suggest.

In the next post i’ll be showing you how to combine all the latest hipster web programming tools like dust.js, CoffeeScript and Less with a Scala backend using Unfiltered to deliver the dynamic template contexts.


11
Dec 11

Documenting the Difficulties of Documentation

Over the years i’ve been involved in a wide-range of diverse open source projects. Some large. Some small. Some very obscure. But every single one has at one point or another, had a “problem” with documentation. Many of you reading this will no doubt have had a similar experience at some point in your programming career. Perhaps you were a project creator wondering how best to communicate the inherent awesome of something you’ve just created, or perhaps you were that eager n00b trying to get to grips with some new technology you came across on github – in either case, you have to create or consume “documentation”.

Now then, before we go any further I do have somewhat of a problem with the overloaded meaning of the term “documentation”. The widely accepted definition of documentation is the following:

Doc·u·men·ta·tion noun – Material that provides official information or evidence or that serves as a record.

Evidence that serves as a record? That sounds awfully vague doesn’t it. I’d like to suggest that this is, to all intent purposes, too vague. More specifically it is often an ambiguous umbrella term for what people are actually referring too. It’s this ambiguity that causes all manner of problems for software projects and their (would-be)users.

Disambiguating Documentation Components

There are many excellent projects in the Scala ecosystem, and many suffer this apparent “lack of documentation”. Curiously though, each project seems to suffer this affliction in its own specific way… at least, this is often what you might witness on the mailing-list of any project you might care to pick at random. Most projects have some thread or other in the archives of their mailing lists where someone has complained about their documentation, or distinct lack of whatever it is they were looking for.

With this in mind, i’d like to now illustrate what I think are the key aspects of the wider “documentation problem”, and disambiguate their respective intentions.

Tutorials and Introductions

The first thrust of documentation i’d like to define is that all-important introductory material people will need when coming to your project in the first instance. This is quite probably the most difficult type of text to write, particularly if the subject matter is highly technical in nature. It’s typically difficult for the following three reasons:

  • Assumptions – Assuming the reader fully understands a topic, line of code, operator or anything else must be one of the most common issues. In introductory texts and tutorials its highly likely that the reader will not be in possession of the implicit knowledge that’s relevant to properly grok the topic at hand.
  • Accessibility – “Joe Developer” can initially be easily scared by large words, complex-sounding terms that originate from academic theories, and terse writing styles. It is so vitally important that your tutorials and introduction texts are accessible. For the most part this may well mean that you have to sweep over some of the finer details, or forego some more abstract possibilities in order to effectively get the point across to newcomers. Ironically, it is often this simplification or frivolity with the facts that programmers struggle with when taking up the pen (ok – keyboard, but you know what I mean).
  • Authorship – Writing is hard. Be honest with yourself and recognise that you may not be any good at it. During the writing of Lift in Action I had to throw away a whole bunch of manuscript which was either too technical or just plain rubbish. Having a professional team of editors who could help me (re)learn about writing was really key… but i’m aware that this is hardly practical for the common case. The fact is that most of us have not written long documents since high-school or college, and it is incredibly difficult. Don’t forget this when writing your project introduction and tutorials – if you can’t do it the proper justice it deserves, then embrace the fact that us humans all have different skills and find someone who can plug the required gaps. Having your texts reviewed honestly by your peers is also another useful strategy to ensure what you’re writing is actually any good.
Examples and Explanations

The second branch of the documentation umbrella is somewhat of an extension to the first, but I decided to make it separate because its use-case feels distinctly different. With this in mind i’ll add the caveat that yes, examples often form parts of tutorials (and later, references), but in and of themselves you wouldn’t use verbose introductory-style writing within an example. In my mind at least, the primary difference is that example/explanatory documentation is tightly coupled with the code to which it relates. That is to say that the text is more often than not sitting next to the code itself in the comments, which usually means there are certain conventions to follow with regard to syntax and so forth (e.g. ScalaDoc, Wiki markup etc). Critically though, the tone of voice in the explanatory text when compared to that of the introductory & tutorial manuscripts is much shorter, more concise and really focusing on the line-by-line, blow-by-blow goings on of the code. More generally, its reasonable to suggest that examples are about illustrating concepts, and this is where the writing style really differentiates itself from the other branches listed in this article.

Finally, if you’re going to go to the trouble of writing examples and explanations, make sure the code actually works! Nothing is more frustrating to find an example that simply does not do what it should because the code either doesn’t compile or doesn’t run correctly.

Reference materials

Reference material is your last line of defence before forcing users to delve into the source code. Consider the type of person might be using a reference, or what their goal might be? I’d propose that when someone is looking at a reference, they know what they are looking for: they need something specific. It’s probably also fair to assume that before arriving at the reference they will have read tutorials and examples, so there is a degree of implied understanding. Reference materials are usually heavy on details and light on fluffy writing style, which allows the author to be far more technical, and satisfy the aforementioned need for presenting the exact facts.

Unlike the other aspects of documentation writing, references can have the tendency to become quite large; even for mid-sized projects. With this in mind you should take care to refactor the organisation and layout of the reference with each major change and strives for a reference that is logically ordered and consistent throughout. If your reference is massive, then you should seriously consider having a decent search function in addition to a logical layout.

Source Code

Your last line of documentation defence is the source code. That might seem odd, as i’m not talking about comments or ScalaDoc (or similar in your language of choice). I’m talking about types (sorry dynamically typed people!). Type annotations can be extremely useful when reading code and concisely communicating the result or intention of a particular item. With Scala for example, consider these two lines:


  // actual code irrelevant
  val foo = whatever.map(...).flatMap(...).foldLeft(...).map(...)
  val foo: Option[Int] = whatever.map(...).flatMap(...).foldLeft(...).map(...)

Having the simple type annotation frees me from having to mull over the code in order to understand its result; its right there in the type annotation. When moving code between teams, or people, having the ability to simple scan complex blocks of code and understand it is a huge win (IMHO). Sure, make use of type inference where the value is obvious (e.g. simple assignment etc), but where you think something might not be directly understood explicitly annotating can serve as effective documentation.

…In any case, writing readable and well documented code could easily be the subject of a whole other blog post (or indeed, academic paper), so we’ll put a pin in that subject and move swiftly along…

In my mind at least, when your general users complain about documentation, they are typically complaining about one of first three branches of this documentation umbrella.

Isn’t all this a lot of work?

I won’t lie to you, good reader: this will take a lot of time and dedication to do. To do it well, will take more time and a fuckton more effort. However, if you want your software or project to be used by people other than yourself, then it is imperative the documentation is well structured, and exhibiting some – if not most – of the traits in this article. It’s also important that you realise that it will, in all likelihood, be “expensive” in terms of time; this is nearly unavoidable, but it will make your project more approachable and more usable.

Interestingly one thing that you often see are projects that try to distill the documentation effort by promoting community authorship, which when considering what a social activity programming has become in recent times, does not seem like such a crazy idea. The reality however is somewhat different to the ideal: people are often keen to submit bugs and patches, but those same keen people are still typically reluctant to contribute documentation. One could speculate that writing documentation was too tedious, or that perhaps it was not as fun as doing the coding and people didn’t want to spend time in that area… the reason is actually irrelevant, as the result is always the same: without a small core of dedicated people who write, maintain and constantly improve that wiki the whole documentation effort will fail. To qualify that, i’m not saying that community-powered documentation never works, as that clearly isn’t the case. I am however suggesting that by-and-large for most communities it simply does not operate effectively, and this has an overall negative impact on the project as a whole.

Who’s doing it right?

I’m not going to gratify this article with pointing out projects that are “doing it wrong”, as frankly most projects are making a hash of their documentation; irrespective of language or community. I do however want to highlight a couple of projects that are setting an excellent example:

  • Akka – The Akka team are making a superb job of documenting their project, even with extensive changes to the codebase they are very effective when it comes to ensuring the docs are up-to-date and covering all new or refactored features. The documentation is nearly exclusively maintained by the core team of programmers.
  • JQuery – Very different to Akka, and in a different community, JQuery has been very effective in delivering core reference materials that allow (and encourage) the wider community to write tutorials, introductions and other helpful articles. JQuery also makes extensive use of illustrative examples, and its good documentation is probably one of the reasons for its apparent ubiquity on the web today.

Both of these projects exhibit dedication on the part of the coders, who are typically the ones authoring the core reference materials and bulk of the ancillary texts. Learn from these projects and others like them. We can all do a better job of documenting our projects, myself included. Say no to undocumented projects, and the next time you’re throwing something on github, take the time to write some documentation… even if its a long README people will thank you for it.


23
Aug 11

Using Apache Shiro with Lift

As it stands, Lift only has its proto* traits for user management, and that system has its limitations and you will ultimately end up replacing it in any non-trivial application as your needs change and you need to grow. Whilst this is what those traits are designed for (quick start, short haul), you typically end up rolling your own system for users etc when using Lift, and this can often be somewhat cumbersome or not particularly easy to do well. As this whole user management piece is so often requested, I figured that i’d write a plugin library for Lift.

Apache Shiro is a Java security framework (formally known as JSecurity) and it comes with a fairly abstract set of classes for building systems that have the familiar users, roles and permissions setup. Pretty much most applications these days have some notion of users, customers or some other subject that you care about and might want to conduct access control around. This is exactly what Shiro is designed for, and it ships with out of the box inter-operation with ActiveDirectory and other such repositories commonly found in the enterprise space for managing user data.

Part of the reason that other security frameworks never really took to Lift (or vice-versa) is that Lift has its own mech for managing resource ACLs and it never made sense to separate that into a different servlet filter and somehow munge that together: its not 1990. Fortunately Shiro was fairly easy to integrate with Lift in such a way that it allows you to simply augment your existing SiteMap setup, template markup and even dispatch resources. Currently this integration project is in early stages, and you can find the source code here: github.com/timperrett/lift-shiro

Example

Here’s a quick walkthrough of the various ways you can use the integration within your project. Firstly, lets assume you only want to display a section of content to authenticated users:


  <lift:has_role name="admin">
    <p>This content is only available for admins</p>
  </lift:has_role>

There are a range of authentication snippets that allow you to define who sees what within your templates, checkout the documentation for more on that. Nextup, what if you want to block access to an page entirely if the user is not authenticated? Just add the following to your SiteMap:

...
Menu("Home") / "index" >> RequireAuthentication
...

By default RequireAuthentication will redirect unauthenticated users back to the URL defined in Shiro.loginURL. Likewise, you can specify whole resources to require a particular role or permission:

...
Menu("Role Test") / "restricted" >> RequireAuthentication >> HasRole("admin")
...

Clearly the SiteMap functionality is implemented as LocParam, so you can implement them within your own Loc types, or simply use them declaratively within the regular SiteMap usage.

This whole integration project wraps the Shiro types, so you only need to configure shiro.ini in the root of your classpath and enter the appropriate realm information as per the regular Shiro documentation, then away you go: password files… active directory… whatever you want.

As above, this project is still early stage, but it does indeed work. I’m currently looking for feedback, so if you have some thoughts or things that would be cool to see, then please checkout the project on Github and fork away.


1
Aug 11

System Scripting with Scala

For the longest time I have used Ruby as my pocket knife for system scripting… you know, just knocking up small little executable files that run helpful tasks or automate yawnful processes. I like Ruby for this kind of thing and it works. Recently a coworker in marketing wanted some automation for something relatively simple and instead of using Ruby I thought i’d just knock it together with Scala and in doing so I came across a neat little thing with the Scala scripting support.

Assuming you have Scala installed, you can execute bash statements and pass them directly to your Scala code. This can be pretty handy as there are certain things that are particularly annoying to do from Scala (and more broadly with Java) like finding out where exactly you are executing too on the file system. Often if you use the good ol’ protection domain trick it will give you a location in /var/tmp, as opposed to the real location of the script. Consider the following:


#!/bin/sh
SCRIPT="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"
DIR=`dirname "${SCRIPT}"}`
exec scala $0 $DIR $SCRIPT
::!#

import java.io.File

object App {
  def main(args: Array[String]): Unit = {
    val Array(directory,script) = args.map(new File(_).getAbsolutePath)
    println("Executing '%s' in directory '%s'".format(script, directory))
  }
}

Notice the base code between #!/bin/sh and ::!#. This allows you to execute bash script (or whatever script you want) before evaluating this file as a Scala script. This can be pretty handy for certain tasks when doing system scripting :-)

Assume you saved this file as “thing”, you can then execute it like any other script: ./thing

Enjoy.


26
Jul 11

Using SOAP with Scala

It seems I have inadvertently become “that guy who does SOAP with Scala”. Given this illustrious position it seemed prudent to get around to putting up an article that explains how to use the SOAP support now present in Scalaxb.

Scalaxb is a nice tool for working with XSD Schema from Scala, and recently WSDL support was added. In short this means that you can use native Scala types (such as Option[T]) for interacting with SOAP methods.

Prerequisites

Before you get going, its necessary to install Scalaxb, which itself requires Conscript, so install that first. With ConScript in place, install Scalaxb by running:

cs eed3si9n/scalaxb

This will install Scalaxb and make it available on your $PATH. You can verify this by running the scalaxb command.

Generating Contracts

With Scalaxb installed and your WSDL to hand, you can run something like:

scalaxb -p eu.getintheloop.sample \ 
        -d src/main/scala \
        src/main/wsdl/weather.wsdl

This will generate a range of .scala files pertaining to the WSDL contract you passed as the last argument to the scalaxb tool. In addition this sample includes the -p to specify your own package and also the -d argument to place the output files into my Scala source directory. In this particular case, I’m using this SOAP endpoint, and you can freely do so too for the sake of this example.

Understanding Generated Classes

Scalaxb generates three separate components:

  • SOAP protocol classes: These are the ancillary classes that are used to operate the SOAP protocol for things like the message envelope.
  • Default transport implementation: The HTTP driver to actually POST the SOAP message to the endpoint URI. This default implementation is based on the blocking HTTP Scala Dispatch
  • Your service contracts: This is the only service specific part of the generated files. These relate to your specific service whilst the other two parts are completely decoupled and reusable over implementations / services you might have.

Enough talking, lets look at some code.

Usage

The Scalaxb SOAP mechanism makes heavy use of the cake pattern, and thus allows you to mix and match different components as your situation dictates. Here’s the default usage pattern:

package eu.getintheloop.sample

import scalaxb._

object Main {
  def main(args: Array[String]){
    
    val remote = new WeatherSoap12s 
       with SoapClients 
       with DispatchHttpClients {}
    
    println {
      remote.service.getWeather(Some("New York"))
    }
  }
}

Note specifically that by combining the weather service contracts with the SOAP protocol classes and the transport implementation, the result is a working driver from which you can directly call the SOAP methods.

The result of the service call itself is a Either[Fault[_], Option[T]], so if you want to get at the actual value you can just simply fold on the Either.

Suggestions for Customisation

If you have multiple services to interact with then it can be nice to cake together all your service implementations so that you just have a single client that lazily loads the appropriate service classes as needed. Additionally, you could also replace the transport implementation with something asynchronous and based on futures… that also is fun.

The sample code for this example can be found at: https://github.com/timperrett/scalaxb-soap-example

Enjoy.


19
Apr 11

SBT gets CloudBees support (and fast deploys!)

About 18 months ago a company came out of nowhere called Stax Networks who were offering the ability to host JVM-based applications in the cloud, for FREE. This was too awesome not to look into and I subsequently made a plugin for SBT that automatically deployed your WAR files with a simple command.

Stax themselves were recently taken over by CloudBees and from what I can see the service has done nothing but become more awesome since that has happened. Now that take over is bedding in, the API has changed somewhat so I thought i’d rewrite my Stax plugin to work with CloudBees instead and take advantage of the ability to delta WAR files and only publish the updates.

Speedy Deploys

The way this works is the build tool creates a WAR file like it would do normally, but as this is usually fairly large it can be exceedingly annoying to have to keep waiting for the deployment to take place. Rather than wait, the build tool calculates the difference between the deployed artefact and the one you just created, and subsequently only deploys the difference (or delta): essentially reducing your deploy time from 15 mins or more to a few seconds.

Gimmeh It

In order to get started with using the SBT plugin, you will of course need a CloudBees account and upon registering you need to grab the key and secret from grandcentral.cloudbees.com, which should look something like:

These values represent the API Key and API Secret that CloudBees will use to verify your deployment rights. Once you have these two values, you can do one of two things in order to have them recognised by the SBT:

  • Enter them when the plugin prompts you; this will be on everytime you run a deployment to the cloud so is potentially a little sub-optiomal.
  • Create the properties file $HOME/.bees/bees.config so that you only need to define them once per computer. This properties file needs to be a key-value pair which should look something like this:
bees.api.key=XXXXXXXXXX
bees.api.secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX=

Whichever route you choose to specify that information, you then only need to define the plugin information in any given project. Specifically, in the Plugins.scala file define the following:

  import sbt._
  class Plugins(info: ProjectInfo) extends PluginDefinition(info) {
    lazy val cloudbees = "eu.getintheloop" % "sbt-cloudbees-plugin" % "0.2.7"
    lazy val sonatypeRepo = "sonatype.repo" 
      at "https://oss.sonatype.org/content/groups/public"
  }


Add the plugin to your SBT project like so:

  import sbt._
  class YourProject(info: ProjectInfo) extends DefaultWebProject(info) 
    with bees.RunCloudPlugin {
    ....
    override def beesUsername = Some("youruser")
    override def beesApplicationId = Some("whatever")
  }

Again, if you would prefer to enter these values when you deploy your application then you can of course just enter the appropriate values when prompted. Now your all configured and good to go, there are two commands you can run with this plugin:

  • Get a list of your configured applications: bees-applist
  • Deploy your application bees-deploy

Upon running bees-deploy for the first time there will of course be a wait whilst the first version is deployed, but all your subsequent deployments should be much, much quicker. CloudBees is a rather awesome service and i’d highly recommend checking it out for fast, easy deployment of your JVM web applications.

Find the source code for the CloudBees SBT plugin here


11
Apr 11

Using Type Classes for Lift Snippet Binding

Back in 2009 I was inspired by this article by Kris Nuttycombe which demonstrated how to use implicit conversions to declare composable, reusable Lift snippet bindings.

At the time that article was written, Scala was still in the 2.7.x series and Lift only had the bind() helpers. As I write this today, Lift has its new CSS-style transformers and the Scala language has moved on quite considerably – especially with regard to the handling of implicits. With this in mind I wanted to show how one could make a similar setup but by leveraging Scala context bounds and Lift’s CSS-style transformers.

Use Case

Consider that you were building a system that displayed products. It’s quite feasible that everywhere you wanted to display said product a same or similar binding would be required. A classic point in case is the product listing vs the checkout; the latter would only require a few of the product aspects to be displayed but there would be enough commonality with the listing usage as to not want to repeat yourself.

For the sake of this article Product will be represented like so:

case class Product(name: String, price: Long)

Binding

In order to make something implicitly bindable, that is to let the compiler know when it should apply the in-scope binding we need to make a bit of infrastructure to facility this:

import net.liftweb.util.CssSel

object Bindings {
  class Bind[T](what: T){
    def bind(implicit bind: DataBinding[T]) = bind(what)
  }
  type DataBinding[T] = T => CssSel
  implicit def asCssSelector[T](in : T): Bind[T] = new Bind[T](in)
}

Here the Bindings object contains a converter class call Bind[T] whos method bind takes an implicit parameter of DataBinding[T]. In more lay terms, given T (ultimately, Product type) apply an implicit conversion from T => CssSel, where CssSel is the internal Lift type for CSS transformers. Finally, the asCssSelector method does the actual conversion to a Bind[T] instance just like any regular implicit conversion.

So all that remains is to implement a binding for Product and show how you can use that in your snippet classes:

import Bindings._
import net.liftweb.util.Helpers._

object ProductBinding extends DataBinding[Product]{
  def apply(product: Product) = 
    ".name" #> product.name
}

class MySnippet {
  private implicit val binder = ProductBinding
  
  def render: CssSel = 
    Product("whatever", 1234L).bind
}

In this example, ProductBinding defines the generic binding that one requires for Product usage within the system. In your code, this would certainly be a lot more fully featured, but for the sake of example it just binds the name. Within the MySnippet class one can then simply call Product("whatever", 1234L).bind and thats all that needs doing. In order to put the implicit binding in-scope, the ProductBinding singleton is just assigned to a value. This could have just as easily been held somewhere else in a common binding object and then imported to save the clutter, but here it is explicitly defined for the snippet.

There is an alternative syntax which you might prefer for the snippet implementation that uses context bounds like so:

def render[Product : Bind] = 
  Product("whatever", 1234L).bind

Importantly, with both implementation styles not that you can also add snippet-specific additions to the generic binding. For example:

def render: CssSel = 
    Product("whatever", 1234L).bind &#038; 
    ".thing" #> "example"

Hopefully you found this useful. For more information like this, please pick up a copy of Lift in Action


23
Feb 11

HTTP Dispatch Guards in Lift using PartialFunction

There are many little known features within the Lift code base and one that i’ve been meaning to blog about for quite some time is the ability ot use partial functions as guards for HTTP dispatch.

Let’s assume that your system requires some state to be set, like a session variable to ensure the user has logged in before they can access other parts of the service. The following example shows you you can implement a simple partial function to act as a guard.

What’s the goal?

The aim is to be able to define your services like so:


  LiftRules.dispatch.append(withAuthentication guard Service)

This gives you a fairly readable API that even with little knowledge of the underlying API you can see that you must have an authenticated session. In this super simple case, I’ll just implement authentication as a Boolean in a SessionVar, but you get the point.

The Service

Consider this service definition:



import net.liftweb.http.rest.RestHelper
import net.liftweb.http.{PlainTextResponse}

object Service extends RestHelper { 
  serve {
    case "protected" :: Nil Get _ => 
      PlainTextResponse("Ohh, secret")
  }
}

This is a super simple service using HTTP dispatch in Lift. Let’s then define the dummy “login” url. In practice this would actually be some kind of bonified authentication but for this example it will suffice.


import net.liftweb.http.rest.RestHelper
import net.liftweb.http.{SessionVar,OkResponse}

object Security extends RestHelper {
  serve {
    case "login" :: Nil Get _ => 
      LoggedIn(true)
      OkResponse()
  }
}

object LoggedIn extends SessionVar(false)

As you can see, simply hitting the URL /login will set the session to be logged in. Completely useless for production, but it serves my means here.

The Boot Configuration

Finally, now you have the services setup its time to write it all together within the Boot class.


import net.liftweb.http.{LiftRules,Req}
import net.liftweb.util.Helpers._ 
import sample.lib.{Security,Service,LoggedIn}

class Boot {
  def boot {
    val withAuthentication: PartialFunction[Req, Unit] = { 
      case _ if LoggedIn.is => 
    }
    
    LiftRules.dispatch.append(Security)
    LiftRules.dispatch.append(withAuthentication guard Service)
  }
}

The key here is the import of Helpers._ to provide the implicit functions to enable guard to be called on the withAuthentication partial function, and the withAuthentication value simply passes all cases to an if statement that accesses the value of the SessionVar. Pretty simple, eh?

Enjoy. All the code for this sample can be found here


30
Jan 11

Memoization of Lift localeCalculator

Within Lift each request has its locale calculated from scratch. Whilst this is fine with the default setting of reading from the accept headers on the incoming request, when you want to perhaps conduct something more complex you can inadvertently add quite an accidental overhead to the processing of each request. You can however ensure that the localeCalculator is only executed once by memoizing the value of the locale for the whole request cycle.

The following code memoizes the locale computation into a variable that will exist for the full lifetime of a page request ensuring that you do not take the overhead of processing the locale a bunch of times.

This is obviously a basic implementation that carries a smalloverhead, but the principal here is the same irrespective of what it is you are actually doing :-)

Find great tips like this and more within Lift in Action


10
Dec 10

Distributing Critical State With ContainerVar

Lift 2.2 brings a lot of new features to Lift, and one of them is ContainerVar. I previously blogged about it but did not have time then to make a screencast or sample. Now I have done both :-)

This and many more techniques are discussed in my book, Lift in Action.

Find source code here: https://github.com/timperrett/lift-terracotta-example