<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0"><channel><title>Felipe Cypriano</title> <link>http://felipecypriano.com/blog</link> <description>You are about to read it</description> <lastBuildDate>Thu, 04 Mar 2010 14:46:25 +0000</lastBuildDate> <generator>http://wordpress.org/?v=2.9.2</generator> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency>  <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/felipecypriano" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="felipecypriano" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><title>Grails with ZK: How To Create Components in Runtime with The Builder</title><link>http://felipecypriano.com/blog/2010/03/04/grails-with-zk-how-to-create-components-in-runtime-with-the-builder/</link> <comments>http://felipecypriano.com/blog/2010/03/04/grails-with-zk-how-to-create-components-in-runtime-with-the-builder/#comments</comments> <pubDate>Thu, 04 Mar 2010 14:42:30 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[ZK Direct RIA]]></category> <category><![CDATA[builder]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[zk]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=245</guid> <description><![CDATA[ZKGrails plugin has an extremely nice feature which make easier than ever to create ZK components in runtime.
First lets see how is the usual way to create components in runtime using Java. This is the zul representation of what we’re trying to achieve:
&#60;div&#62;
&#60;toolbarbutton label="Clickable Item" href="#" /&#62;
&#60;toolbarbutton image="edit.png" if="${userHasAccess}" /&#62;
[...]]]></description> <content:encoded><![CDATA[<p><a
href="http://code.google.com/p/zkgrails/">ZKGrails</a> plugin has an extremely nice feature which make easier than ever to create ZK components in runtime.</p><p>First lets see how is the usual way to create components in runtime using Java. This is the zul representation of what we’re trying to achieve:</p><pre class="brush: xml">&lt;div&gt;
  &lt;toolbarbutton label="Clickable Item" href="#" /&gt;
  &lt;toolbarbutton image="edit.png" if="${userHasAccess}" /&gt;
  &lt;toolbarbutton image="delete.png" if="${userHasAccess}" /&gt;
&lt;/div&gt;</pre><p>And the java code to do the same:</p><pre class="brush: java">Div div = new Div();
Toolbarbutton tbb = new Toolbarbutton("Clickable Item");
tbb.setHref("#");
tbb.setParent(div);
if (userHasAccess) {
    Toolbarbutton tbbEdit = new Toolbarbutton();
    tbbEdit.setImage("edit.png");
    tbbEdit.setParent(div);
    Toolbarbutton tbbDelete = new Toolbarbutton();
    tbbDelete.setImage("delete.png");
    tbbDelete.setParent(div);
}</pre><p>As you can easily see the java code is pretty verbose. Using ZKBuilder the code will be easier to understand and smaller, take a look:</p><pre class="brush: groovy">Div div = new Div();
div.append {
    toolbarbutton(label: "Clickable Item", href: "#")
    if (userHasAccess) {
        toolbarbutton(image: "edit.png")
        toolbarbutton(image: "delete.png")
    }
}</pre><p>Which one do your prefer? <img
src='http://felipecypriano.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> If you want more continue reading to see how to use the builder as a template to a list of items.</p><h2>Using ZKBuilder as a Template</h2><p><span
style="font-size: 13pt;"><span
id="more-245"></span></span></p><p>I think the builder is specially useful when I’ve a list of items and I need to display these items with a specific layout one that the grid nor the listbox <a
href="http://www.zkoss.org/smalltalks/databind4/databind4.dsp">can provide</a>. So I start as I started this post making the layout on a zul page and after I get what I want, I made a ZKBuilder version and put it in a loop to execute for each item I need to show.</p><pre class="brush: groovy">// ...
def items = myService.getItems()
items.each { item -&gt;
    div.append {
        toolbarbutton(label: item.name, href:  item.link)
        if (userHasAccess) {
            toolbarbutton(image: "edit.png", onClick: {editItem item})
            toolbarbutton(image: "delete.png", onClick: {deleteItem item})
        }
    }
}
//...
public def editItem(def item) { /* code to edit the item */}
public def deletetem(def item) { /* code to delete the item */}</pre><p>ZkBuilder is bundled in ZKGrails 0.7.6 and earlier. Enjoy!</p> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2010/03/04/grails-with-zk-how-to-create-components-in-runtime-with-the-builder/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Handling events on ZK macro components</title><link>http://felipecypriano.com/blog/2010/01/15/handling-events-on-zk-macro-components/</link> <comments>http://felipecypriano.com/blog/2010/01/15/handling-events-on-zk-macro-components/#comments</comments> <pubDate>Fri, 15 Jan 2010 10:41:55 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[ZK Direct RIA]]></category> <category><![CDATA[java]]></category> <category><![CDATA[zk]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=303</guid> <description><![CDATA[One of the great features of ZK is the possibility to create a new component based only on other existing components using the declarative language ZUML - the same you've been using in you zul files. Those are called Macro Components. The beauty of macro components is that it's very easy to make a new [...]]]></description> <content:encoded><![CDATA[<p>One of the great features of ZK is the possibility to create a new component based only on other existing components using the declarative language ZUML - the same you've been using in you zul files. Those are called Macro Components. The beauty of macro components is that it's very easy to make a new one and hence avoid code duplication on your pages.</p><p>Talk about how to implement a macro component isn't the scope of this post, so I suggest you to read the <a
title="ZK - Macro Component - Documentation" href="http://docs.zkoss.org/wiki/Macro_Component">documentation</a> before continue reading.</p><p>We'll work on a very simple macro component. But, don't hesitate when you need to make a very complex one. Our macro component is this: <em>WEB-INF/mymacro.zul</em></p><pre class="brush: xml">&lt;hbox&gt;
    &lt;label id="myLabel" value="Click the button"/&gt;
    &lt;button id="myButton" label="The Button"/&gt;
&lt;/hbox&gt;</pre><p>Now that you already knows what is and how to make a macro component, let's start talking about what you may think it'll work but actually it doesn't.</p><h2>Automatically Forward Event Doesn't Work</h2><p>The standard way to <a
title="ZK - MVC Made Easy" href="docs.zkoss.org/wiki/ZK_MVC_Made_Easy">register events on ZK's component, using </a><acronym
title="Model View Controller"><a
title="ZK - MVC Made Easy" href="docs.zkoss.org/wiki/ZK_MVC_Made_Easy">MVC</a></acronym>, is to use the "autowire" feature of GenericForwardComposer. Like this:</p><p>WEB-INF/index.zul</p><pre class="brush: xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;zk&gt;
    &lt;window apply="com.felipecypriano.IndexComposer"&gt;
        &lt;label id="lblOutside"/&gt;
        &lt;button id="btnOutside" label="Not In Macro"/&gt;
    &lt;/window&gt;
&lt;/zk&gt;</pre><p>src/com/felipecypriano/IndexComposer.java</p><pre class="brush: java">package com.felipecypriano;

import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Label;

public class IndexComposer extends GenericForwardComposer {
    private Label lblOutside;

    public void onClick$btnOutside() {
        lblOutside.setValue("Button 'not in macro' clicked");
    }
}</pre><p>The button 'btnOutside' belongs to the window component and therefore its composer can automatically access and configure btnOutside events. When the Composer is initializing it detects the method onClick$btnOutside() and sets this method as a 'btnOutside' onClick event listener, in other words when the component is clicked this method is executed.</p><p>Knowing this we can think that add an event to 'myButton', which belongs to 'mymacro', is pretty much the same. Don't we? Let's add the macro in the index.zul and create a new method to handle onClick event of 'myButton':</p><p>WEB-INF/index.zul</p><pre class="brush: xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;?component name="mymacro" macroURI="/mymacro.zul" ?&gt;
&lt;zk&gt;
    &lt;window apply="com.felipecypriano.IndexComposer"&gt;
        &lt;label id="lblOutside"/&gt;
        &lt;button id="btnOutside" label="Not In Macro"/&gt;
        &lt;separator bar="true"/&gt;
        &lt;mymacro/&gt;
    &lt;/window&gt;
&lt;/zk&gt;</pre><p>Just before <em>&lt;zk&gt;</em> tag is the macro component definition (line 2), this directive tells to ZK where is the file that contains the component - <em>macroURI="/mymacro.zul"</em> -  and what's the tag name we'll use - <em>name="mymacro"</em> - to reference our component (line 8).</p><p>Adding the onClick event on 'myButton' cannot be done by just adding this method to IndexComposer:</p><p>src/com/felipecypriano/IndexComposer.java</p><pre class="brush: java">    public void onClick$myButton() {
        lblOutside.setValue("Button 'myButton' clicked");
    }</pre><p>So, if this doesn't work what should I do?</p><h2>Using a Speciliazed Class</h2><p>To take care of mymacro's behavior we need to write some code. We need to create a class to specifically handle our component's needs. The purpose of mymacro component is to update the label when the button is clicked, this will not affect any of the components that doesn't belong to mymacro so it makes sense to put the event in a specialized class that can be used to all pages.</p><p>The two components inside the macro - label and button - will be accessed using <a
href="http://www.zkoss.org/javadoc/3.6.1/zk/org/zkoss/zk/ui/Component.html#getFellow(java.lang.String)">getFellow(string)</a> method and the <a
href="http://docs.zkoss.org/wiki/Event_listening_&amp;_processing#Add_and_Remove_Event_Listeners_Dynamically">event will be dynamically added</a> to the button using <a
href="http://www.zkoss.org/javadoc/3.6.1/zk/org/zkoss/zk/ui/Component.html#addEventListener(java.lang.String,%20org.zkoss.zk.ui.event.EventListener)">addEventListener</a> method.</p><p>src/com/felipecypriano/MyMacro.java</p><pre class="brush: java">package com.felipecypriano;

import org.zkoss.zk.ui.HtmlMacroComponent;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zul.*;

public class MyMacro extends HtmlMacroComponent {
    private Label myLabel;

    @Override
    public void afterCompose() {
        super.afterCompose(); // DON'T forget this
        Button myButton = (Button) getFellow("myButton");
        myLabel = (Label) getFellow("myLabel");

        myButton.addEventListener(Events.ON_CLICK, new EventListener() {
            public void onEvent(Event event) throws Exception {
                myLabel.setValue("Hooray! 'myButton' was clicked.");
            }
        });
    }
}</pre><p>Now change the component's definition to point to MyMacro.java as the component's class:</p><pre class="brush: xml; toolbar:false">&lt;?component name="mymacro" macroURI="/mymacro.zul" class="com.felipecypriano.MyMacro" ?&gt;</pre><p>Voilà.</p><h2>Global Component Definition</h2><p>There's a <acronym
title="Don't Repeat Yourself">DRY</acronym> principle violation and we must solve it. The main reason to use a macro component is to share a set of components between multiple pages, to avoid code duplication. The macro itself does this, but if you pay attention you'll see that the component's definition must be at the very beginning of each page which wants to use the component and this, definitely, isn't a good a thing.</p><p>For instance, supposing that you have 25 pages that are currently using the macro component, and in each one of them has the component's definition. Some months later, for some reason, you must change yours component's class. Instead of changing just one simple place you'll have to update 24 more places. Keep your code simple and don't repeat anything.</p><p>In order to make the component's definition global we need to create a new xml file called <em>lang-addon.xml</em>:</p><p>WEB-INF/lang-addon.xml</p><pre class="brush: xml">&lt;language-addon&gt;
    &lt;addon-name&gt;myaddon&lt;/addon-name&gt;
    &lt;language-name&gt;xul/html&lt;/language-name&gt;
    &lt;component&gt;
        &lt;component-name&gt;mymacro&lt;/component-name&gt;
        &lt;component-class&gt;com.felipecypriano.MyMacro&lt;/component-class&gt;
        &lt;macro-uri&gt;/mymacro.zul&lt;/macro-uri&gt;
    &lt;/component&gt;
&lt;/language-addon&gt;</pre><p>WEB-INF/zml.xml</p><pre class="brush: xml">&lt;zk&gt;
    &lt;language-config&gt;
        &lt;addon-uri&gt;/WEB-INF/lang-addon.xml&lt;/addon-uri&gt;
    &lt;/language-config&gt;
&lt;/zk&gt;</pre><p>And at last, remove <em>&lt;? component ?&gt;</em> directive from <em>index.zul.</em> From now on <em>mymacro</em> component is available to all zul pages in your application.</p><h2>Making the macro component shout to the world</h2><p>Just one more detail to learn, the component can handle its own components events, but how do the page that has the macro component knows what's going on? We need to make the macro component send events to the page, or any listener. And this is the our final step.</p><p>To keep it simple the macro component will respond just to onClick event, that's when the button is clicked 'myLabel' will be update as usual and the macro component will send the onClick event to all its listeners. Replace myButton EventListener with the following code:</p><p>src/com/felipecypriano/MyMacro.java</p><pre class="brush: java">myButton.addEventListener(Events.ON_CLICK, new EventListener() {
    public void onEvent(Event event) throws Exception {
        myLabel.setValue("Hooray! 'myButton' was clicked.");

        if (isListenerAvailable("onClick", true)) {
            Event clicked = new Event(Events.ON_CLICK, getParent());

            Iterator listeners = getListenerIterator(Events.ON_CLICK);
            while (listeners.hasNext()) {
                EventListener listener = (EventListener) listeners.next();
                listener.onEvent(clicked);
            }
        }
    }
});</pre><p>The code between lines 5 and 13 is responsible to send the event to the listeners. But we need a couple more changes, like make IndexComposer listen to mymacro. First put an id in mymacro:</p><p>WEB-INF/index.zul</p><pre class="brush: xml; toolbar: false">&lt;mymacro id="mymacro"/&gt;</pre><p>And register the event using the standard way in IndexComposer:</p><pre class="brush: java">    public void onClick$mymacro() {
        lblOutside.setValue("I can hear you 'mymacro'!");
    }</pre><p>With all this it's possible to do complex and incredible powerful macro components. Go ahead and try.</p> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2010/01/15/handling-events-on-zk-macro-components/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Grails with ZK: Embedding ZUL in GSP</title><link>http://felipecypriano.com/blog/2009/12/10/grails-with-zk-embedding-zul-in-gsp/</link> <comments>http://felipecypriano.com/blog/2009/12/10/grails-with-zk-embedding-zul-in-gsp/#comments</comments> <pubDate>Thu, 10 Dec 2009 17:31:54 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[ZK Direct RIA]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[gsp]]></category> <category><![CDATA[zk]]></category> <category><![CDATA[zul]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=274</guid> <description><![CDATA[How about zk pages and gsp were so friends that we could use both together? Imagine the possibility to use Sitemesh to decorate your page or use UrlMapping to choose what the URL will be. Or you could move your project to ZK painlessly, you could update the pages one by one and the new code [...]]]></description> <content:encoded><![CDATA[<p>How about zk pages and gsp were so friends that we could use both together? Imagine the possibility to use Sitemesh to decorate your page or use <a
href="http://grails.org/URL+mapping">UrlMapping</a> to choose what the URL will be. Or you could move your project to ZK painlessly, you could update the pages one by one and the new code will work side by side.</p><p><a
href="http://code.google.com/p/zkgrails/wiki/ReleaseNote076">ZKGrails plugin 0.7.6 has been released</a> with this great new feature, you can use two simple tags to include any zul page in your GSP. To include the necessary css and javascript into head use &lt;z:head/&gt; and to insert the content anywhre you want in the body of your gsp you'll use &lt;z:body/&gt;.</p><p>To see it in practice let's change <a
href="http://www.grails.org/Quick+Start">Grails Quick Start</a>. Follow the steps described there and after you complete all the steps, go back here to update the list.gsp to use ZK Grid component. Don't forget to use Grails 1.1.2 and ZKGrails 0.7.6 at least.</p><h2>Embedding ZK in GSP</h2><p>Firstly create this file: <em>grails-app/conf/BuildConfig.groovy</em> and configure <a
href="http://code.google.com/p/zkgrails/">ZKGrails repository</a>:</p><pre class="brush: groovy; toolbar:false">grails.plugin.repos.discovery.zkgrails = "http://zkgrails.googlecode.com/svn/plugins"
grails.plugin.repos.resolveOrder = ['zkgrails','default','core']</pre><p>Now you can install ZKGrails version 0.7.6 by executing <em>grails install-plugin zk 0.7.6</em>. After installing ZK plugin, create the zul page we'll use: <em>web-app/book/list.zul</em>. You can let this file blank for now, before editing it we need to change automatic scaffolding by creating the the gsp pages  executing this command:</p><pre>grails generate-views Book</pre><p>The command will create 4 gsp files in <em>grails-app/views/book</em>: <em>create.gsp</em>, <em>edit.gsp</em>, <em>list.gsp</em> and <em>show.gsp</em>. We will change the list.gsp to instead of use simple HTML table we'll use ZK components. Now let's get back to our <em>web-app/book/list.zul</em>, the objective is to create a grid using zk components and to add a new functionality to delete all selected books. Open <em>list.zul</em> file and put the following code in it:</p><pre class="brush: xml">&lt;?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?&gt;
&lt;?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" arg0="./wnd"?&gt;
&lt;zk xmlns:n="http://www.zkoss.org/2005/zk/native"&gt;
    &lt;window id="wnd" apply="${bookListComposer}"&gt;
        &lt;listbox id="listBoxBooks" model="@{wnd$composer.booksModel}" checkmark="true" multiple="true"
                 fixedLayout="true" width="500px"&gt;
            &lt;listhead&gt;
                &lt;listheader label="ID" sort="auto(id)" width="50px"/&gt;
                &lt;listheader label="Author" sort="auto(author)" width="225px"/&gt;
                &lt;listheader label="Title" sort="auto(title)" width="225px"/&gt;
            &lt;/listhead&gt;
            &lt;listitem self="@{each=book}" value="@{book}"&gt;
                &lt;listcell label="@{book.id}"/&gt;
                &lt;listcell label="@{book.author}"/&gt;
                &lt;listcell label="@{book.title}"/&gt;
            &lt;/listitem&gt;
        &lt;/listbox&gt;
        &lt;n:span class="buttons"&gt;
            &lt;button id="btnDelete" sclass="delete" mold="os" label="Delete Selected"/&gt;
        &lt;/n:span&gt;
    &lt;/window&gt;
&lt;/zk&gt;</pre><p>Next step is create the composer for this list.zul page, the composer is the thing that controls the page's behavior, just like a controller. Create a <em>BookListComposer.groovy</em> file in <em>grails-app/composers</em>, and this is the content:</p><pre class="brush: groovy">import org.zkoss.zkgrails.*
import org.zkoss.zkplus.databind.BindingListModelList

class BookListComposer extends GrailsComposer {

    def wnd
    def listBoxBooks
    def booksModel
    def binder

    def afterCompose = {
        booksModel = new BindingListModelList([], true)
        reloadBooks()
        binder = wnd.getVariable("binder", true)
    }

    public void onClick_btnDelete() {
        if (listBoxBooks.selectedCount &gt; 0) {
            listBoxBooks.selectedItems.each { listItem -&gt;
                def book = listItem.value
                book.delete(flush: true)
            }
            reloadBooks()
        }
    }

    private def reloadBooks() {
        def books = Book.list()
        booksModel.clear()
        booksModel.addAll(books)
        binder?.loadAll()
    }

}</pre><p>Now we only need to put the zul page in the list.gsp replacing the HTML &lt;table&gt; tag to &lt;z:body /&gt;, the final code is this:</p><pre class="brush: html">&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/&gt;
        &lt;meta name="layout" content="main" /&gt;
        &lt;z:head /&gt;
        &lt;title&gt;Book List&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class="nav"&gt;
            &lt;span class="menuButton"&gt;&lt;a class="home" href="${resource(dir:'')}"&gt;Home&lt;/a&gt;&lt;/span&gt;
            &lt;span class="menuButton"&gt;&lt;g:link class="create" action="create"&gt;New Book&lt;/g:link&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div class="body"&gt;
            &lt;h1&gt;Book List&lt;/h1&gt;
            &lt;g:if test="${flash.message}"&gt;
            &lt;div class="message"&gt;${flash.message}&lt;/div&gt;
            &lt;/g:if&gt;

            &lt;z:body /&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre><p>As you can see - lines 5 and 19 - we only need to put the tags where we want it's content to be in the page. But you might be wondering where is the path to list.zul file? By default the same convention used by Grails' view, so for our example both tags - head and body - automatically resolves to /book/list.zul. And if you need to specify the files you want you can by setting the attribute zul, like:</p><pre class="brush: xml; toolbar: false">&lt;z:body zul="/path/to/file.zul" /&gt;</pre><p>Now we can mashup our both favorite frameworks to make our projects look and behave even better.</p><p><strong># Update 1</strong></p><p>Fixed a missing namespace on zul file; and the binder call on BookListComposer. Thanks André.</p><p><strong># Update 2</strong></p><p>GitHub repository with full source code used to made this post: <a
href="http://github.com/fmcypriano/embedding-zul-gsp">http://github.com/fmcypriano/embedding-zul-gsp</a></p> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2009/12/10/grails-with-zk-embedding-zul-in-gsp/feed/</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Grails with ZK: Where are my Controllers?</title><link>http://felipecypriano.com/blog/2009/11/19/grails-with-zk-where-are-my-controllers/</link> <comments>http://felipecypriano.com/blog/2009/11/19/grails-with-zk-where-are-my-controllers/#comments</comments> <pubDate>Thu, 19 Nov 2009 20:37:31 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[ZK Direct RIA]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[mvc]]></category> <category><![CDATA[zk]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=213</guid> <description><![CDATA[ZK's zul pages works very differently compared to Grails' gsp pages but they have one thing in common both have a class to control the page's state, the behavior of each piece, the data that is showed or is being inserted by the user and this class is called Composer and Controller respectively. This is [...]]]></description> <content:encoded><![CDATA[<p>ZK's zul pages works very differently compared to Grails' gsp pages but they have one thing in common both have a class to control the page's state, the behavior of each piece, the data that is showed or is being inserted by the user and this class is called Composer and Controller respectively. This is the second article about my work with ZK and Grails, read the first part before reading this one to get an overview: <a
href="http://felipecypriano.com/blog/wp-admin/post.php?action=edit&amp;post=211">Grails with ZK Understanding Both Together</a>.</p><p>"A [grails] controller handles requests and creates or prepares the response. They can generate the response or delegate to a view.", this is the <a
href="http://grails.org/Controllers">definition taken from grails website</a>. In other words the controller receives a request do what it has to do and sends the response back.</p><p>ZK's composers are a little different, they can do things that you'd need javascript to do using gsp and controllers. The main power of a controller is that you've full control of all components in the page without need to write any javascript code. You could add or remove any component dynamically from the page, register events and whatever more you java and groovy skills let's you do.</p><h2>Pages Shouldn't Have Any Code</h2><p>In both technologies you can embed code directly in the page, in gsp you can use scriptlets:</p><pre>&lt;% items.each {
    total = it.quantity * it.price
}%&gt;</pre><p>An in zul pages you can use zkscript tags:</p><pre>&lt;zkscript&gt;
    items.each {
        total = it.quantity * it.price
    }
&lt;/zkscript&gt;</pre><p>It's fairly easy to  use code inside the pages and I really do believe you shouldn't do this, it makes your code harder to read and a mess to maintain.</p><p>The only places where this kind of code is good is in tutorials and that's why you'll see lots of tutorials using it, but in your actual project the composer/controller should do this job always.</p><h2>Your First Composer</h2><p>To demonstrate what a composer does lets create a simple editable page. The page will show a text to the user an the user can click on some buttons to change the text. All the actions will happen without refresh and you won't need to write any javascript.</p><p>Create a file named <em>editable.zul</em> in &lt;<em>your-project&gt;/web-app/</em> with this content:</p><p><em>&lt;your-project&gt;/web-app/editable.zul</em></p><pre class="brush: xml">&lt;?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?&gt;

&lt;window id="wndEditable" title="Editable Text" apply="${editableComposer}"&gt;
    &lt;div id="divText"/&gt;

    &lt;button id="btnEdit" label="Edit"/&gt;
    &lt;button id="btnSave" label="Save" visible="false"/&gt;
    &lt;button id="btnCancel" label="Cancel" visible="false"/&gt;
&lt;/window&gt;</pre><p>Pay attention to the id attribute it's value  will be used in the composer to get the java object corresponding to the component. We create an empty div called 'divText' just to make sure where the text will be in: at the top, before the buttons.</p><p>Now let's go to the composer - hooray finally eh -. Create a new directory in <em>grails-app</em> folder called <em>composers</em> and inside this new directory create a file called <em>EditableComposer.groovy</em>.</p><p><em>grails-app/composers/EditableComposer.groovy</em></p><pre class="brush: groovy">import org.zkoss.zkgrails.GrailsComposer
import org.zkoss.zul.*
import org.zkforge.fckez.FCKeditor

class EditableComposer extends GrailsComposer {
    def divText
    def btnEdit
    Button btnSave
    def btnCancel

    FCKeditor editor
    String text

    def afterCompose = {
        // This is code execute just after all the components are created, so you can access them safely
        showText()
        viewMode true
    }

    void onClick_btnEdit() {
        if (!editor) {
            editor = new FCKeditor()
        }
        editor.value = text

        divText.children.clear()
        divText.appendChild editor

        viewMode false
    }

    void onClick_btnSave() {
        text = editor.value
        showText()
        viewMode true
    }

    void onClick_btnCancel() {
        showText()
        viewMode true
    }

    private def showText() {
        text = text ?: "This is my first Composer"

        divText.children.clear()
        divText.appendChild new Html(content: text)
    }

    private def viewMode = { isViewing -&gt;
        btnEdit.visible = isViewing
        btnSave.visible = !btnEdit.visible
        btnCancel.visible = btnSave.visible
    }
}</pre><p>The components in zul are injected in composer's attributes with the same name as the id on zul file. On line 8 we use a specific type to declare the btnSave, this is just to show you that for each component in zul there's a corresponding java class where you can access and/or change all the attributes. You don't need to worry about thread safety here because for each accessed page a new composer is instantiated, this commonly known as prototype scope.</p><p>The afterCompose closure - lines 14 through 18 - is execute just after all the components declared in the zul are created and ready to use, here is the right place to put all your initialization code.</p><p>One of the features that I really like is how we can declare events to each component. As you can see in lines 20, 32 and 38 we've declared events to listen to the user clicks on the button for each of the 3 buttons. Basically this is how you declared all kinds events for all components:</p><pre class="brush: groovy; toolbar: false">public void onEventName_componentId(Event event)</pre><p>Before the underscore character is the event name and after is the component id. You can set events even for components that you didn't declared as composers attributes.</p><p>You don't need to worry about javascript to change the state in the client-side ZK will handle it for you, just change the attributes values in your groovy code and you're done. I highly recommend you give ZK a try and start playing with it, if the application you're developing fits this desktop like model ZK is a great framework to boost your productivity.</p><p><strong>See Also:</strong></p><ul><li><a
title="A walkthrough of how it was and how it is easy today" href="http://www.zkoss.org/smalltalks/mvc3/">ZK MVC Made Easy</a></li><li><a
href="http://www.zkoss.org/zkdemo/userguide/#f4">ZK FCKEditor Live Demo</a></li></ul> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2009/11/19/grails-with-zk-where-are-my-controllers/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Grails with ZK Understanding Both Together</title><link>http://felipecypriano.com/blog/2009/11/07/grails-with-zk-understanding-both-together/</link> <comments>http://felipecypriano.com/blog/2009/11/07/grails-with-zk-understanding-both-together/#comments</comments> <pubDate>Sat, 07 Nov 2009 22:38:30 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[ZK Direct RIA]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[zk]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=211</guid> <description><![CDATA[You may already know both technologies but I'll briefly introduce them. Grails is the best web framework that I ever work with, it uses Groovy and convention over configuration to simplify our development efforts. To name a few this is what you've out-of-the-box: persistence layer to save your entities to a relational database, dependency injection, [...]]]></description> <content:encoded><![CDATA[<p>You may already know both technologies but I'll briefly introduce them. <a
title="Grails - The Search is Over" href="http://www.grails.org">Grails</a> is the best web framework that I ever work with, it uses <a
title="Groovy an agile dynamic language for the Java Platform" href="http://groovy.codehaus.org">Groovy</a> and convention over configuration to simplify our development efforts. To name a few this is what you've out-of-the-box: persistence layer to save your entities to a relational database, dependency injection, lots and lots of great plugins and <acronym
title="Groovy Server Pages">GSP</acronym> to build the view.</p><p>If Grails is so complete why do I need another framework and why ZK? I'm building an enterprise web app which means it will be used by users of a company to do daily tasks, I needed a more responsiveness app without refresh and without increase the effort of getting it done. Searching for a solution I consider mainly this two frameworks: <a
href="http://www.extjs.com">ExtJS</a>, beautiful interface and a bunch of built-in components but you've to deal with javascript; <a
title="Google Web Toolkit" href="http://code.google.com/webtoolkit/">GWT</a> clever javascript compilation from Java code, but only a few built-in components and build interfaces using only java code isn't a pleasant work for me.</p><p><a
title="ZK Direct RIA" href="http://www.zkoss.org">ZK Direct RIA</a> is bundled with lots of very useful built-in components,  you can build your pages using a declarative syntax like XHTML or using Java code, since we'll use Grails we can use Groovy to simplify the java code. Your code is processed on the server and because of this you can use your classes without any modifications, all your classes groovy or java will work as is in ZK no modification is need.</p><p>ZK will be responsible to render and process the events of the view layer (the pages), the main difference compared to standard Grails is that instead of use Controllers and gsp files you'll use Composers and zul files. It doesn't mean that you can't use Controllers nor gsp anymore you can mix both without problems. From a gsp page you can go to a zul page, and there is no secret just link one to another with an &lt;a&gt; tag, for example. And it's possible to share objects between the pages as well, using Services, zkgrails plugin's Facade or with your own spring bean.</p><p>This is the first of a series of articles I'll write about my experience working with Grails and ZK. Now I'll show a very simple example of how to start using both and what we gain using both in the same project. First of all create a new grails project and install zk plugin:<span
id="more-211"></span></p><pre>$ cd &lt;path_you_want&gt;
$ grails create-app grails-and-zk-app1
    ...
    Created Grails Application at &lt;path_you_want&gt;/grails-and-zk-app1
$ cd grails-and-zk-app1
$ grails install-plugin zk 0.7.4
    ....
    Plugin zk-0.7.4 installed
    Plug-in provides the following new scripts:
    ------------------------------------------
    grails create-composer
    grails create-facade
    grails create-zul</pre><p>Your project is now created and configured to use ZK. Now I'll show you how easy is to build an rich interface with ZK and Grails, create the zul file:</p><pre>$ grails create-zul myFirstZkPage</pre><p>This will create two files the page and it's Composer, remember the composer is the ZK controller.</p><div
id="attachment_239" class="wp-caption aligncenter" style="width: 310px"><a
href="http://felipecypriano.com/blog/wp-content/uploads/2009/11/created-by-create-zul.png"><img
class="size-medium wp-image-239 " title="Created by create-zul myFirstZkPage" src="http://felipecypriano.com/blog/wp-content/uploads/2009/11/created-by-create-zul-300x298.png" alt="Created by create-zul myFirstZkPage command" width="300" height="298" /></a><p
class="wp-caption-text">Created by create-zul myFirstZkPage command</p></div><p>The plugin creates the files with a Hello World page ready to work. Execute it to see it running:</p><pre>$ grails run-app</pre><p>Open this url in your browser <em>http://localhost:8080/grails-and-zk-app1/myFirstZkPage.zul</em>. Write a text inside the text box and click on "Hello" button and a greeting text will be show. This is very simple but the implementation shows some cool features, let's see them.</p><p>This is the page <em>grails-and-zk/web-app/myFirstZkPage.zul</em>, the language is called ZUML it's a markup language to build rich interfaces every component (some tags) here has it's own Java class so you can use them in your code without any problems:</p><pre class="brush: xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" ?&gt;
&lt;?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?&gt;
&lt;?page zscriptLanguage="GroovyGrails"?&gt;

&lt;zk xmlns="http://www.zkoss.org/2005/zul"
    xmlns:h="http://www.w3.org/1999/xhtml"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul/zul.xsd"&gt;

&lt;window apply="${myFirstZkPageComposer}"&gt;

    &lt;vbox&gt;
        &lt;image src="images/grails_logo.jpg"/&gt;
    &lt;/vbox&gt;

    &lt;grid id="gdMain"&gt;
        &lt;rows&gt;
            &lt;row&gt;
                Name: &lt;textbox id="txtName" /&gt;
                &lt;button id="btnHello" label="Hello"/&gt;
            &lt;/row&gt;
        &lt;/rows&gt;
    &lt;/grid&gt;

    &lt;listbox id="lstResult" mold="paging"/&gt;
&lt;/window&gt;

&lt;/zk&gt;</pre><p>On line 11, the apply attribute tells ZK which class is the Composer of the Window component it expects the class' full qualified name. Hum, what is being passed to apply doesn't look like any full qualified name. Yes it isn't, <em>apply="${myFirstZkPageComposer}"</em> is an EL expression which is resolved to the Spring Bean named "myFirstZkPageComposer" and this bean is, as you can easily guess: <em>grails-app/composers/MyFirstZkPageComposer.groovy</em>, cool eh. Every class in composers directory which ends with "Composer" will be automatically a spring bean.</p><p>Inside the window we've three components with an id setted (lines 17, 21 and 26), looking the composer's code we can see that for each of this three components there's one attribute with the same name:</p><pre class="brush: groovy">import org.zkoss.zkgrails.*

class MyFirstZkPageComposer extends GrailsComposer {

    def txtName
    def btnHello
    def lstResult

    def myFirstZkPageFacade

    def onClick_btnHello() {
        lstResult.clear()
        lstResult.append {
            listitem { listcell { label(value: "Hello, ${txtName.value} !") } }
        }
    }

    def afterCompose = { c -&gt;
        // initialize component here
    }
}</pre><p>This mean you've full access of this components own's attributes you can read and write it's values.  For example, try to add this new line at the end of onClick_btnHello method and save it:</p><pre class="brush: groovy; toolbar: false">btnHello.label = "Hello There!"</pre><p>Run the app an see what happens when you click the Hello button. Play with the code to see what more you can do. To learn more about ZK I recommend you to read the <a
href="http://docs.zkoss.org/wiki/Documentation">documentation page</a> specially the Developer's Guide and Developer's Reference. Use your curiosity to make great things <img
src='http://felipecypriano.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>In the next articles I'll enter in more details.</p><p><strong># Update 1</strong></p><p><a
href="http://felipecypriano.com/blog/2009/11/19/grails-with-zk-where-are-my-controllers/">ZK with Grails: Where are my controllers?</a> Learn what is and how to use ZK Composers.</p> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2009/11/07/grails-with-zk-understanding-both-together/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Tweak ZK to make event processing call groovy’s invokeMethod</title><link>http://felipecypriano.com/blog/2009/10/26/tweak-zk-to-make-event-processing-call-groovys-invokemethod/</link> <comments>http://felipecypriano.com/blog/2009/10/26/tweak-zk-to-make-event-processing-call-groovys-invokemethod/#comments</comments> <pubDate>Mon, 26 Oct 2009 11:32:50 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[ZK Direct RIA]]></category> <category><![CDATA[groovy]]></category> <category><![CDATA[zk]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=149</guid> <description><![CDATA[My current project needs a very dynamic and fast pages without refreshs, or using the buzz word ajax, to accomplish this requirement I'm using ZK Direct RIA. As ZK heavily uses ajax requests with unpredictable url I need another way to protect the controller's actions (composer's method) instead of url. Using @Secured and groovy's invokeMethod I was [...]]]></description> <content:encoded><![CDATA[<p>My current project needs a very dynamic and fast pages without refreshs, or using the buzz word ajax, to accomplish this requirement I'm using <a
href="http://www.zkoss.org/">ZK Direct RIA</a>. As ZK heavily uses ajax requests with unpredictable url I need another way to protect the controller's actions (composer's method) instead of url. <a
href="http://felipecypriano.com/blog/2009/10/19/enable-secured-annotation-with-grails-spring-security-plugin/">Using @Secured and groovy's invokeMethod I was able to protect each method of any class</a> (please read the post to get a better picture of what I'll discuss) which works fines if the method call is from a groovy code, ZK is fully implemented in java though.</p><p>When a user clicks on a button, or does anything that generates events, zk process it and call the corresponding method in the composer class. ZK events processing executes this code when it find the method to call:</p><pre class="brush: java;toolbar: false">mtd.invoke(controller, new Object[] {evt});</pre><p>This uses Java Reflection API and completely bypass groovy's invokeMethod, what we need to do is use groovy's InvokerHelper class instead of direct calling the method using reflection.</p><pre class="brush: java;toolbar: false">InvokerHelper.invokeMethod(controller, mtd.getName(), new Object[] {params});</pre><p>Now that we know how to do it for any kind of java code let's dig into the problem with ZK event and find out where we should use InvokerHelper.<span
id="more-149"></span></p><h2>Implementing InvokerHelper in GrailsComposer</h2><p>The GrailsComposer in ZKGrails plugin is a subclass of GenericForwardComposer that changes the  default char separator from '$' to '_', because groovy already uses the '$' with another meaning, and allows the use of a closure as the <a
href="http://www.zkoss.org/javadoc/3.6.1/zk/org/zkoss/zk/ui/util/GenericAutowireComposer.html#doAfterCompose(org.zkoss.zk.ui.Component)">doAfterCompose method</a>. So when you create a new composer using <em>grails create-composer &lt;composer name&gt;</em> your new class extends GrailsComposer. Let's create a composer and protect two of it's buttons.</p><pre class="brush: groovy">import org.springframework.security.annotation.Secured
class MainAreaComposer extends GrailsComposer {
    private Button btnEditText // automatically wired from the zul file
    private Button btnSaveText
    private Button btnCancelText

    def afterCompose = {
        // loads the current text
    }

    @Secured("mainArea_editText")
    public void onClick_btnEditText() {
        // shows the rich text editor to edit the text
        btnSaveText.visible = true
        btnCancelText.visible = btnSaveText.visible
        btnEditText.visible = false
    }

    @Secured("mainArea_editText")
    public void onClick_btnSaveText() {
        // saves the text, hide the editor and load the new text
         btnSaveText.visible = false
         btnCancelText.visible = btnSaveText.visible
         btnEditText.visible = true
    }

    public void onClick_btnCancelText(){
         // hide the editor and loads the text without any modifications
    }
}</pre><p>The idea here is that only some users have access to edit the text. ZK is fully ajax based and every event cames from client through javascript request. Because of this even if the btnEditText is invisible a malicious users could forge a request to call the method - not easy, but possible - the use of @Secured is to assure that an attempt to call this method from an unauthorized user will fail.</p><p>If you run your app using ZKGrails 0.7.5, the current version for Grails 1.1.1, and test if an unauthorized user fails when call the method - just make the button always visible to test - you will see that nothing is blocked no AccessDeniedException is thrown, and of course this isn't good. Humm, and how could we solve this? How to make zk event handling aware of the dynamic methods?</p><p>My first thought was "ZK is open source, what about reading it's code to understand the event system?" and there I go, downloaded the source and start reading how ZK maps the methods name to components event, in other words how it does this magic:</p><pre class="brush: groovy;toolbar: false">public void onClick_btnCancelText() {// event code}</pre><p>The above method is the same as the not so nice:</p><pre class="brush: groovy;toolbar: false">btnCancelText.addEventListener("onClick", {// event code} as EventListener)</pre><p>Reading the source code I find out that this kind of event is a <a
href="http://www.zkoss.org/javadoc/3.6.1/zk/org/zkoss/zk/ui/event/ForwardEvent.html">ForwardEvent</a> but I couldn't find where the original method is called until I look the class diagram for GrailsComposer:</p><div
id="attachment_183" class="wp-caption aligncenter" style="width: 310px"><a
href="http://felipecypriano.com/blog/wp-content/uploads/2009/10/GrailsComposer-class-hierarchy.png"><img
class="size-medium wp-image-183 " title="GrailsComposer class hierarchy" src="http://felipecypriano.com/blog/wp-content/uploads/2009/10/GrailsComposer-class-hierarchy-300x149.png" alt="GrailsComposer class hierarchy" width="300" height="149" /></a><p
class="wp-caption-text">GrailsComposer class hierarchy</p></div><p>And there was the solution GenericEventListener onEvent method, I've finally found where the original method (onClick_componentId) is invoked and now we just need to override onEvent in GrailsComposer, this is the implementation:<br
/> <em>org/zkoss/zkgrails/GrailsComposer.java</em></p><pre class="brush: java">    /**
     * Overrides GenericEventListener to use InvokerHelper to call methods. Because of this the events are now
     * part of groovy's dynamic methods, e.g. metaClass.invokeMethod works for event methods.
     * @param evt
     * @throws Exception
     */
    @Override
	public void onEvent(Event evt) throws Exception {
		final Object controller = getController();
		final Method mtd =	ComponentsCtrl.getEventMethod(controller.getClass(), evt.getName());
		if (mtd != null) {
			if (mtd.getParameterTypes().length == 0) {
                InvokerHelper.invokeMethod(controller, mtd.getName(), null);
            } else if (evt instanceof ForwardEvent) { //ForwardEvent
				final Class paramcls = (Class) mtd.getParameterTypes()[0];
				//paramcls is ForwardEvent || Event
				if (ForwardEvent.class.isAssignableFrom(paramcls)
				|| Event.class.equals(paramcls)) {
                    InvokerHelper.invokeMethod(controller, mtd.getName(), new Object[] {evt});
				} else {
					do {
						evt = ((ForwardEvent)evt).getOrigin();
					} while(evt instanceof ForwardEvent);
                    InvokerHelper.invokeMethod(controller, mtd.getName(), new Object[] {evt});
				}
			} else {
                InvokerHelper.invokeMethod(controller, mtd.getName(), new Object[] {evt});
            }
		}
	}</pre><p>Just replacing method.invoke to InvokerHelper.invokeMethod (lines 13, 19, 24 and 27) is enough to make the methods actually secured. Open your GrailsComposer class and add this method to the class, this is all you need to do. If you don't understand how the @Secured is now working, read the <a
title="Enable @Secured annotation with Grails Spring Security plugin" href="http://felipecypriano.com/blog/2009/10/19/enable-secured-annotation-with-grails-spring-security-plugin/">previous post</a> which is about the implementation of @Secured.</p><p>I've submitted this as a patch to Chanwit, the plugin's maintainer, and ZKGrails 1.0 will have this overridin onEvent out-of-the-box. No need to change the plugin source code anymore, great news.</p> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2009/10/26/tweak-zk-to-make-event-processing-call-groovys-invokemethod/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Enable @Secured annotation with Grails Spring Security plugin</title><link>http://felipecypriano.com/blog/2009/10/19/enable-secured-annotation-with-grails-spring-security-plugin/</link> <comments>http://felipecypriano.com/blog/2009/10/19/enable-secured-annotation-with-grails-spring-security-plugin/#comments</comments> <pubDate>Mon, 19 Oct 2009 20:46:15 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[groovy]]></category> <category><![CDATA[security]]></category> <category><![CDATA[spring]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=136</guid> <description><![CDATA[How could I protect each method of my classes? Using Spring Security it should be easy, right? After a quick search I realize that the best way is to use @Secured annotation, good! Another issue fixed. But as life isn't fun without problems to solve it didn't work as expected.
The problem started because grails acegi [...]]]></description> <content:encoded><![CDATA[<p>How could I protect each method of my classes? Using Spring Security it should be easy, right? After a quick search I realize that the best way is to use <a
href="http://static.springsource.org/spring-security/site/apidocs/org/springframework/security/annotation/Secured.html">@Secured</a> annotation, good! Another issue fixed. But as life isn't fun without problems to solve it didn't work as expected.</p><p>The problem started because grails acegi plugin, in version 0.5.2, doesn't support this annotation.<a
href="http://www.nabble.com/How-can-I-activate-%40Secured-from-Spring-Security--td25878294.html">Talking about this in grail user mailing list</a> Benjamin Doerr gave me a nice idea: use <a
title="Using invokeMethod and getProperty" href="http://groovy.codehaus.org/Using+invokeMethod+and+getProperty">groovy's invokeMethod</a> to add the support that I needed.</p><p>The idea is to use groovy meta magic to add behavior to the classes that have at least one method annotated, we well override the metaClass.invokeMethod of the class we want to enable the annotation. To keep things organized I create a new boot strap file in <em>grail-app/conf/SecurityBootStrap.groovy</em> and all the related code is place in this file.</p><p>First off all let's create a closure that can be used to override invokeMethod of any class:<span
id="more-136"></span></p><pre class="brush: groovy">    def verifyMethodAccess = {String name, args -&gt;
        def method = delegate.metaClass.getMetaMethod(name, args)
        def logMsg = new StringBuilder("invoking ${method}, ")
        if (method) {
            def annotation = method.cachedMethod.getAnnotation(Secured)
            logMsg += "is @Secured ${annotation != null}"
            if (annotation) {
                def annotationValue = annotation.value()?.toString()?.replaceAll(~/[\[-\]]/, '') // remove [ and ]
                logMsg += " by ${annotationValue}"
                if (!authenticateService?.ifAnyGranted(annotationValue)) {
                    log.debug logMsg.toString()
                    throw new AccessDeniedException("Access denied to ${delegate.class.simpleName}.${name} from user ${authenticateService.principal()?.username}")
                }
            }
            log.debug logMsg.toString()
            return method.invoke(delegate, args)
        }

        log.error "Method ${delegate.class.simpleName}.${name} not found"
        return null
    }</pre><p>In a glance this closure gets the <a
title="MetaMethod API" href="http://groovy.codehaus.org/api/groovy/lang/MetaMethod.html">method</a> that is been invoked and verifies if this method is annotated with @Secured annotation, if it does then the granted authorities passed to the annotation's value is obtained - line 8 - and is passed to the authenticationService if the current user has access the method is invoked otherwise an AccessDeniedException is thrown.</p><p>To active this behavior in a class we only need to override it's metaClass.invokeMethod:</p><pre class="brush: groovy">import org.springframework.security.annotation.Secured
import org.springframework.security.AccessDeniedException

public class SecurityBootStrap {
    def init = {servletContext -&gt;
        ClassifiedClass.metaClass.invokeMethod = verifyMethodAccess
    }
    // verifyMethodAccess declaration and body goes here
}</pre><p>To complete the example this is the ClassifiedClass:</p><pre class="brush: groovy">public class ClassifiedClass {
    @Secured("ROLE_PRESIDENT")
    String protectedMethod() {
        "I'm a top classified information!"
    }

    def ordinaryMethod() {
        "Anyone can call me."
    }
}</pre><p>Every time a groovy code calls any method of ClassifiedClass it's metaClass.invokeMethod will be executed before the actual method. Just pay attention to use the same Secured annotation in your class and in SecurityBootStrap.</p><p>Unfortunately this solution only works if the call came from groovy code, if any java code calls classifiedObj.protectedMethod() it will succeed even without permission. Java code completely ignores the invokeMethod. Now stop thinking that you read all of this for nothing, because on next post I'll talk about using <a
href="http://groovy.codehaus.org/api/org/codehaus/groovy/runtime/InvokerHelper.html">InvokerHelper</a> class to make java code obey the law.</p><p><strong># Update 1</strong></p><p>Read this <a
href="http://felipecypriano.com/blog/2009/10/26/tweak-zk-to-make-event-processing-call-groovys-invokemethod/">post to see how to make java code be aware of groovy's dynamic method</a>, including invokeMethod.</p> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2009/10/19/enable-secured-annotation-with-grails-spring-security-plugin/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Customizing SpringSecurity to protect each button of a page using Grails Acegi plugin</title><link>http://felipecypriano.com/blog/2009/10/14/customizing-springsecurity-to-protect-each-button-of-a-page-using-grails-acegi-plugin/</link> <comments>http://felipecypriano.com/blog/2009/10/14/customizing-springsecurity-to-protect-each-button-of-a-page-using-grails-acegi-plugin/#comments</comments> <pubDate>Wed, 14 Oct 2009 22:36:57 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[security]]></category> <category><![CDATA[spring]]></category><guid isPermaLink="false">http://felipecypriano.com/blog/?p=27</guid> <description><![CDATA[I'm very happy with grails acegi plugin, aka Spring Security Plugin,  but on my newest project I needed a finner grained way to do control access than using simple urls filters and roles.
I wanted a way to control which button, link, action of the current page the user can access. If the user has only [...]]]></description> <content:encoded><![CDATA[<p>I'm very happy with grails <a
href="http://grails.org/plugin/acegi">acegi plugin</a>, aka Spring Security Plugin,  but on my newest project I needed a finner grained way to do control access than using simple urls filters and roles.</p><p>I wanted a way to control which button, link, action of the current page the user can access. If the user has only read access to a page than the page is shown but edit action isn't, because of this requirement using only roles to grant access isn't enough and could easily became a mess if I create one role per action. Use urls filters won't work because most urls are generated by <a
href="http://www.zkoss.org/">ZK framework</a> and hence are non predictable.</p><p>The solution is fully based on SpringSecurity capabilities and should work on every project that uses it independent of plugins or frameworks that I use. Since spring security plugin does the hard work for us, we just need to create two more classes besides acegi's default user and role and extends <a
href="http://static.springsource.org/spring-security/site/apidocs/org/springframework/security/userdetails/UserDetailsService.html">UserDetailsService</a> interface. This is based on <a
title="Stephan's ZK Sample Project" href="http://code.google.com/p/zk-sample-db/">zk_sample project</a> and is a database implementation of this <a
title="Spring Security customization (Part 1 – Customizing UserDetails or extending GrantedAuthority)" href="http://blog.springsource.com/2009/01/02/spring-security-customization-part-1-customizing-userdetails-or-extending-grantedauthority/">article by Oleg Zhurakousky</a>.</p><h3><span
id="more-27"></span>The database schema</h3><p>The plugin needs User and Role class by default, to extend (not meaning inheritance) them I create two new classes to add more control over which resource can be accessed namely: Group and Access. The Group class purpose is only to organize the Access, since there will be a lot of them. It's important to notice that the <strong>access' name and the role's authority must be unique</strong>.</p><div
id="attachment_68" class="wp-caption aligncenter" style="width: 323px"><img
class="size-full wp-image-68" title="security_class_diagram" src="http://felipecypriano.com/blog/wp-content/uploads/2009/10/security_class_diagram1.png" alt="User, Role, Group and Access class diagram" width="313" height="173" /><p
class="wp-caption-text">User, Role, Group and Access class diagram</p></div><p>With this classes we can create roles that contains a list of granted accesses, for instance:</p><ul><li>ROLE_ADMIN<ul><li>pagePolicy.btnNew</li><li>pagePolicy.btnSave</li><li>pagePolicy.btnDelete</li></ul></li><li>ROLE_ORDINARY<ul><li>pagePolicy.btnNew</li></ul></li></ul><p>With our granted access setup in database we need to teach spring security how to authorize an access based on the access name:</p><pre class="brush: groovy; toolbar: false">authenticateService.ifAllGranted "ROLE_ADMIN" //  works out of the box
authenticateService.ifAllGranted "pagePolicy.btnNew" //  don't work</pre><p>The goal is to make both options works, to do this we need to provide a custom implementation of UserDetailsService which will load to the UserDetails object both roles and accesses as <a
title="GrantedAuthority API" href="http://static.springsource.org/spring-security/site/apidocs/org/springframework/security/GrantedAuthority.html">GrantedAuthority</a>. Let's <a
title="Customizing UserDetailsService" href="http://www.grails.org/AcegiSecurity+Plugin+-+Custom+UserDetailsService">customize</a> spring security and extend <a
title="GrailsDaoImpl source code" href="http://plugins.grails.org/grails-acegi/trunk/src/groovy/org/codehaus/groovy/grails/plugins/springsecurity/GrailsDaoImpl.groovy">GrailsDAOImpl</a> to add our logic:</p><p><em>src/groovy/HierachyUserDetailsService.groovy</em></p><pre class="brush: groovy">public class HierachyUserDetailsService extends GrailsDaoImpl {
    protected GrantedAuthority[] loadAuthorities(user, String username, boolean loadRoles) {
        if (!loadRoles) {
        	return []
        }

        def accessCriteria = Access.createCriteria()
        // get all the accesses for this user
        def accesses = accessCriteria.list {
            authorizedGroups {
                authorizedRoles {
                    users {
                        eq("login", username)
                    }
                }
            }
        }

        // now we iterate over the accesses to get the roles associated to each access
        def allAuthorities = [] as Set
        accesses.each { access -&gt;
            def roles = [] as Set
            access. authorizedGroups*. authorizedRoles*.each { role -&gt;
                roles &lt;&lt; new GrantedAuthorityImpl(role.authorityValue)
            }

            allAuthorities.addAll(roles)
            allAuthorities &lt;&lt; new AccessGrantedAuthority(access.name, roles)
        }
        log.debug "Authorities for user ${username}: ${allAuthorities}"

        return allAuthorities as GrantedAuthority[]
    }
}</pre><p>GrailsDaoImpl already implements UserDetailsService interface and provide a very good set of methods we just need to override one of them to achieve our goal. Great.</p><p>The <a
title="AccessGranteduthority source code" href="http://felipecypriano.com/blog/wp-content/uploads/2009/10/AccessGrantedAuthority.groovy">AccessGrantedAuthority</a> (line 28) is just to make it easier to debug from which role the access came from. See the log debug output using this class:</p><blockquote><p>Authorities for user admin: [ROLE_ADMIN, ROLE_ORDINARY, pagePolicy.btnNew[ROLE_ADMIN, ROLE_ORDINARY], pagePolicy.btnSave[ROLE_ADMIN], pagePolicy.btnDelete[ROLE_ADMIN]]</p></blockquote><p>If don't want this information you could use the default implementation, GrantedAuthorityImpl as in line 24.</p><p>Now that we have our implementation the last step is to configure our implementation as the current implementation used by Spring Security:</p><p><em>grails-app/conf/spring/resources.groovy</em></p><pre class="brush: groovy">import org.codehaus.groovy.grails.plugins.springsecurity.AuthorizeTools
beans = {
    // Spring Security
    def securityConf = AuthorizeTools.securityConfig.security
    userDetailsService(br.com.litoraltextil.vc.springsecurity.AuthorityHierachyUserDetailsService) {
        usernameFieldName = securityConf.userName
        passwordFieldName = securityConf.password
        enabledFieldName = securityConf.enabled
        authorityFieldName = securityConf.authorityField
        loginUserDomainClass = securityConf.loginUserDomainClass
        relationalAuthoritiesField = securityConf.relationalAuthorities
        authoritiesMethodName = securityConf.getAuthoritiesMethod
        sessionFactory = ref('sessionFactory')
        authenticateService = ref("authenticateService")
    }
}</pre><p>As a full configuration of spring security plugin isn't the focus of this post I suggest you to read <a
href="http://www.grails.org/AcegiSecurity+Plugin+-+Customizing+with+SecurityConfig">how to customize the plugin using SecurityConfig</a>.</p><p>Finally we can use all the <a
title="AcegiSecurity Plugin - Artifacts" href="http://www.grails.org/AcegiSecurity+Plugin+-+Artifacts">artifacts</a> using both the role name or the access name, some examples:</p><pre class="brush: html; toolbar: false">&lt;g:ifAllGranted role="ROLE_ADMIN"&gt;secure stuff here&lt;/g:ifAllGranted&gt;
&lt;g:ifAllGranted role="ROLE_ADMIN, aAccess.name"&gt;secure stuff using both&lt;/g:ifAllGranted&gt;</pre>]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2009/10/14/customizing-springsecurity-to-protect-each-button-of-a-page-using-grails-acegi-plugin/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Solving Grails/GORM data truncation error on blob column using Java</title><link>http://felipecypriano.com/blog/2009/10/09/solving-grailsgorm-data-truncation-error-on-blob-column-using-java/</link> <comments>http://felipecypriano.com/blog/2009/10/09/solving-grailsgorm-data-truncation-error-on-blob-column-using-java/#comments</comments> <pubDate>Fri, 09 Oct 2009 21:33:27 +0000</pubDate> <dc:creator>Felipe Cypriano</dc:creator> <category><![CDATA[Groovy / Grails]]></category> <category><![CDATA[gorm]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[hibernate]]></category> <category><![CDATA[java]]></category><guid isPermaLink="false">http://blog.felipecypriano.com/?p=3</guid> <description><![CDATA[Today GORM was in a bad mood and refuses to insert a text in a blob (clob) column. If a set a non null value in the attribute which was mapped to a blob field I end up with this strange error:
Caused by: java.sql.DataTruncation: Data truncation
Data truncation for a blob column makes no sense since [...]]]></description> <content:encoded><![CDATA[<p>Today GORM was in a bad mood and refuses to insert a text in a blob (clob) column. If a set a non null value in the attribute which was mapped to a blob field I end up with this strange error:</p><blockquote><p>Caused by: java.sql.DataTruncation: Data truncation</p></blockquote><p>Data truncation for a blob column makes no sense since blobs are made to handle large amount of data, as far as I know the limit is your storage space.</p><p>What I needed was an improved version of the Setting class that cames with <a
href="http://grails.org/plugin/settings">settings plugin</a>, I wanted to store large texts in some settings, larger the 100 characters which is the current limit, so I create a new attribute to store large texts, this new attribute is a blob in the dabase.</p><p><span
id="more-3"></span>Here is the new grails domain class that I created:</p><p><em>grails-app/domain/Setting.groovy</em></p><p><code> </code></p><p><code> </code></p><p><code></p><pre class="brush: groovy">class Setting {
    String code
    String content
    String largeText

    static constraint {
        code(length: 100)
        content(length: 255)
    }
    static mapping {
         largeText type: “text”
    }

    public static final String LARGE_TEXT = “large_text”
    public String getContent(){
       content != LARGE_TEXT ? content : largeText
    }

    public void setContent(String value) {
        if (value &amp;&amp; value.size() &gt; 255) {
            this.content = LARGE_TEXT
            largeText = value
        } else {
            this.content = value
            largeText = null
        }
    }
}</pre><p></code></p><p>This is the logic behind the class, very simple and effective. The problem begun when I set a content bigger than 255 characters and call save()... boom java.sql.DataTruncation.</p><p>After searching for a solution, and asking in the mailing list, I don’t find an answer. So I decide to make the mapping the way I was sure it works: using annotations and POJO. Then I create a java class instead of a groovy one,  obvious parts are omitted:</p><p><em>src/java/entity/Setting.java</em></p><p><code> </code></p><p><code> </code></p><p><code></p><pre class="brush: java">package entity;
// don’t forget the imports
@Entity
public class Setting implements Serializable {
    @Column(length = 100, unique = true)
    private String code;
    @Column(length = 255)
    private String content;
    @Lob
    private String largeText;

    // Getters and setters, the ones for content are identical the groovy version
}</pre><p></code></p><p>Ok, the POJO is here but how will it work with grails and all its great features, like <a
href="http://www.grails.org/DomainClass+Dynamic+Methods">dynamic finders</a>?</p><p>It’s very simple just tell Hibernate, which is under the hood in Grails, that you want to map the Setting class. Open the file <em>grails-app/conf/hibernate/hibernate.cfg.xml</em> and configure it like this:</p><pre class="brush: xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC '-//Hibernate/Hibernate Configuration DTD 3.0//EN'
        'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'&gt;
&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;mapping class="entity.Setting" /&gt;
    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;</pre><p>And voilà your POJO is now a full-blown Grails domain class. For now on you can call the dynamic finders, save method and everything:</p><p><code> </code></p><p><code></p><pre class="brush: groovy; toolbar: false">Setting.findByCode(“your.setting”)
settingObj.save()</pre><p></code></p><p>This is how I solved a problem with GORM and blob columns. I belive that I need to do all this because of the database I'm using in this project, which is Firebid 2.1. After all what matters is how great is groovy/grails integration with plain java. <img
src='http://felipecypriano.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /></p> ]]></content:encoded> <wfw:commentRss>http://felipecypriano.com/blog/2009/10/09/solving-grailsgorm-data-truncation-error-on-blob-column-using-java/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss><!-- This site's performance optimized by W3 Total Cache. Dramatically improve the speed and reliability of your blog!

Learn more about our WordPress Plugins: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk
Database Caching using memcached

Served from: apache2-quack.cannons.dreamhost.com @ 2010-03-15 10:19:15 -->
