Simple REST App in Web Content Management (JSONFactoryUtil and HttpUtil)

I've heard that you can do some really cool stuff in Web Content (check out James's and Ray's blogs) but haven't gotten around to tinkering with that myself.  Here is a fun little experiment with that, it grabs a Chuck Norris joke from a REST API, all from inside of a Web Content template.

 

 

And here is the code for the Web Content Template:

#set($jsonResponse = $jsonFactoryUtil.createJSONObject($httpUtil.URLtoString('http://api.icndb.com/jokes/random')))

<p>We are calling a <a href="http://www.icndb.com/api/">simple REST API which grabs a Chuck Norris joke</a> and displaying part of our web content based on that response.</p>

<p>Output some values for debuging purposes:</p>

<ul>
    <li>jsonFactory: $jsonFactoryUtil (This will display the full package name if this loads correctly)
    <li>Response: $jsonResponse
</ul>

#if ($jsonResponse.getString('type') == 'success')
    <div class="portlet-msg-success">
        $jsonResponse.getJSONObject('value').getString('joke')
    </div>
#else
    <div class="portlet-msg-error">
        You broke the interwebs.
    </div>
#end

 

Additional Notes:

  • You can paste this into any web content template.  This outputs the same thing regardless of what is in your structure and web content.
  • Tested against 6.1.30 and 6.2.10
  • Uncheck "cacheable" if you want to load a new joke each time the page refreshes.
  • When using this code snippet, make sure that you have the script language set to "Velocity".
  • For this example, you wont need to enable restricted values from velocity or freemarker, but if you need more power and want to use Liferay services, be sure to check that out.