Showing posts with label grails. Show all posts
Showing posts with label grails. Show all posts

Friday, December 19, 2014

Groovy, Gorm with Spring XD


This piece covers the setup and use of Gorm (Grails ORM layer) as a stand-alone entity that can be used by Spring XD jobs and modules.


Foremost - why? What's Gorm and why use it with Spring XD?


Gorm is an extension to Hibernate in a way. Hibernate is good at ORM i.e. mapping classes to database objects. Hibernate is also good at querying. What Hibernate is not good at is the actual usage. There's simple too much you have to do get things going and too much noise afterwards. You have to annotate classes (or worse use XML descriptors), you have to setup persistent context, you have to use Hibernate session to execute actual queries. Now these are the areas addressed by Gorm. With Gorm you can use meaningful defaults. Let's have a look at this Groovy class

class EntityName {
String name
String value
String someOtherValue
Date lastUpdated
Date dateCreated
}

A class like this when seen by Gorm would automagically get converted into something similar

@Entity 
@Table (name = "entity_name")
class EntityName {
@Id @GeneratedValue
    @Column(name = "id")
int id

@Version
int version

    @Column(name = "name")
    String name
    
    @Column (name = "value")
    String value
    
    @Column (name = "some_other_value")
    String someOtherValue

    @Column (name = "last_update")
Date lastUpdated

@Column (name = "date_created")
Date dateCreated

    
    @PrePersist
    void onCreate() {
       dateCreated = new Date();
    }

    @PreUpdate
    protected void onUpdate() {
       lastUpdated = new Date();
    }
}

As you can see you can get a lot for free just by using Gorm. Now that's just a tip of the iceberg as with Gorm you also get validations, constraints and many, many more.

Hope it's clear now that it makes sense to use Gorm even outside of Grails. So what else you have to do to get Gorm running in Spring XD?

First of all, you have to get all Gorm dependency classes loaded by the initial classloader. To this end you can either copy all the classes into the lib folder (you don't really want to do that do you?) or tweak the startup script a bit and add another folder , say called ext, to added onto the classpath. See the attached patch for details.

Now with all the required classes on the classpath we can start playing with Gorm. First, we need to add it into our module's context.

<gorm:sessionFactory base-package="your.package" data-source-ref="dataSource" message-source-ref="messageSource">
    <property name="hibernateProperties">
     <util:map>
                <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
        </util:map>
    </property> 
</gorm:sessionFactory>        

Obviously you have to define the messageSource and dataSource (dataSource is normally already bound the one define in the main yaml file) and the messageSource is easy to define

<bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages"/>
</bean>

Just add all your messages files on the classpath (your module config will suffice). And that's pretty much it.

All your domain classes need to be annotated by the import grails.persistence.Entity`annotation and have to implement equals and hash - for the lazy use the import groovy.transform.EqualsAndHashCode annotation and an AST transformation will take care of it for you.

There are several things you have to keep in mind should you wish to share the model classes between stand-alone Gorm and Grails' Gorm.


  • Autostamping is not working (dateCreated, lastUpdated). You can always use the beforeUpdate closures though.
  • You have to use session explicitly (DomainClass.withSession) or make a component using Gorms domain classes org.springframework.transaction.annotation.Transactional. In both cases you just make sure the Hibernate session is threadlocal.
  • The Entity annotation adds (or more specifically AST adds) some extra fields to the domain classes. Gorm then tries to blindly maps those to the underlaying model and the fails. To avoid this add these fields into the transient section


static transients = ['errors', 'instanceGormInstanceApi', 'instanceGormValidationApi', 'staticGormStaticApi', 'instanceConvertersApi', 'attached', 'dirty'] 

The source can be found on Github.

Wednesday, November 12, 2014

Integrating Grails 2.4.4 with CMS

In our company we use Typo3 CMS to maintain our dynamic contents - copywriting, descriptions etc. The content is actually stored as GSP pages - meaning even in our CMS we use tags such as <a:message/>or our custom tags <z:whatever/>. Basically the way it works we go to CMS every time our URLMapping matches certain pattern to extract and display the content. Once we retrieve the information we use the GroovyPagesTemplateEngine, as provided by Grails, to render the page. Now, with this rendered content we just call the render method to get the actual content rendered providing the layout parameter so the content nicely fits into our app. And it works surprisingly. In a bit of pseudo-code it looks like this:


def template = HTTPClient.get (cmsURL)
def template = groovyPagesTemplateEngine.createTemplate(template, "whateverName")
def result = new StringWriter()
template.make().writeTo(result)
def pageContent = result.toString()
render(text:pageContent, encoding:"UTF-8", type:"text/html", layout: layout)

As you can see it is a fairly straight forward solution. No catches here. Obviously under the hood we do pretty crazy stuff as Grails has to parse the template and execute it in the context of the current request, however from our point of view it looks simple.

All this worked great on Grails 2.3. Then we decided to move onto Grails 2.4. We upgraded a couple of dependancies and so on and were looking forward to see our pages in the new shiny Grails 2.4 look and feel. That didn't happen though. The reason was our CMS. Pages were fetched, templates rendered however the output was stripped, we could only see blank pages and we were asking WHY!?

After several hours of looking under the bonnet of our application we'd finally figured out the reason. To actually explain the why let me just briefly explain how layouts work in Grails 2.3 and Grails 2.4. In version 2.3 Grails uses Sitemesh filter. Basically all layout related operations are stored in a request object and once they leave controllers they're processed by the Sitemesh filter. From this point of view it doesn't matter at what stage you do what with layouts - all is post-processed in the filter. Grails 2.4 has ditched the filter and applies Sitemesh in the render method. Although it looks like a minor change it actually means a lot. It most importantly means that timing is important now. If you just render your pages then the impact is zero - if you compile your GSPs on the fly you have to do several steps to make the process working.

First you have to prepare the request for the initial GSP rendering. That would normally happen during the rendering but we run our GSP before we call render so we have to do it manually. Now when rendering templates all layout elements are processed by the RenderTagLib. This library finds all layout related tags and saves them into a GSPSitemeshPage instance stored in a request. So what we do now is that before calling the initial rendering of our template coming from CMS we create an instance of that class and store it in a request. Once this is done we move that particular instance into a different place in request where the layout rendering can locate it and we do the layout rendering. After that we have our HTML nicely stored in a String variable. The last step is to render it as a text. In a pseudo code it could look like:


static final GSP_SITEMESH_PAGE ='org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutView.GSP_SITEMESH_PAGE'
static final PAGE = "__sitemesh__page";


def template = HTTPClient.get (cmsURL)
request.setAttribute(GSP_SITEMESH_PAGE, request.getAttribute(GSP_SITEMESH_PAGE)?: new GSPSitemeshPage(false)) // that's where we prepare the empty sitemesh page
def sitemeshPage = request.getAttribute(GSP_SITEMESH_PAGE)
def template = groovyPagesTemplateEngine.createTemplate(template, "whateverName")
def result = new StringWriter()
template.make().writeTo(result)
def pageContent = result.toString()
def template = (GroovyPageTemplate) findLayout(request, layoutName)
result = new StringWriter()
request.setAttribute(PAGE, page) //layout rendering needs the simemesh page here
template.make()writeTo(result)
pageContent = result.toString()

render(text:pageContent, encoding:"UTF-8", type:"text/html")


And that's the end of the story. Just keep in mind that every GSP template you load from CMS is actually compiled into Java class and loaded by the classloader. That means that naming the templates is more important than you might have actually thought!

Monday, November 21, 2011

Challenging week

What a week last week. Three project - three completely different technologies.
  • I started the week bug fixing our Wheelchair portal written in Grails. Grails underpinned by my favorite language Groovy is by far framework of my choice and means that i had a pretty good time coding.
  • Next one - PoC opening Oracle CRM (EBiz suite) custom form preloaded with data coming from our new out of the shelf leasing product. Normally we would pass this information in URL but that would mean customizing Oracle CRM which is expensive and no one wants to do it. Solution - Calling system will store input data in database and CRM will load this data on form load event. This event can be handled as personalization (not customization). Technologywise - Oracle SOA to store data into database (exposed as sync webservice) and Oracle forms on CRM side.
  • Last one - creating MS Outlook tasks triggered by events in CRM. The CRM bit is outsourced but the Exchange bit is pure java witha hint of Apache Jackrabbit (client side only - no webDAV server) and composition of webDAV messages.
To be honest that somehow demonstrate how experienced developers (could this be me?) can contribute - by bringing in knowledge from many fields spanning across many technologies. I'm not saying that less experienced developers can't do that but in my opinion they're more focus on latest trends rather than having all round knowledge especially outside of the mainstream (how many of them do Oracle forms, BPEL, not to mention webDAV?).
Anyway good times last week, this week it will be more about implementing more PoC and more, unfortunately, meetings ...