Groovy, SQL and accessing Java libraries
The beauty of Groovy is that it combines the lovely scripty-ness with the java integration. Here is an example form this morning, I needed to encode some passwords in a database table and wanted a quick script to do the job.
What this script demonstrates is that Groovy can get at databases out of the box and talk to regular Java. Note the postgres driver below - this ran straight away and is the same driver we use in regular java dev. Also note the function “encodePassword”. This calls a load of regular Java stuff from the import java.security.MessageDigest packge.
Yet I can whack all this together and still do the crazy forEach closure thing.
Apologies for shonky code but hey:
import groovy.sql.*
import java.security.MessageDigest
/*
* function to encode a string/password
*/
public String encodePassword(String password, String algorithm) {
byte[] unencodedPassword = password.getBytes();
MessageDigest md = null;
try {
// first create an instance, given the provider
md = MessageDigest.getInstance(algorithm);
} catch (Exception e) {
print ("Exception: " + e);
return password;
}
md.reset();
// call the update method one or more times
// (useful when you don't know the size of your data, eg. stream)
md.update(unencodedPassword);
// now calculate the hash
byte[] encodedPassword = md.digest();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < encodedPassword.length; i++) {
if ((encodedPassword[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
}
return buf.toString();
}
/*
* Main bit of groovy starts here
*/
def DB='jdbc:postgresql://localhost/callbriefdb?useUnicode=true&characterEncoding=utf-8'
def USER='chutney'
def PASSWORD='pants'
def DRIVER='org.postgresql.Driver'
def sql = Sql.newInstance(DB,USER,PASSWORD,DRIVER)
//not really sure how to process a result set so just hacked it ![]()
sql.eachRow('select * from app_user where id <> 0′) { n -> newPw =encodePassword(n.pinNumber,”SHA”) ; sql.execute(”update app_user set password = ${newPw} where id = ${n.id}” )}
3 Responses to “Groovy, SQL and accessing Java libraries”
Leave a Reply
July 22nd, 2011 at 10:16 am
Wait, I cnnoat fathom it being so straightforward.
July 25th, 2011 at 7:38 am
GN0wfB tctisziexdlv