Monday, April 5, 2010

Grails cheatsheet

Tags


iterate over a map: ${foo}

#never use the plain
tag



.





Determine production/test/development env: GrailsUtil.getEnvironment() will return 'production' 'test' or 'development'
flash.error = message(code: 'permission.error', args: [groupType]) ; permissions.error=No perm for group {0}
Find what plugins are installed:
chain(action:"search", model: ['foo': foo])
printing validation errors: if (!user.validate()) {
user.errors?.allErrors?.each{
println it
}


GORM

def users = User.createCriteria().list(params) { eq("enabled", true) }
1-many: class Story { static hasMany = [comments:Comment] }
class Comment { static belongsTo = [story:Story] }
don't turn version = false unless you physically remove the version column from the table.
Pagination & filtering: def users = User.createCriteria().list(params) { eq("enabled", true) }
Using a postgres sequence: id generator:'sequence', params:[sequence:'blah-id-seq']
When you get a 'pkey constraint violation' ensure that object you are inserting is not already in

HQL example: IncidentDevice has a child named incident of Type Incident
def c = IncidentDevice.createCriteria()
def result = c {
eq("incident.id", incidentId as Long)
}

Domain

static mapping = {
sort "fileName"
id generator:'sequence', params: [sequence:'upload_id_seq']
version false
}
if say a column named 'system' has to be unique within a 'incident' and 'datacenter' then
static constraints = {
system(unique:['incident','datacenter'])
}

Controller and service

Get the current loggedIn user in a controller or in a service
def user = authenticateService.userDomain()
Check if the user is logged in
in gsp:
in controller:


Grails -> Calling a REST service without using any Grails plugin or Groovy XMLSlurper


Add these Jar to your application lib
A lib/httpcore-4.0.1.jar
A lib/commons-collections-3.2.1.jar
A lib/asm-util-3.2.jar
A lib/httpclient-4.0.jar
A lib/commons-codec-1.3.jar
A lib/http-builder-0.5.0-RC3.jar
A lib/json-lib-2.3-jdk15.jar
A lib/commons-lang-2.4.jar
A lib/commons-beanutils-1.8.0.jar
Then: src/groovy/com/rackspace/status/RESTUtil.groovy

Steps to convert / migrate from Jsecurity to Shiro
Steps for converting from JSecurity 3.x/ 4.x to Shiro
1. uninstall jsecurity
grails uninstall-plugin jsecurity-0.3
2. download and copy the /grails-shiro-1.0-SNAPSHOT.zip to your_grails_apps/plugins folder.
3. grails install-plugin ./plugins//grails-shiro-1.0-SNAPSHOT.zip
4. fix the broken imports in file AuthController.groovy and your-Realm.groovy, to point to org.apache.shiro instead of org.jsecurity
5. fix the strategy in Config.groovy to point to
security.shiro.authentication.strategy = new org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy()
6. the jsec: namespace has changed to shiro: so in all you gsp files make the change.
7. In your AuthController or anywhere else change reference of jsecSecurityManager to shiroSecurityManager
8. Change all imported class names with org.jsecurity to org.apache.shiro.

9. insert into ShiroPermission (type, possibleActions) values ('org.jsecurity.grails.JsecBasicPermission', '*')
10. Use the new tags
  • SSL Certificates


  • 11: your perm can not be like the GString below, you have to actually spel out the controller name and action name

    certificateManager( controller: 'certificate', action: 'updatePrice' ) {
    before = {
    accessControl {
    permission("${controller}:${action}")
    }

    }
    }
    12: When you are putting in permission requirements in the security filter, the order of the rules does not matter. Th least restrictive rules do not have to go before the more general rules. Eg> Here the more permissive rule is placed first, yet the app behaves as expected.
    certificateManager( controller: 'certificate', action: '*' ) {
    before = {
    accessControl {
    permission('certificate')
    }
    }
    }

    certificateManager( controller: 'certificate', action: 'updatePrice' ) {
    before = {
    accessControl {
    permission("certificate:updatePrice")
    }
    }
    }

    Monday, March 29, 2010

    Checking for mimetype during a file upload

    The code below will only accept files of type .pdf

    file = request.getFile('fileAttachment')
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    def contentType = fileNameMap.getContentTypeFor(file.originalFilename)
    if (contentType != 'application/pdf') {
    return error
    }

    Sunday, January 31, 2010

    Groovy operators

    These operators are very powerful:
    If you have two lists and want to subtract one list from another:
    myList = myList - yourList // requires that both lists have same type of elements.


    Intersection
    userIds.intersect(usersWithPermissions)


    Split a name-value pair string to make it a String[]
    String [] pair = someString.split(":") // now pair[0] = key and pair[1] = value

    Saturday, January 30, 2010

    Groovy operations

    This is so cool:
    If you have two lists and want to subtract one list from another:
    myList = myList - yourList // requires that both lists have same type of elements.


    Intersection
    userIds.intersect(usersWithPermissions)


    Split a name-value pair string to make it a String[]
    String [] pair = someString.split(":") // now pair[0] = key and pair[1] = value
    split() uses regex so escape any special char e.g. split("\\|") to split("|")

    Thursday, December 3, 2009

    Calling methods with param name: value

    One of the things I like in Groovy is that when I call a method that takes one or more arguments, I can call this method in the caller program with explicit names of the method argument, that way I don't have to remember the order of the arguments.
    e.g. If the method is:
    public List fetchAccountAdmins(Account account, boolean effective)

    Use: fetchAccountAdmins(account: myAccount, effective: true)
    instead of: fetchAccountAdmins(myAccount, true)

    This is a little verbose but gives me more freedom. However, there is one caveat, the target method you are calling must be implemented in Groovy. It can't be a Java method.

    Monday, July 6, 2009

    Grails javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException No name matching

    Recently I was trying to connect to a service via XMLRPC. The server had a cert that was invalid.
    I tried the usual thing of importing the remote server cert into my JVM, restart my Grails client app and I still got the following error.

    javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching [server] found.

    It happens because the server name and the name on the cert do not match. To get aorund this you have to turn the name validation off.

    This is what you need to put in your Bootstrap.groovy to get around this.


    def init = {servletContext ->
    // Disable certificate verification
    def trustManagerMethods = [
    getAcceptedIssuers: { null },
    checkClientTrusted: {a, b -> },
    checkServerTrusted: {a, b -> }
    ]

    def hostnameVerifierMethods = [
    verify: {a, b -> true }
    ]

    def trustManager = ProxyGenerator.instantiateAggregate(trustManagerMethods, [X509TrustManager])
    TrustManager[] trustAllCerts = (TrustManager[]) [trustManager]

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL")

    def hostnameVerifier = ProxyGenerator.instantiateAggregate(hostnameVerifierMethods, [HostnameVerifier])
    HostnameVerifier hv = (HostnameVerifier) hostnameVerifier

    sc.init(null, trustAllCerts, new java.security.SecureRandom())
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
    HttpsURLConnection.setDefaultHostnameVerifier(hv)
    }

    Tuesday, June 16, 2009

    Acegi security pluing tag with Grails

    Here are the most common tags to use with the Acegi and Grails:

    g:ifallgranted role="ROLE_ADMIN,ROLE_SUPERVISOR">
    g:ifanygranted role="ROLE_ADMIN,ROLE_SUPERVISOR">
    g:ifnotgranted role="ROLE_USER">
    g:isloggedin>
    g:isnotloggedin>

    Also you can get some extra info about the logged in user/

    g:loggedinuserinfo field="username"> // as a gtag
    ${loggedInUserInfo(field:'username')} // as a GString-expression

    Getting the loggedin or current User
    If you have the Grails/Acegi plugin installed

    def authenticateService

    def list = {
    def user = authenticateService.principal()
    def username = user?.getUsername()


    If you don't have Acegi or Jsecurity plugin installed

    Object obj =
    SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username;
    if ( obj instanceof UserDetails ) {
    username= ( (UserDetails)obj ).getUsername();
    } else {
    }