Showing posts with label Grails. Show all posts
Showing posts with label Grails. Show all posts

Friday, April 13, 2012

Problem with grails, maven and spring security

Environment:
Ubuntu 12.04 3.2.0-20-generic-pae kernel
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.1) (6b24-1.11.1-3ubuntu3)
OpenJDK Server VM (build 20.0-b12, mixed mode)

I installed STS 2.9.1 RELEASE which includes apache-maven-3.0.3

I placed the apache-maven-3.0.3 in my PATH environment variable

I created a project with:
mvn archetype:generate \
-DarchetypeGroupId=org.grails \
-DarchetypeArtifactId=grails-maven-archetype \
-DarchetypeVersion=1.3.7 \
-Dversion=1.0.0alpha \
-DgroupId=com.henyo.foobar -DartifactId=foobar

mvn proceeded to download the internet and then created the project folder with the pom file
I modified the pom file to set the source and target to 1.6 as described in the grails manual

I then did:
mvn initialize
which created the grails directory structure

I tried:
mvn grails:run-app
which resulted in the app successfully running

I then tried running just the unit tests with:
mvn grails:exec -Dcommand=test-app -Dargs="--unit"
which resulted in successful build

I then installed the spring security core plugin with:
mvn grails:install-plugin -DpluginName=spring-securit-core

I then tried using the s2-quickstart script:
mvn grails:exec -Dcommand=s2-quickstart -Dargs="com.henyo.foobar.model User Role"
which resulted in a build FAILURE:
[ERROR] Failed to execute goal org.grails:grails-maven-plugin:1.3.7:exec (default-cli) on project foobar: Unable to start Grails: java.lang.reflect.InvocationTargetException: org/springframework/security/core/Authentication: org.springframework.security.core.Authentication -> [Help 1]

It seems that the grails maven integration still needs a lot of work. I suspect this is a dependency resolution issue.

Uploaded a sample project that has this issue: http://dl.dropbox.com/u/5541070/foobar.tar.gz

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Friday, October 01, 2010

Drawing the Usecase Diagrams

I imagine TaskStream will be used by 2 types of people in an organization, Users and Admins.
The diagrams above was produced using yuml.me using:

[User]-(Sign in)
(Sign in)>(Sign out)
(Sign in)>(Update Settings)
(Sign in)>(Forgot Password)
[User]-(Share a task)
(Share a task)>(Delete task)
(Share a task)>(Update task)
[User]-(View task stream)
[User]-(Comment on a task)
(Comment on a task)>(Delete own comment)

Admins, in addition to what regular users can do, also have a few more use cases:


[Admin]-(Manage Users)
(Manage Users)>(Update a User)
(Manage Users)>(Delete a User)
[Admin]-(Generate Reports)

I think this is enough to cover the basic functionality of TaskStream. It's time to go into detail and flesh out the User Stories.

TaskStream devlog#02: Writing the User Stories
TaskStream: simple task sharing and tracking

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

TaskStream: simple task sharing and tracking


TaskStream is a web application that allows the internal users of an organization to share tasks with one another as well as to comment on each others tasks. It is designed and built to be run on the intranet allowing organizations better control of usage as well as features and customizations. The web application tracks the status of each task as well as the amount of time spent on said task allowing management to make timely and accurate decisions. 


TaskStream will also serve as the showcase application for building a grails application using the correct approach: complete with upfront Use Case Diagrams,User Stories and Domain Models. I will also strive to write the tests first before the implementing code whenever possible. I will be documenting the progress on this blog which could allow me to make an e-book or perhaps a couple of screencasts to sell on line. Perhaps this could also form the basis of a seminar/talk which I could give so as to help pay for the bills. Or I could accept donations for feature requests so that I could continue working on the system. The possibilities seem endless but I am getting ahead of myself.

TaskStream devlog#01: Drawing the Usecase Diagrams
TaskStream devlog#02: Writing the User Stories
TaskStream devlog#03: Mocking up the screens
TaskStream devlog#04: Domain Modeling
TaskStream devlog#05: Creating the Grails Project
TaskStream devlog#06: Dealing with Security

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Wednesday, September 15, 2010

REST XML parsing with Grails 1.3.4

We encountered an issue with Grails 1.3.4 where we found that the XML packet was not parsed and added to the params variable in the controller.

The grails manual has a section which describes how to do REST web services. We followed the instructions but we weren't able to get the automatic data binding to our domain class to work. A fix seems to be on the way but in the mean time, the code below provides a workaround for the issue:

private populateParamsFromXML(xml,map) {              
        def rootName = xml.name()
        //check if params is already populated
        if(map[rootName])
            return
        def xmlMap = [:]
        map[rootName] = xmlMap          
        map = xmlMap
        for (child in xml.children()) {
            // one-to-ones have ids
            if (child.@id.text()) {
                map["${child.name()}.id"] = child.@id.text()
                def childMap = [:]
                def key 
                map[child.name()] = childMap
                populateParamsFromXML(child, childMap)
            }
            else {
                map[child.name()] = child.text()
            }
        }
    }

It should be called in a controller action before the params variable is used to populate a domain class.

populateParamsFromXML(request.XML,params)

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Monday, May 03, 2010

Grails with Notepad++ Text Editor

Yesterday, I had to work on a Grails project on my old laptop which was running a fresh install of Windows XP SP3. The laptop is about 8 years old. It had 512mb memory and a Pentium M 1500Mhz. The experience was not very good.

First thing I had to do was to get Java installed. I went to the official website and downloaded JDK 1.6.0_20. I ran the installer and proceeded with the next step.
Next I downloaded the zip file distribution of Grails version 1.1.1 and extracted it to c:\grails.

Friday, August 07, 2009

Using ID tables with Grails

Background and Use Case: We had to migrate one of our web applications to Grails. The old one used JPA and table-based scheme of generating primary key IDs. I scoured the internet with the help of google and found no one with the same problem. I of course had to do it on my own and after going thru the Grails docs, JPA docs and Hibernate docs, I arrived at the solution:
    static mapping = {
        id generator:'org.hibernate.id.enhanced.TableGenerator',
            params:[table_name:'id_table',value_column_name:'gen_id',segment_column_name:'gen_key',segment_value:'fooID']
    }
If you stick the above code in a domain class named Foo, you will end up with a table named id_table and it will have two columns, gen_key and gen_id. If you try saving an instance of Foo, you will end up with:
gen_keygen_id
fooID 1

If you do something similar to the domain Bar, you will end up with:
gen_keygen_id
fooID 1
barID 1

Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Wednesday, June 24, 2009

Run grails-app on the root context

USECASE: You want to run your shiny grails killer-app using the jetty server on port 80 and using the root context. Running it on port 80 is covered by providing the grails run-app command with the desired port but your app will still run on http://localhost:80/killer-app. To run it on the root context, you can do:
grails -Dserver.port=80 -Duse.root.context.path=true run-app
but first, you have to modify _GrailsRun.groovy and change an existing method to this:
private runInline(scheme, host, httpPort, httpsPort) {
    EmbeddableServerFactory serverFactory = loadServerFactory()    
    def useRootContextPath = System.getProperty("use.root.context.path")
    if(useRootContextPath)
        serverContextPath = '/'
    grailsServer = serverFactory.createInline("${basedir}/web-app", webXmlFile.absolutePath, serverContextPath, classLoader)
    runServer server: grailsServer, host:host, httpPort: httpPort, httpsPort: httpsPort, scheme:scheme
    startPluginScanner()
}
You can find _GrailsRun.groovy in $GRAILS_HOME/scripts

WARNING: THERE ARE SERIOUS PENALTIES FOR ROLLING OUT YOUR APP THIS WAY

The code seems trivial but I'll submit it anyway to the grails dev team for inclusion. Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Wednesday, April 29, 2009

Mocking Transactions for unit testing a Grails Service

Use Case:
As a good developer
I should be able to unit test services that programmatically use transactions
So that I can minimize defects  and have high unit test coverage
The Example Specs:
A persistent Foo object has a bar field which is of type String. Write a service with a doSomethingTransactional method that accepts a Foo object as a parameter. The method should change the value of bar to 'did something transactional' if the value of bar is NOT 'oops'
The Domain:
package com.henyo.model

class Foo {

    String bar

    static constraints = {
    }
}
The Unit Test:
package com.henyo.service

import grails.test.*
import com.henyo.model.*
import com.henyo.service.*
import com.henyo.*

class FooServiceTests extends BaseUnitTestCase{

    void testShouldCommit(){
        def foo = new Foo(bar:'not oops')
        mockForTransaction(Foo)
        def service = new FooService()
        service.doSomethingTransactional(foo)
    }

    void testShouldRollBack(){
        def foo = new Foo(bar:'oops')
        mockForTransaction(Foo,true)
        def service = new FooService()
        service.doSomethingTransactional(foo)
    }
}
The unit test above takes into account 2 scenarios. One where we expect that the transaction will be committed and the other one will signal a rollback. The mockForTransaction actually returns a TransactionStatus object which can be used to check if the transaction is indeed committed or if it is for roll back. There is no need though to test for this as BaseUnitTestCase handles this for you automatically.
The Service:
package com.henyo.service

import com.henyo.model.*

class FooService {

    boolean transactional = false

    def doSomethingTransactional = { foo ->
        Foo.withTransaction{ status ->
            if(foo.bar == 'oops'){
                status.setRollbackOnly()
            }
        }
    }
    
}
My BaseUnitTestCase:
package com.henyo

import grails.test.GrailsUnitTestCase
import org.springframework.transaction.TransactionStatus

class BaseUnitTestCase extends GrailsUnitTestCase {

    def statusControls

    protected void setUp() {
        super.setUp()
        statusControls = []
    }

    protected void tearDown(){
        statusControls.each{
            it.verify()
        }
        statusControls.clear()
        super.tearDown()
    }

    def mockForTransaction(Class clazz,boolean expectRollback = false){
        registerMetaClass(clazz)
        def statusControl = mockFor(TransactionStatus)
        statusControls << statusControl
        if(expectRollback)
            statusControl.demand.setRollbackOnly(1..1) { println 'setRollbackOnly called'}
        def status = statusControl.createMock()
        clazz.metaClass.'static'.withTransaction = {
            Closure callable ->  callable.call(status)
        }
        return statusControl
    }
}
Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Friday, November 21, 2008

Simple Periodic Task Scheduling with Grails

Need to run a periodic background task in your grails app? Here's how you can do it with no additional plug-ins. I tried this with Grails version 1.03 but I believe its valid even for older versions. This approach assumes that you need to execute a method in one of your service components periodically. In this example, I need to run the doFoo() method of the FooService every minute with an initial delay of 1 minute. Open the resources.groovy file located in the spring folder inside your conf folder inside the grails-app directory of your project. So if your project is in a directory myproject, you can find it at ~/myproject/grails-app/conf/spring Add or modify the contents of the file to include the following declarations:
beans = {
    doFooTimerTask(org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean){
        targetObject = ref("fooService")
        targetMethod = 'doFoo'
    }
    
    doFooScheduledTimerTask(org.springframework.scheduling.timer.ScheduledTimerTask){
        delay = 60000
        period = 60000
        timerTask = ref('doFooTimerTask')
    }
    
    timerFactory(org.springframework.scheduling.timer.TimerFactoryBean){
        scheduledTimerTasks = [ref('doFooScheduledTimerTask')]
    }   
}

The code above uses Grails' Spring DSL to define the necessary beans to implement the needed functionality. The first segment defines a MethodInvokingTimerTaskFactoryBean which sets up the service and the metod to be called. The next segment defines a ScheduledTimerTask which setups the initial delay and the period between calls. The third and last bean initializes the timer factory which is a TimerFactoryBean which is responsible for running each timer task at the specified intervals.

Wednesday, July 30, 2008

Setting up gedit for groovy and grails

Setting up gedit for groovy and grails

 I use CentOS5 and Ubuntu 8.04.

Save groovy-mime.xml to your home directory.

Save groovy.lang to your home directory.

Save gsp-mime.xml to your home directory.

Save gsp.lang to your home directory.

The above 4 files are not under any restrictive license. They are for anyone who may want them for any use they may wish to put them to.

Log-in as root or you can also log-in as a non-root user with sudo permissions.

If you do login as a non-root user then you should make the appropriate changes to the commands below i.e. by adding sudo before each of the commands. Open a command line terminal and do:
 
mv ~/groovy-mime.xml /usr/share/mime/packages/
 
mv ~/groovy.lang /usr/share/gtksourceview-2.0/language-specs/
 
mv ~/gsp-mime.xml /usr/share/mime/packages/  

mv ~/gsp.lang /usr/share/gtksourceview-2.0/language-specs/
 
update-mime-database /usr/share/mime

Launch gedit and open a groovy file or a gsp file. You should now have syntax highlighting.

REST with Grails

Development Environment: Java: 1.5.0_16; Java HotSpot(TM) Client VM 1.5.0_16-b02 System: Linux version 2.6.18-53.el5 running on i386; UTF-8; en_US (nb) NetBeans IDE Dev (Build 200807040101) + Groovy and Grails plugin - created a grails project - created a domain class with name Game
class Game {
    String title
    String publisher
}
- used generate all to generate the view and controller - modifed Bootstrap.groovy to add sample data
class BootStrap {
     def init = { servletContext ->
         new Game(title:"game1",publisher:"pub1").save()
         new Game(title:"game2",publisher:"pub1").save()
         new Game(title:"game3",publisher:"pub2").save()
         new Game(title:"game4",publisher:"pub2").save()
     }
     def destroy = {
     }
} 
- run the app and test it - modify URLMappings.groovy
class UrlMappings {
    static mappings = {\
        "/ws/game/$id?"(controller:"game"){
            action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]
        }
    }
}
- modify GameController.groovy show method
def show = {
    if(params.id && Game.exists(params.id)) {
        def g = Game.get(params.id)
        render g as XML
    }
    else {
        def all = Game.list()
        render all as XML
    }
}
- the method can be tested with this client
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
def url = "http://localhost:8080/GameTrax/ws/game/${args[0]}"
def method = new GetMethod(url)
def client = new HttpClient()
def statusCode = client.executeMethod(method)
println "STATUS CODE:$statusCode"
def stream = method.getResponseBodyAsStream()
println "--- START RESPONSE BODY --- "
System.out << stream
println "\n--- END RESPONSE BODY ---"
stream.close()
method.releaseConnection()
- modify GameController.groovy save method
def save = {
    def game = new Game(params['game'])
    if(game.save())
        render game as XML
    else{
        def myerrors = game.errors.allErrors.collect { g.message(error:it) }
        render(contentType:"text/xml") {
            errors {
                for(err in myerrors) {
                    error(err)
                }
            }
        }
    }        
}
- you can test the method with the client below:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
def url = "http://localhost:8080/GameTrax/ws/game"
def method = new PostMethod(url)
def client = new HttpClient()
def payload = """
<game>
  <title>newgame</title>
  <publisher>newpublisher</publisher>
</game>
"""
method.addRequestHeader("Content-Type","text/xml")
method.addRequestHeader("Accept","text/xml,application/xml;q=0.9")
method.setRequestEntity(new StringRequestEntity(payload))
def statusCode = client.executeMethod(method)
println "STATUS CODE:$statusCode"
def stream = method.getResponseBodyAsStream()
println "--- START RESPONSE BODY --- "
System.out << stream
println "\n--- END RESPONSE BODY ---"
stream.close()
method.releaseConnection()