Category Archives: Groovy

Grails Starter kit

After years of working with Grails, I thought I would put down in one place a few things I tend to use frequently in my Grails projects. These are things I thought might help others getting started with Grails.

Templates

I often find that I need to extend the default session timeout(found in the src/templates). All that is needed is

> grails install-templates

You will then need to edit the web.xml contained in the following directory structure that was generated from the above command.

src -> templates -> war -> web.xml

you can now modify the timeout value

<session-config>
    <session-timeout>180</session-timeout>
 </session-config>

Custom Domain Classes

Update your domain class templates to reduce having to type in your company standards for every domain class. One of the environments I worked in had a database standard that required us to label Primary Key column name(PK_column_name) and use oracle’s generator for ids. I addressed this by creating a private company “db standards” Grails plugin.

First I updated the

templates-> artifacts ->DomainClass.groovy file

@artifact.package@class @artifact.name@ {
    Date lastUpdated
    Date dateCreated
    String createdBy
    String updatedBy

    static constraints = {

    }
    static mapping={
        id generator: 'sequence', params: [sequence: '@artifact.name.uppercase@_SEQ']
        columns { id column: 'PK_@artifact.name.uppercase@_ID' }//prod/test
    }
}

I then copied and modified a core grails script(see comments in code) that creates domain classes and renamed it create-my-domain(well it was better names then this… but you get the gist :D). See below.
Then I can run

>create-my-domain Book

The following concrete domain class is generated(notice the sequence,id, and generator are all there).

class Book{

  Date lastUpdated
  Date dateCreated
  String createdBy
  String updatedBy
  static mapping = {
    id generator: 'sequence', params: [sequence: 'BOOK_SEQ']
    columns { id column: 'PK_BOOK_ID' }
}

DataSource(s)

There are times when I need to query a database that I don’t need/want a Domain Class for.  I tend to create a datasource and inject it into a service that will be handling the connection/query with groovySql

Here is an example datasource in the DataSource.groovy file.

dataSource_salesInfo {
  driverClassName = "oracle.jdbc.driver.OracleDriver"
  url = ""//more on how to configure this later in this blog entry
  username = ""

  password = ""
  dialect = "org.hibernate.dialect.Oracle10gDialect"
  hibernate {
    cache {
      use_second_level_cache = false
      use_query_cache = false
    }
  }
}

Example service that uses the defined datasource entry.

class AwesomeService{

  def dataSource_salesInfo //Inject it

  def queryDB(){
  def sql = new Sql(dataSource_salesInfo)
  String myQuery ='..'
  sql.rows(myQuery).each { resultSet -> /*do something*/}
  }
}

Externalize Datasources

One way to externalize your jdbc connection url is to use an system environment variable. Another is to have your operations team generate a properties file based on the tnsnames.ora file and read it into your grails application. I will describe how the properties file based solution would work.
An Example tnsnames.properties entry might look like the following.

DATAWAREHOUSE=jdbc:oracle:thin:@xyaeyp49:1521:DATAWAREHOUSE

in datasource.groovy file, I add the following to the top of the file.

def props = new Properties()
new File('pathToTNS.properties').withInputStream { stream -> 
props.load(stream) }

then I reference the property in the URL entry for the datasource I am working with 

username='javazquez'
url = props.get("DATAWAREHOUSE")
...

 

Most of my day is spent with Oracle databases. The validation query that I use is

 

validationQuery = "SELECT sysdate from dual"

here is a complete example.

production {
  dataSource {
    url = props.get("DATAWAREHOUSE")
    username = ""
    password = ""
    properties {
      maxActive = -1
      minEvictableIdleTimeMillis = 1800000
      timeBetweenEvictionRunsMillis = 1800000
      numTestsPerEvictionRun = 3
      testOnBorrow = true
      testWhileIdle = true
      testOnReturn = true
      validationQuery = "SELECT sysdate from dual"
    }
  }
}

 

Here are the lines that actually allow you to externalize your config/datasources(Thanks to Burt Beckwith and his book )

 

production {
grails.config.locations = [
"file:path_2_external_config.properties" //NOTE: don’t leave spaces
]
}

I like to have the following in my path

grails.config.locations = [
 "file:path_${appName}/${appName}_${grails.util.Environment.current.name}_config.groovy",
]

This forces the file name to have development || production || test and the application name in the configuration file to prevent copy and paste errors(you would never do that right 😉 )

SQL Logging

There are a couple of ways to see what is going on under the hood when your application is querying the database.

The easiest is to add the logSql = true to your datasource

development {
  dataSource {
    url = props.get("DATAWAREHOUSE")
    logSql = true
    ...
    }
  }
}

If you need more information,  Burt Beckwith has the following Logging Hibernate SQL post that you should read. He shows how adding the following lines to your log4j closure will help with understanding what is happening under the hood.

log4j = {
   ...
   debug 'org.hibernate.SQL'
   trace 'org.hibernate.type.descriptor.sql.BasicBinder'
}

Misc

A log pattern that works with tomcat(YMMV)

appenders {
console name: 'stdout', threshold: org.apache.log4j.Level.INFO
rollingFile name: 'MyLogs', file: 'logs/MyLog.log', maxSize: 104576, threshold: org.apache.log4j.Level.INFO ,
layout:pattern(conversionPattern: "%d{yyyy-MM-dd HH:mm:ss} [%t] %p %c - %m%n")

}

Have your war tell you what environment you are deploying to

grails.project.war.file = "target/${appName}-${appVersion}-${System.getProperty('grails.env')[0..3]}.war"

Websites and links to check out

 

Many of the things I have learned have come from the above links and people. A big Thank You to the gr8 community for all the help over the years.

 

-Juan

Grails ldap integration with Active Directory via spring-security-ldap

The spring-security-ldap has great documentation. I put together a working example (at least in my environment) to complement the docs. When I was tasked with integrating our grails apps with Active Directory I remember there being a scarcity of examples.. so I hope this code will save you some time in getting ldap working with Active Directory in your grails environment.

Important files

grails-app/conf/Config.groovy
src/groovy/com/javazquez/ldapexample/MyUserDetailsContextMapper.groovy
src/groovy/com/javazquez/ldapexample/MyUserDetails.groovy
grails-app/conf/spring/resources.groovy

once you have your Active Directory configurations entered (grails-app/conf/Config.groovy), fire up your app and
test it out by logging in via the login controller.

Notes

  • You may have to update MyUserDetailsContextMapper.groovy as my Active Directory environment may differ from yours.
  • You may also want to update MyUserDetails.groovy to hold more or less info than my config.

-JV

Add Map, Reduce, and Filter to Groovy with an Extension Module

Having just read Michał Mally’s blog that was posted on Google+,
I was intrigued with two benefits listed in the blog:

  • The idea of being able to augment Groovy with changes that would behave as “if they were a part of original GDK”
  • support from your IDE like code completion shall be available out-of-the-box

In order to get my head around how Extension modules worked, I used the following as references
Creating an extension module
Groovy Goodness: Adding Extra Methods Using Extension Modules
Groovy Extension Modules

Cédric Champeau had this to say after I asked about the benefits of Extension Modules over using MetaClass/Expando/Category

@Juan: extension modules are automatically loaded and made available globally. You don’t have to bother with metaclasses (and potential issues with external changes). As well, categories are lexically scoped, although extension modules are global (meaning that they can be used anywhere in the code as long as the extension module is found on classpath).

Last but not least, extension modules are compatible with type checking and static compilation 🙂

To solidify my new understanding of Groovy’s Extension Modules, I decided that I needed to write some code. The example I came up with was to have the functional names (map, reduce, filter ) that I had come familiar with in using Clojure added to Groovy. These “extended methods” are using Groovy’s built-in collect, inject, and grep under the hood.

Source code can be found here

Here is the code for the new aliases found in the FuncProgUtilExtension.groovy class

package com.javazquez;

public class FuncProgUtilExtension {
    public static Collection filter(Collection self, Closure clozure) {
	   return self.grep(clozure)
   }
   public static Collection map(Collection self, Closure clozure) {
	   return self.collect(clozure)
   }
   public static Object reduce(Collection self, Closure clozure) {
	   return self.inject(clozure)
   }
   public static Object reduce(Collection self, String operator) {
	   switch(operator){
		   case '+' :
		      self.inject({acc, val -> acc + val})
			  break
		   case '-' :
			   self.inject({acc, val -> acc - val})
			   break
		   case'*' :
			   self.inject({acc, val -> acc * val})
			   break
		   case '/':
		   	   self.inject({acc, val -> acc / val})
			   break
		   case'**':
		   	   self.inject({acc, val -> Math.pow(acc, val)})
			   break
		   default:
			   throw new IllegalArgumentException()
			   break
	   }
   }
}

In a file named ‘org.codehaus.groovy.runtime.ExtensionModule’ located in ‘src/main/resources/META-INF/services/’

I have the following

moduleName=JavazquezFuncProgTest
moduleVersion=1.0
extensionClasses=com.javazquez.FuncProgUtilExtention

Using spock, I wrote the following tests :

package com.javazquez

import spock.lang.Specification

class FuncProgUtilSpec extends Specification{

	def "test map"(){
		expect:
			[ 1 ,2 ,3 ,4].map{it*2} == 	[ 1 ,2 ,3 ,4].collect{ it*2 } 	
	}	
	def "test reduce "(){
		expect:
			[ 1 ,2 ,3].reduce('*') == 6
			[ 1 ,2 ,3,4].reduce('+') == 10
			[ '1' ,'2' ,'3','4'].reduce('+') == '1234'
			[ 1 ,2 ,3].reduce('-') == -4
			[ 2, 2 ,2].reduce('**') == 16
			[ 1 ,2 ,3].reduce({acc, val -> acc + val}) ==[ 1 ,2 ,3].inject { acc, val -> acc + val}
	}
	def "test invalid argument"(){
	 	when:
	 		[ 1 ,2 ,3,4].reduce('%')
		then:
			thrown(IllegalArgumentException)
	}
	def "test filter"(){
		expect:
			[1,2,3,4,5,6,7,8,9].filter { it % 2 ==0 } == [2,4,6,8]
			[1,2,3,4,5,6,7,8,9].filter { it > 2 } == [3,4,5,6,7,8,9]
			"Juan Vazquez".toList().filter { it ==~ /[aeiou]/} == ['u','a','a','u','e']
	}
}

My biggest obstacle was getting the directory structure correct. It is amazing how little code was required to accomplish my goal. I hope my example project and listed references will help in your understanding of this powerful feature. My next step with this project going to be to make evaluation lazy.

Groovy Invoke Dynamic Support

The release of Groovy 2.1 comes with full Invoke Dynamic Support. Initially I had issues with trying to get a working example up and running as seen by the following message.

>groovy –indy mergesort.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
General error during class generation: Cannot use invokedynamic, indy module was excluded from this build.

I checked the groovy version to make sure that I had Java 7 loaded as seen here
groovy -version
Groovy Version: 2.1.0 JVM: 1.7.0_11 Vendor: Oracle Corporation OS: Mac OS X

In order to get things working, I read that I needed to get the “indy” jar on my classpath. I added the following to my .bash_profile and restarted my terminal and the error cleared up

export CLASSPATH=$HOME/.gvm/groovy/current/indy/groovy-2.1.0-indy.jar

Hope this helps and a huge thanks to the Groovy Core Team for this latest update!

-Juan

Simple Groovy project using Gradle

Hello fellow Groovyists 🙂

I have been kicking the tires on using Gradle for my Groovy projects. I had a few stumbles along the way and wanted to share what I came up with for getting a very simple example working.

build.gradle

apply plugin: 'groovy'
version = "1.0-${new Date().format('yyyyMMdd')}"

manifest.mainAttributes("Main-Class" : "com.javazquez.HelloThere")

repositories {
mavenCentral()
mavenRepo urls: "http://groovypp.artifactoryonline.com/groovypp/libs-releases-local"
}
dependencies {
groovy group: 'org.codehaus.groovy', name: 'groovy-all', version: '1.8.4'
groovy group: 'org.mongodb', name: 'mongo-java-driver', version: '2.6.5'
groovy group: 'com.gmongo', name: 'gmongo', version: '0.9.1'
testCompile "org.spockframework:spock-core:0.5-groovy-1.8"
}

jar {
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

below is the the HelloThere.groovy file located src/main/groovy/com/javazquez/HelloThere

package com.javazquez
public class HelloThere {

public static void main(String []args) {
println "Hello coders!"

}

}

after running gradle build, I can navigate to the build/libs directory and run java -jar HelloThere-1.0-20111115.jar and get the following ouptut

Hello coders!

Gradle is a fantastic tool and I hope this article helps show the ease of getting a project set up.

Activiti GET/POST REST requests with Groovy

I have been working with Activiti lately and needed to test the REST API included with the demo. Below are the GET and POST requests I whipped up using Groovy. Hope you find this useful 🙂


//---Get Request
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0' )
import groovyx.net.http.RESTClient

def client = new RESTClient('http://localhost:8080/activiti-rest/service/process-engine')
println client.get(headers:[Authorization:"Basic ${'kermit:kermit'.bytes.encodeBase64()}"]).data

// output
[name:default, exception:null, version:5.7, resourceUrl:jar:file:/Users/juanvazquez/Documents/activiti-5.7/apps/apache-tomcat-6.0.32/webapps/activiti-rest/WEB-INF/lib/activiti-cfg.jar!/activiti.cfg.xml]


// POST request
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0' )
import static groovyx.net.http.ContentType.JSON

def jsonObj = new groovy.json.JsonBuilder()
jsonObj{
  userId 'kermit'
  password 'kermit'
}
def client = new groovyx.net.http.RESTClient('http://localhost:8080/activiti-rest/service/login')
def response = client.post(contentType: JSON, body:jsonObj.toString() )

println response.data           

//output
[success:true]

Login with Basic Authentication using Groovy

Hey there fellow Groovyists! I was recently in need of performing Basic Authentication on Apache using Groovy for a proof of concept. Below is what I was able to quickly put together.

//Here is a quick groovy 1.7.4 Basic Auth Example
@Grab(group=’org.codehaus.groovy.modules.http-builder’, module=’http-builder’, version=’0.5.0′ )

def authSite = new groovyx.net.http.HTTPBuilder( ‘http://10.110.201.115/~juanvazquez/basicAuth/’ )
authSite.auth.basic ‘user’, ‘pwd’
println authSite.get( path:’testAuth.html’ )

Windows GUI File Parser using Groovy

I find myself doing a lot of file parsing on my Windows XP machine lately. I decide to write a quick utility that would allow me to drag and drop files and search for the key words that I have identified. The utility doesn’t have the logic for searching using regex’s yet, but it should be really easy to add this functionality.

I hacked some Groovy Code with some Java Code and came up with the following script. Hope it is useful.

DISCLAIMER:

As the title suggests, I have only been able to get this to work on my Windows XP machine, OS X didn’t like the javax.swing.TransferHandler and it appears some other operating systems have a hard time with this also.


import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.TransferHandler.*;

class FileDropHandler extends TransferHandler {

private static final long serialVersionUID = 1L;

def wordsToFind =[]
JTextArea output
private JLabel errorMsg;
private String fileText = "";
private boolean test = false;
private boolean same = true;

public boolean canImport(TransferSupport supp) {
/* for the demo, we'll only support drops (not clipboard paste) */
if (!supp.isDrop()) {
return false;
}

/* return false if the drop doesn't contain a list of files */
if (!supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}

boolean copySupported = (COPY & supp.getSourceDropActions()) == COPY;

if (copySupported) {
supp.setDropAction(COPY);
return true;
}

return false;
}

public boolean importData(TransferSupport supp) {
if (!canImport(supp)) {
return false;
}

/* get the Transferable */
Transferable t = supp.getTransferable();

try {

Object data = t.getTransferData(DataFlavor.javaFileListFlavor);

List fileList = (List) data;

for (int j = 0; j < fileList.size(); j++) { File file = (File) fileList.get(j); //file.getAbsolutePath() def tmpfh = new File("FileParser.txt") println wordsToFind.inspect() new File(file.getAbsolutePath()).eachLine{line->
wordsToFind.each{ if(line =~ "${it}" ){
println "${line}"
tmpfh.append(line)
tmpfh.append("\n\n")
this.output.setText(this.output.getText()+line+"\n")
}
}
}//end for

tmpfh.close()

}
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return true;
}

public void setOutput(JTextArea jta) {
this.output = jta;
}

public void setOutput(JLabel jta) {
errorMsg = jta;
}

public String getText() {
return fileText;
}

public void clearAll() {
fileText = "";
test = false;
same = true;

}
}

class AL implements ActionListener{
public JTextField jtf
public FileDropHandler dh
public AL(JTextField jtf,FileDropHandler dh){
this.jtf = jtf
this.dh =dh
}
public void actionPerformed(ActionEvent actionEvent){
println "${this.jtf.getText()}"
dh.wordsToFind= this.jtf.getText().split(' ')
}
}

JTextArea dTextArea = new JTextArea("Drop on me");
FileDropHandler dh = new FileDropHandler()
dh.setOutput(dTextArea)
JTextField jta = new JTextField("Enter words seperated by spaces")
dh.wordsToFind= jta.getText().split(' ')
JButton jb =new JButton("Update Word List")
jb.addActionListener( new AL(jta ,dh ))

dh.setOutput(dTextArea);
dTextArea.setDragEnabled(true);
dTextArea.setTransferHandler(dh);

JPanel p =new JPanel(new BorderLayout());
JFrame f = new JFrame()
p.add(jta, BorderLayout.NORTH)
p.add(dTextArea, BorderLayout.CENTER)
p.add(jb, BorderLayout.SOUTH)

f.getContentPane().add(p)
f.setSize(400,400)
f.setVisible(true)

A Groovy Flickr API

A long time ago I wanted to write a desktop GUI interface for Flickr. At the time I had just learned Java and thought it would be really cool to write it using swing. Little did I know how not cool working with swing would be 🙁

About halfway through the project I heard about a cool new dynamic way to write Java code called Groovy. From that day on Groovy has been making my life a whole lot easier. I didn’t need all the functionality in the flickrj library, so I decide to write a few methods for my app using Groovy. The hardest part of the whole thing was figuring out how to post images to Flickr, for that, I used the flickrj code as a reference. If that source code was not available, I don’t think I would have ever figured it out. So a big thanks to all the folks working on that project!

This is not a complete API for Flickr, but should provide enough to get started.
Link to my GitHub Repo