Paulo Poiati | Blog

@SuppressWarnings(“unused”)

  • Home
  • About
  • Github
  • GMongo
  • SandBox
Twitter Facebook RSS
Category Archives: Groovy

Easyhash: An easy interface to generate md5 and sha1 hash in hexadecimal format

Posted on 31/12/2011 by Paulo Poiati
No comments

Generate hash in hexadecimal format is a common need for most developers. Generally this is an easy task, but like a lot of stuff it’s complicated to do in Java. You need to use the java.security.MessageDigest API and convert the result from bytes to a hexadecimal string.

Unfortunately, even in Groovy there is no easy path. With that in mind I developed a small library to do the work.

Using Java

First, Put the easyhash jar into the classpath and then:

import static com.lazythought.easyhash.HashGenerator.*;
...
assert "ab07acbb1e496801937adfa772424bf7".equals(md5("foo bar baz"));
assert "c7567e8b39e2428e38bf9c9226ac68de4c67dc39".equals(sha1("foo bar baz"));
...


Using Groovy

With Groovy you can use the @Grab AST:

@Grab('com.lazythought:easyhash:1.0')
import static com.lazythought.easyhash.HashGenerator.*

assert 'ab07acbb1e496801937adfa772424bf7' == md5('foo bar baz')
assert 'c7567e8b39e2428e38bf9c9226ac68de4c67dc39' == sha1('foo bar baz')



There is also the HashCategory option:

@Grab('com.lazythought:easyhash:1.0')
import com.lazythought.easyhash.HashCategory

use(HashCategory) {
    assert 'b071ed8a2de56ecd5958305641a81755' == 'frodo bags'.md5()
    assert 'b6b5ece040fd0c467cb189a284c6e7c752c747f5' == 'frodo bags'.sha1()
}


More info

It’s Available at Maven Central:

<dependency>
    <groupId>com.lazythought</groupId>
    <artifactId>easyhash</artifactId>
    <version>1.0</version>
</dependency>

Source code: https://github.com/poiati/easyhash

Share and Enjoy

Categories: Groovy, Java | Tags: easyhash, groovy, java

Grails / GORM: Changing default id name and type from an entity

Posted on 04/10/2011 by Paulo Poiati
No comments

While developing a simple application at work I got stuck with a common case in GORM, and I didn’t found the solution in the documentation.

I have a table with a column named myid of type varchar. But the GORM, by default, auto generate an id property for you with the long type. The solution is straight forward, just call the method id in the mapping closure, with the following param(s):

class Foo {

    String myid

    static constraints = {}

    static mapping = {
        id generator: 'assigned', name: 'myid'
    }
}

The generator is the strategy to auto-generate the id, you can use a sequence or something like, since it’s a string the value will be assigned, not generated. The name is the current property to bind the value (myid in this case).

Share and Enjoy

Categories: GORM, Grails, Groovy | Tags: grails gorm groovy

Groovy / GMongo tips and tricks

Posted on 29/01/2011 by Paulo Poiati
1 comment

Based on some emails I received last days I will show some features of GMongo that not everyone is aware.

Regex based search

In the mongo official Java driver you can do searches using Regular Expression. To do that you just need to pass a java.util.regex.Pattern instance as the search term. In Groovy there is a shortcut to create a Pattern: ~/regex/.

For example:

def pattern = ~/mypattern/
assert pattern.class.is(java.util.regex.Pattern)

Here is a small script demonstrating the usage of regex search:

@Grab('com.gmongo:gmongo:0.6')
import com.gmongo.GMongo

def gmongo = new GMongo('localhost:27017')
def db = gmongo.getDB('tips')

db.so.drop()
db.so << [name: 'Windows XP']
db.so << [name: 'Windows 7']
db.so << [name: 'Windows Vista']
db.so << [name: 'Mac OS X v10.3 "Panther"']
db.so << [name: 'Mac OS X v10.4 "Tiger"']
db.so << [name: 'Mac OS X v10.5 "Leopard"']
db.so << [name: 'Mac OS X v10.6 "Snow Leopard"']
db.so << [name: 'Mac OS X v10.7 "Lion"']

// Mac OS Only
println "\nMac Os Only\n"
db.so.find([name: ~/^Mac/]).each { so ->
    println so
}

// Print: 

// Mac OS Leopard, Snow Leopard
println "\nMac OS Leopard, Snow Leopard\n"
db.so.find([name: ~/Leopard/]).each { so ->
    println so
}

Persisting your POGO

There is an easy way to persist your POGO using GMongo. Suppose we have the class:

class Person {
   def name
   def age
}

In Groovy we can get all properties from a class using the properties property, for example:

def person = new Person(name: 'Paulo', age: 25)
println person.properties

This code outputs:

[
  class:class Person,
  age:25,
  metaClass:org.codehaus.groovy.runtime.HandleMetaClass@450a10011],
  name:Paulo
]

As you can see, not every property means something to us. We doesn’t want to store class and metaClass in our storage, because it isn’t part of the domain. So, we need to ignore them:

println person.properties.findAll { !['class', 'metaClass'].contains(it.key) }

Now, all we need to do is persist this Map in MongoDB. Here is a complete example:

@Grab('com.gmongo:gmongo:0.6')
import com.gmongo.GMongo

class Person {
   def name
   def age
}

def gmongo = new GMongo('localhost:27017')
def db = gmongo.getDB('example')

def person = new Person(name: 'Paulo', age: 25)

db.persons.drop()
db.persons << person.properties.findAll { !['class', 'metaClass'].contains(it.key) }

def personFromMongo = db.persons.findOne()

assert 'Paulo' == personFromMongo.name
assert 25      == personFromMongo.age

BasicDBObject to POGO conversion

The class com.mongodb.BasicDBObjects extends java.util.LinkedHashMap so it’s easy to convert it to POGO, thankfully to Groovy array notation constructor call. Don’t worry, I will explain. Suppose we have the class:

class Person {
   def name
   def age
}

The two statements bellow are equivalent:

Person mike = new Person(name: 'Mike', age: 23)
Person john = [name: 'John', age: 36]

To this work you need to use typed variable. If you use untyped variable definition Groovy can’t infer what constructor to call.

So, taking advantage of this cool Groovy feature you can do things like this:

@Grab('com.gmongo:gmongo:0.6')
import com.gmongo.GMongo

class Person {
   def name
   def age

   def whoIAm() {
       "Hello, I'm $name and I have $age year."
   }
}

def gmongo = new GMongo('localhost:27017')
def db = gmongo.getDB('example')

def person = new Person(name: 'Paulo', age: 25)

db.persons.drop()
db.persons << person.properties.findAll { !['class', 'metaClass'].contains(it.key) }

Person personFromMongo = db.persons.findOne().findAll { it.key != '_id' }

assert "Hello, I'm Paulo and I have 25 year." == personFromMongo.whoIAm()

As you can see, we need to remove the _id property from the Map before instantiate the class Person, that is because Person hasn’t this property. Another alternative is add the _id property to the Person class.

Any feedback is appreciated.

Share and Enjoy

Categories: GMongo, Groovy, Programming | Tags: gmongo, groovy, mongodb

GMongo available at Maven Central

Posted on 03/07/2010 by Paulo Poiati
1 comment

A maintenance release (0.5.1) of GMongo was launched. It just fixed a bug with com.mongodb.DB#createCollection.

But the good news is the GMongo availability in the Maven Central (http://repo2.maven.org/maven2/).

Maven:

<dependency>
      <groupId>com.gmongo</groupId>
      <artifactId>gmongo</artifactId>
      <version>0.5.1</version>
</dependency>

Ivy:

<dependency org="com.gmongo" name="gmongo" rev="0.5.1"/>

Groovy Grape:

@Grab(group='com.gmongo', module='gmongo', version='0.5.1')

This should compile and run seamlessly in an environment with Groovy 1.7.2 (or later):

@Grab("com.gmongo:gmongo:0.5.1")
import com.gmongo.GMongo

def mongo = new GMongo("127.0.0.1", 27017)
def db = mongo.getDB('myDb')

db.greetings.insert(hello: 'world')

Updated: Version 0.6 is now available as well.

Share and Enjoy

Categories: GMongo, Groovy, NoSQL | Tags: gmongo, groovy, java, mongodb, nosql

GMongo 0.5 Released

Posted on 20/06/2010 by Paulo Poiati
24 comments

GMongo is an alternative to de default Java driver for Mongodb. It’s use an easy and less verbose syntax, the grammar is very close to the official mongo shell cliente (javascript).

It’s just a wrapper around the Java driver. So, every single method of the the official driver is available here too.

The main class is the com.gmongo.GMongo. It has the same API of the com.mongodb.Mongo but it’s not a subclass. Instead, the methods calls are delegated. Despite GMongo, all other classes are the same from the Java driver.

To be more practical, here are some examples:

// To download GMongo on the fly and put it at classpath
@Grab(group='com.gmongo', module='gmongo', version='0.5.1')
import com.gmongo.GMongo
// Instantiate a com.gmongo.GMongo object instead of com.mongodb.Mongo
// The same constructors and methods are available here
def mongo = new GMongo("127.0.0.1", 27017)

// Get a db reference in the old fashion way
def db = mongo.getDB("gmongo")

// Collections can be accessed as a db property (like the javascript API)
assert db.myCollection instanceof com.mongodb.DBCollection
// They also can be accessed with array notation
assert db['my.collection'] instanceof com.mongodb.DBCollection

// Insert a document
db.languages.insert([name: 'Groovy'])
// A less verbose way to do it
db.languages.insert(name: 'Ruby')
// Yet another way
db.languages << [name: 'Python']

// Insert a list of documents
db.languages << [[name: 'Javascript', type: 'prototyped'], [name: 'Ioke', type: 'prototyped']]

def statics = ['Java', 'C', 'VB']

statics.each {
	db.languages << [name: it, type: 'static']
}

// Finding the first document
def lang = db.languages.findOne()
assert lang.name == 'Groovy'
// Set a new property
lang.site = 'http://groovy.codehaus.org/'
// Save the new version
db.languages.save lang

assert db.languages.findOne(name: 'Groovy').site == 'http://groovy.codehaus.org/'

// Counting the number of documents in the collection
assert db.languages.find(type: 'static').count() == 3

// Another way to count
assert db.languages.count(type: 'prototyped') == 2

// Updating a document using the '$set' operator
db.languages.update([name: 'Python'], [$set: [paradigms: ['object-oriented', 'functional', 'imperative']]])

assert 3 == db.languages.findOne(name: 'Python').paradigms.size()

// Using upsert
db.languages.update([name: 'Haskel'], [$set: [paradigms: ['functional']]], true)

assert db.languages.findOne(name: 'Haskel')

// Removing some documents
db.languages.remove(type: 'prototyped')
assert 0 == db.languages.count(type: 'prototyped')

// Removing all documents
db.languages.remove([:])
assert 0 == db.languages.count()

// To ensure complete consistency in a session use DB#inRequest
// It is analogous to user DB#requestStarted and DB#requestDone
db.inRequest {
	db.languages.insert(name: 'Objective-C')
	assert 1 == db.languages.count(name: 'Objective-C')
}

And a simple MapReduce:

@Grab(group='com.gmongo', module='gmongo', version='0.5.1')
import com.gmongo.GMongo

// There is some bug using the [Random] word into codesnipt plugin
import java.util.Random as Rand

def mongo = new GMongo("127.0.0.1", 27017)
def db = mongo.getDB("gmongo")

def words = ['foo', 'bar', 'baz']
def rand  = new Rand()		

1000.times {
	db.words << [word: words[rand.nextInt(3)]]
}

assert db.words.count() == 1000

def result = db.words.mapReduce(
	"""
	function map() {
		emit(this.word, {count: 1})
	}
	""",
	"""
	function reduce(key, values) {
		var count = 0
		for (var i = 0; i < values.length; i++)
			count += values[i].count
		return {count: count}
	}
	""",
	"mrresult",
	[:] // No Query
)

assert db.mrresult.count() == 3
assert db.mrresult.find()*.value*.count.sum() == 1000

It’s a stable version and still a work in progress. The only dependency is the mongo Java driver version 2.0 and, of course, Groovy. It’s tested under Groovy 1.7.2 and 1.7.3. It’s opensource and hosted at http://github.com/poiati/gmongo.

The binaries can be found at Maven Central.
Click here for more details.

Any bug, suggestion or issue, please, contact me.

Share and Enjoy

Categories: GMongo, Groovy, NoSQL | Tags: groovy, java, mongodb, nosql, opensource
  • Recent Posts

    • Easyhash: An easy interface to generate md5 and sha1 hash in hexadecimal format
    • Grails / GORM: Changing default id name and type from an entity
    • Groovy / GMongo tips and tricks
    • GMongo available at Maven Central
    • GMongo 0.5 Released
  • Categories

    • GMongo
    • GORM
    • Grails
    • Groovy
    • Java
    • NoSQL
    • Objective-c
    • Programming
  • Tags

    C easyhash gmongo grails gorm groovy groovy java mongodb nosql Objective-c opensource
  • Blogroll

    • Rodrigo Lazoti Blog
  • Links

    • Mac Developers
  • Recent Comments

    • rohit on Groovy / GMongo tips and tricks
    • Paulo Poiati on GMongo 0.5 Released
    • Steve on GMongo 0.5 Released
    • Steve on GMongo 0.5 Released
    • Paulo Poiati on GMongo 0.5 Released
© Paulo Poiati | Blog. Proudly Powered by WordPress | Nest Theme by YChong