Grails and Ehcache Annotations for Spring

Ehcache Annotations for Spring is a project that allows "declarative, aspect based caching to be added to a Spring Framework based application by simple annotation". And because Grails stands on Spring, there is no problem to do that. We are using spring xml based configuration here, but if any one know how rewrite it to Groovy DSL, please leave a comment.

1) Configure dependencies in BuildConfig.groovy.

 
compile('com.googlecode.ehcache-spring-annotations:ehcache-spring-annotations:1.2.0'){
    excludes 'ehcache-core', 'slf4j-api'
}
 

2) Configure spring resources.xml. We are using proxy-target-class="true" option to avoid JdkDynamicAopProxy ClassCastException problem.

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">
 
    <ehcache:annotation-driven proxy-target-class="true" />
 
    <ehcache:config cache-manager="cacheManager">
        <ehcache:evict-expired-elements interval="60" />
    </ehcache:config>
 
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
 
</beans>
 

3) Configure Ehcache in ehcache.xml.

 
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
 
    <diskStore path="java.io.tmpdir"/>
 
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            overflowToDisk="false"
            timeToIdleSeconds="300"
            timeToLiveSeconds="300"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            />
 
    <cache name="cacheableService"
           maxElementsInMemory="30000"
           eternal="false"
           overflowToDisk="false"
           diskPersistent="false"
           timeToLiveSeconds="86400"
           timeToIdleSeconds="0"
            />
 
</ehcache>
 

4) Use annotations in code:

 
class CacheableService {
 
    @Cacheable(cacheName="cacheableService")
    public MyData getData() {
        ...
        return myData
    }
 
    @Transactional
    @TriggersRemove(cacheName="cacheableService", removeAll=true)
    public void updateData() {
        ...
    }
}
 

Grails Gmock partial mock example

 
class Foo {
 
    def methodFoo(String param){
        return "methodFoo"
    }
}
 
...
 
class Bar {
 
    def foo
 
    def methodBar(String param){
        return foo.methodFoo(param) + methodBarSecond(param);
    }
 
    def methodBarSecond(String param){
         return "methodBarSecond"
    }
}
 
...
 
import static org.hamcrest.Matchers.any
 
@WithGmock
class BarTests {
 
    @Test
    public void checkMethodBar(){
        def result = "my other result"
        def mockFoo = mock(Foo)
        mockFoo.testMethod(any(String)).returns(result)
 
        Bar bar = new Bar()
        bar.foo = mockFoo
        mock(bar).methodBarSecond(any(String)).returns(result)
 
        play {
            assertEquals (result * 2, bar.methodBar())
        }
    }
}
 

Grails bean factory + method with parameters

 
class MyObjectFactory {
    static final int TYPE_ONE = 1
    static final int TYPE_TWO = 2
 
    def produce(int type){
         if (type == TYPE_ONE){
              return ... // type one
         }
 
         if (type == TYPE_TWO){
              return ... // type two
         }
 
         throw new IllegalArgumentException()
    }
} 
 
...
 
beans {
 
    myObjectFactoryBean(MyObjectFactory)
 
    myObjectBean(myObjectFactoryBean:'produce'){bean->
         bean.constructorArgs = [MyObjectFactory.TYPE_ONE ]
    }
}
 

STS and Grails development

After long, long time I have back to eclipse as a main IDE for Grails development. There are two reason to do that. First, my license on IntelliJ was token (end of project == end of license), and before I give lots of $ for my own copy of JetBrains product, I want to test an alternative solutions. Second, I wanted to test Spring Source work (honestly!).

What I have remembered from my last contact with Eclipse + Grails combination was pain. Not even pain but PAIN. But, almost 2 years ago there wasn't to much alternatives. Yes, there was IntelliJ but even my beloved IDE wasn't perfect.

But now, everything changed. Grails became popular framework, Spring buy it and rush began in IDE development.  So how its looking now with STS and Grails? 

We got new project explorer view with nice separations of project elements (controllers, services, domains and so one). What is nice, STS will handle plugins and dependencies and display its source in explorer too. Even more - it will handle project that base on plugin oriented architecture. Sweet.

Other nice feature will appear when you press Alt+Ctrl+Shift+G (ok, one finger left). Its Grails console, with autocomplete (just write "ins" and press Ctrl + Space) similar to console used in Roo/STS integration.

What most important, code autocomplete  is working.  We can navigate through project classes structure, plugins and dependencies.

So is everything shiny? Unfortunately  no - in my case there were some problems with import visibility: even if class was correctly reflected, and autocompletion shows methods (even dynamic, yupi!) eclipse shows nasty error in line where import statement was. Fortunately "clean project" allows to correct this problem.  

Another problem was with inner classes. For class like this:

 
class Role {
     static class Type {
           static final ADMIN = 'ROLE_ADMIN'
           static final PLAYER = 'ROLE_PLAYER'
     }
}
 

STS will not see ADMIN and PLAYER fields.

So, what opinion I give to Spring Soruce IDE? Not bad. I will stick to it for now. Definitely I am able to work with Grails project without headache. There are still problems, but not critical. IDE is still evolving and I am sure that in near future it will be great tool. But to be hones, IntelliJ at this moment is just better.

Burning Image 0.5 released

New version of Grails plugin for image manipulation released. Current version ships with ImageMagick support.

To read more go to project home page.

Burning Image 0.4 released

New version of Grails plugin for image manipulation released. Current version allows to:

  • mark domain class as DB image container by using @DBImageContainer annotation
  • configure image storage outside of application dir

To read more go to project home page.

I want to thanks Руслан Бычков for help with works on this version and solving major problem that i encountered. Cheers man!

Groovy magic: asType

Every one who used Grails had to deal (or will have) with XML/JSON converters. They allow to transform object by using syntax like:

 
import grails.converters.*
 
class TestController {
    def index = {
         [a:1, b:2, c:3] as JSON
    }
}
 

I like this "as" syntax, is very verbose and clear. How we can implement in our code? Simple, just use asType method:

 
class Foo {
    def name
 
    String toString(){
        "Foo name is ${name}"
    }
}
 
class Bar {
    def name
 
    String toString(){
        "Bar name is ${name}"
    }
}
 
class Bas {
 
    def name
 
    String toString(){
        "Bas name is ${name}"
    }
 
    Object asType(Class type){
        typeWorker[type](this)
    }
 
    @Lazy
    private def typeWorker = [(Foo):asFoo, (Bar):asBar]
 
    private def asFoo = {it ->
        new Foo(name:it.name)
    }
 
    private def asBar = {it ->
        new Bar(name:it.name)
    }
}
 
def bas = new Bas(name:"Gringo")
 
println bas
println bas as Foo
println bas as Bar
 

and output will be :

Bas name is Gringo
Foo name is Gringo
Bar name is Gringo

Grails, sky is the limit

Yesterday during my research about fronted (Flex) <-> backend (anything) communication solutions, I hit in Grails Red5 plugin. It take only a few minutes to setup fully accessible RTMP server, that will allow you to build, e.g. video chat. Only several commands change Grails into something totally different. And I like it.

Burning Image 0.3 released

New version of Grails plugin for image manipulation released. Current version allows to:

  • scale image with approximate width and height
  • scale image with accurate width and height
  • add image watermark
  • crop image
  • write text on image
  • mark domain class as image container by using @FileImageContainer annotation
  • save image binded to domain class by using ImageUpladService
  • validate uploaded image

To read more go to project home page.

Grails and AST transformations – hard start

Recently i tried to use AST transformation in my Burning Image Grails plugin. I want to use them, to mark domain objects that should be extended by some methods and fields that allow to use this object as a container for information about image saved on server.

I follow this "how to" tutorial, but after struggling with code for several hours, its appears (Joshua Burnett was very helpful - thanks) that if you want to use this technique, you should write code as a pure Java classes not Groovy scripts. After that, it run smoothly.

If any one is capable to run AST transformations as groovy scripts (in Grails project), i will be very thankful for "how to".

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.