<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>The Integrallis Blog : Category grails, everything about grails</title>
    <link>http://www.integrallis.com/blog/category/grails.rss</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Musings on Ruby, Groovy, Java and programming in general</description>
    <item>
      <title>Using GORM to Boost Legacy Spring Applications</title>
      <description>&lt;h3&gt;Using GORM with your Spring application can increase the productivity and readability of your code&lt;/h3&gt;

&lt;p&gt;Groovy and Grails has stormed the Java world as the new way to create reliable Web 2.0 applications in a concise and fast manner. The ability to go from the start of a project to the end, especially for a smaller demo, is exponentially faster. This is due to the many features of Grails. Out of the box applications are easier to build, create, test, and deploy because of the convention over configuration methodology. In addition Grails is written in Groovy, a dynamic language that can run on the JVM and interact as if they were Java classes. Groovy gives the power to write dynamic code with power and features that are normally unavailable in Java. Possibly the best example of this power in Groovy and Grails is the creation of the Grails Object Relational Mapper (GORM). &lt;/p&gt;

&lt;p&gt;However, we can&#8217;t all just go to our managers and say &#8220;Hey, let&#8217;s rewrite this entire application in Grails&#8221;. We would more than likely get laughed out the door. At many companies it also isn&#8217;t feasible to ask for an entire framework shift. However, most of us can request &#8220;small changes&#8221;, especially if they help save time. &lt;/p&gt;

&lt;p&gt;With Spring 2.0 and above we can create Spring beans out of Groovy objects. This gives us a nice ability to use Groovy nomenclature in our Spring code (e.g. the Meta Object Programming (MOP), cleaner syntax, etc). However, what we do not get with straight Groovy is a better way to interact with the database. For that we need the power of GORM. With Grails 1.1 that has become significantly easier.&lt;/p&gt;

&lt;h3&gt;Why Do I Want To Use GORM?&lt;/h3&gt;

&lt;p&gt;You may be familiar with Hibernate and wonder why you should bother with GORM. Hibernate is a GREAT ORM, and the framework has been developed steadily since its inception. While Spring&#8217;s wrapping of Hibernate has made it easier to interact with the database, it is still missing the readability and ease of use that most modern developers want.  The following example demonstrates how GORM brings simplicity to Hibernate code. (Please note that although GORM derives from Hibernate any mention of Hibernate here will specifically be in reference to the pure Java Hibernate form.)&lt;/p&gt;

&lt;p&gt;This example starts by performing a simple query to retrieve items from the Todo table in the database where name and description matched some given text. When using Spring&#8217;s Hibernate Template, the code would look something like this:&lt;/p&gt;

&lt;pre class="brush: java;"&gt;
public List find(final String name, final String desc) {
final String hqlQuery =         
    "select t from Todo t where t.name = :name and t.description = :desc";
    return (List) getHibernateTemplate().execute(new HibernateCallback() {
    public Object doInHibernate(Session session) throws HibernateException {
        Query query = session.createQuery(hqlQuery);      
        query.setString("name", name);
        query.setString("desc", desc);
        return query.list();
    }
});    
}
&lt;/pre&gt;

&lt;p&gt;Listing NUS-1&lt;/p&gt;

&lt;p&gt;While this code does the job, something more readable would not only make it easier for everyone to understand, but would also cut down on time and errors.&lt;/p&gt;

&lt;p&gt;Now if we were using Java Persistence API (JPA) supported queries we could make the code in Listing NUS-1 a bit simpler as shown in Listing NUS-2.&lt;/p&gt;

&lt;pre class="brush: java;"&gt;
@PersistenceContext
EntityManager manager;

public List find(final String name, final String desc) {
    final String hqlQuery =         
        "select t from Todo t \
        where t.name = :name and t.decscription = :desc";
    return manager.createQuery(hqlQuery)
        .setParameter(&#8220;name&#8221;, name)
        .setParameter(&#8220;desc&#8221;, desc)
        .returnResultList();
}
&lt;/pre&gt;

&lt;p&gt;Listing NUS-2&lt;/p&gt;

&lt;p&gt;This is more concise and fairly readable, but several queries in a row would require repeating the same block of code many times with slight alterations and would increase our time and effort to do so. You may be asking yourself what is the problem with this? After all I am sure many of you have witten similar or even more verbose code before. The problem lies in the fact that code should be easily readable. As good developers we want to concern ourselves with the business logic, using the write tools. We shouldn&#8217;t have to spend too much of our time deciphering easy parts of the code, and queries to the database are often just that. Using GORM helps us to solve that problem, and here&#8217;s how.&lt;/p&gt;

&lt;p&gt;Let&#8217;s take what that code is doing and write it in English. The code is wanting to query the Todo table to find all by name and description. Well how do we write that out? How about this:&lt;/p&gt;

&lt;pre class="brush: java;"&gt;Todo.findAllByNameAndDesc(name, desc)&lt;/pre&gt;

That is simple, concise, and in GORM that line is actual code. This begins to show the ease of using GORM over Hibernate and we will expand on that concept when using Criteria queries later. But first, let&#8217;s see how to use GORM in our Spring application.

### Injecting GORM

The interesting thing about writing an article on Using GORM with Spring is that there is barely enough setup required to fill a blog entry, let alone an entire article. In fact, you could almost Twitter the entire extra XML needed; however, for the purpose of learning we are going to go into a bit more detail. We will show not only how to set up GORM in Spring but also various options when using Spring. This will require configuring the Spring beans, installing the right JARs, and, most importantly, understanding the various ways to use GORM in your application.

### Configuring the Spring Beans
We are going to go over in this section the necessary modifications to the spring files needed for using GORM with Spring. The modifications here will be to your bean configurations and are independent of whether you are using Spring in web environment or a standalone application. That being said of course if you were to be using Spring in a web environment no modifications are needed for the web specific files (like web.xml)
The first thing to do is to add an XML namespace to your bean configuration. This one is specifically for GORM:
xmlns:gorm="http://grails.org/schema/gorm" 

Once the namespace is set you will be able to use the GORM Session Factory instead of the Hibernate Session Factory. Listing NUS-3 is an example of the GORM bean definition that would go into your bean definition file..

&lt;pre class="brush: java;"&gt;
 &lt;gorm:sessionFactory 
     base-package="com.integrallis.demo.domain"
     data-source-ref="dataSource"
     message-source-ref="messageSource"&gt;
     &lt;property name="hibernateProperties"&gt;
        &lt;util:map&gt;
          &lt;entry key="hibernate.hbm2ddl.auto" value="update"/&gt;
      &lt;/util:map&gt;
     &lt;/property&gt; 
 &lt;/gorm:sessionFactory&gt;
&lt;/pre&gt;

&lt;p&gt;Listing NUS-3&lt;/p&gt;

&lt;p&gt;Luckily, this listing isn't too complicated. Often times with Spring beans one has to define the classes being used; however, with the use of XML namespaces that is not necessary Spring is aware based on the namespace used  With that being said Listing NUS-3 serves the same purpose as your standard Hibernate definitions usually do in Spring and that is to define the Session Factory. In fact, most of the items defined will be similar to Hibernate Session Factory listings.&lt;/p&gt;

&lt;p&gt;Line 1 is the name space reference to the GORM Session Factory, which is fairly standard stuff. The rest really is general Hibernate type configurations that are specific to GORM. Line 2 is used to specify where your domain objects exist.  Remember, with Hibernate you have to define your domain objects. There are basically two ways to do this: one is to define a directory full of hibernate XML mapping files, the other is to specify a directory of domain objects. Line 3, data-source-ref, references a data source that you have defined in Spring. This can be a Java Naming and Directory Interface (JNDI) data source, in memory data source or a more database specific data source. Line 4, message-source-ref, is specific to GORM itself. GORM allows one to define validation constraints in its domain, these constraints then print out messages via a message resource bundle. In Grails this message resource bundle is a predefined name and area, with GORM you will have to specify that item yourself. In GORM these validators are in a specific place with a specific name, but with Spring one can customize the location and name of this resource bundle. On line 5 we start to define the Hibernate properties.  If you were using Grails these items would be specified inside your DataSource.groovy file and if you were using JPA would be in the persistence.xml file.&lt;/p&gt;

&lt;h3&gt;JAR Files Needed&lt;/h3&gt;

&lt;p&gt;In addition to defining the GORM Session Factory we will also need a few of the Grails JAR files to make this work. Only three jars from Grails are needed and can be included either manually or via your Ivy/Maven configurations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;grails-bootstrap 1.1&lt;/li&gt;
&lt;li&gt;grails-gorm 1.1&lt;/li&gt;
&lt;li&gt;grails-web 1.1&lt;/li&gt;
&lt;/ul&gt;</description>
      <pubDate>Tue, 08 Sep 2009 20:36:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:9340e9fd-049e-489d-9e46-d357d7164f02</guid>
      <comments>http://www.integrallis.com/blog/2009/09/08/using-gorm-to-boost-legacy-spring-applications#comments</comments>
      <category>Java</category>
      <category>Spring</category>
      <category>Groovy</category>
      <category>Grails</category>
      <category>gorm</category>
      <category>Groovy</category>
      <category>Grails</category>
      <category>spring</category>
      <category>Java</category>
      <category>orm</category>
      <link>http://www.integrallis.com/blog/2009/09/08/using-gorm-to-boost-legacy-spring-applications</link>
    </item>
    <item>
      <title>JSecurity Permissions in Grails</title>
      <description>&lt;p&gt;One of the security plugins I have looked at with the most interest is the JSecurity plugin. I was attracted to the JSecurity because it seemed to provide a good mix of out of the box support but also being flexible enough for customizations.&lt;/p&gt;

&lt;p&gt;On the surface JSecurity provides much of the normal security you'd expect from any framework. There is out of the box support for login/logout authentication, support for role based lock downs, and finally even the ability to create permission based security. It's the last one I wanted to write about.&lt;/p&gt;

&lt;p&gt;Understanding how to do normal authentication with JSecurity and implementing roles is pretty straight forward and the documentation on the grails wiki found &lt;a href="http://www.grails.org/JSecurity+Plugin+-+Quick+Start"&gt;here&lt;/a&gt;. Where I believe the documentation lacks a bit on is using permissions. That being said, the documentation on the wiki is very good at understanding WHAT permissions are and creating custom ones but not necessarily how to create basic ones in the first place.&lt;/p&gt;

&lt;p&gt;I am going to assume you have all used JSecurity or can go to the previous URL and read about it and will discuss implementing permissions for JSecurity. Sometimes knowing when to use permissions can be rather complex. And sometimes justifiably so, the way to use permissions (and of course there are many ways to use them) is when you keep needing to fine tune access to a particular source on a per user basis. Take a typical web application with a user list. We may want to allow someone to have read access to the list, another to have read and write, and another to have read, write, delete. To perform this check with roles we would basically have to have 3 different roles and assign them when needed. The problem with this solution is it basically gets messy fast especially if you have quite a bit of resources you want to lock down in this way. Permissions are designed to solve this problem exactly, by allowing a finer grain access on a resource. Let's dive into how to create permissions in JSecurity.&lt;/p&gt;

&lt;p&gt;How do we perform this in Grails with JSecurity? JSecurity essentially has three tables that handle permissioning: JsecPermission, JsecUSerPermissionRel, and JsecUserRoleRel. We will look at how these tables are going to help us create and lock down pages on a per user basis.&lt;/p&gt;

&lt;p&gt;Let's first discuss how JSecurity interprets permisssions to begin with. JSecurity permission is more complex than some because it does not force one to treat every resource (ie: web page, file system, specific part of the app) equally. JSecurity allows you to define what the permission resource IS in the first place. For example the permission logic for a web URL like our in example of a user page, to-do page, etc would differ from a file resource if you were creating a documentation management site. The wiki for the JSecurity shows examples of a FilePermission or a ProjectPermission, anything that implements the Permission interface. Each of these classes will have an implies() methods that actually determines HOW one is to interpret the permission. This is great because it gives the user the maximum flexibilty in determining how they want there permission applied. Now while i say that is great, let's face it most of us are going to use permissions for as I described above in Grails, to lock down a particular controller / action. The good news is out of the box Grails JSecurity plugin provides a specialized permission for controller based security. They have what is called a basic permission 'org.jsecurity.grails.JsecBasicPermission'. This permission is good for when you want to apply the concept of controller / action security. And it is this particular use case I am going to show how to use below.&lt;/p&gt;

&lt;p&gt;To start with even though we have the permission as a resource on the class path its name needs to be stored to the database so the system can do reflection on it later. The first table we need to add to is the JsecPermission table. This table is simply going to keep a list of all the permission classes we have and the possible actions for each. So for our controller / action lockdowns we will simply add a reference to the JsecBasicPermission into the database:&lt;/p&gt;

&lt;h3&gt;Creating the Database Permission&lt;/h3&gt;

&lt;pre class="brush: groovy;"&gt;
def perm = new JsecPermission(type: 'org.jsecurity.grails.JsecBasicPermission', possibleActions: '*').save() 
&lt;/pre&gt;

&lt;p&gt;Now as you have noticed i have used an * for the possible actions, this is more to fill in the blanks than for anything useful. By default with the JsecBasePermission it really does not care about the actions used here. Now just because this particular permission is not using possible actions does not mean that another permission in the future could use it nor does it mean it HAS to use it either. This is part of JSecurity's methodology of trying to keep maximum flexibility.&lt;/p&gt;

&lt;p&gt;Assigning the User to the Permissions
Now that we created the permission let's assign it to a user you have already created. To assign it you basically have two choices. Either assign it to a role or assign the permission directly to the user. I am going to do the latter and assign it to the user. In the following code we are taking our user and our permission and allowing the actions of delete and edit.&lt;/p&gt;

&lt;pre class="brush: groovy;"&gt;
new JsecUserPermissionRel(
    user : user,  
    permission: perm, 
    target : 'user', 
    actions : 'delete, edit').save() 
&lt;/pre&gt;

&lt;h3&gt;Locking Down the Resource&lt;/h3&gt;

&lt;p&gt;So now that we have the permission we are going to lock down the security for the controller, and here is where it may get a bit tricky to understand. First off remember we have not done any permissioning for create or list, so by default we do not want to do any permissioning check for those because we have not assigned any. So in our filter lets add two permissioning interceptors for delete and edit only:&lt;/p&gt;

&lt;pre class="brush: groovy;"&gt;
user(controller: &amp;quot;register&amp;quot;, action: &amp;quot;delete&amp;quot;) {      
    before = { 
        accessControl { 
            permission(type: 'user', actions: actionName)
        }      
    } 
}  

user(controller: &amp;quot;register&amp;quot;, action: &amp;quot;edit&amp;quot;) {      
    before = {
        accessControl { 
            permission(type: 'user', actions: actionName) 
        }      
    } 
} 
&lt;/pre&gt;

&lt;p&gt;Now the application will check for permissions with edit and delete only, and unless you are assigned will take you to a page saying that you aren't allowed.&lt;/p&gt;

&lt;p&gt;Now where I said it can get confusing is the naming as you go through, and this is where we harp back to saying that the permissions in JSecurity is very much user based. While this provides a huge degree of flexibility it can also cause naming you thought should go together not always go together. So take where we initially defined type in the JsecPermission table. This type was our fully qualified class type. However, the type down in the filter we define has nothing to do with the JsecPermission type. This type is instead going to relate to the target we defined in JsecUserPermissionRel. This is an important distinction to make, and one that confused me at first when using the JsecBasicPermission. The actions part, that is more self explanatory and the actions you pass in will be the actions that it will check against.&lt;/p&gt;</description>
      <pubDate>Tue, 03 Mar 2009 20:45:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:96a982d5-4986-439c-9869-e3c8db4a86c2</guid>
      <comments>http://www.integrallis.com/blog/2009/03/03/jsecurity-permissions-in-grails#comments</comments>
      <category>Groovy</category>
      <category>Grails</category>
      <category>Grails</category>
      <category>Security</category>
      <trackback:ping>http://www.integrallis.com/blog/trackbacks?article_id=jsecurity-permissions-in-grails&amp;day=03&amp;month=03&amp;year=2009</trackback:ping>
      <link>http://www.integrallis.com/blog/2009/03/03/jsecurity-permissions-in-grails</link>
    </item>
  </channel>
</rss>
