How to encode and decode Base64 in Grails, Groovy or Java

Posted: Fri, Mar 25 11:54 AM (PDT)

I don't know why, but function decodeBase64 in Grails doesn't work correctly. And I found other solution. See below

Now we include the base64 library

import org.apache.commons.codec.binary.Base64

Our encode function

def encodeBase64(String text) {
	return new String(Base64.encodeBase64(text.getBytes()))
}

Our decode function

def decodeBase64(String text) {
	return new String(Base64.decodeBase64(text))
}

That's all

Tags:

How to parse JSON in Grails

Posted: Thu, Mar 24 01:49 PM (PDT)

1. include JSON library

import grails.converters.JSON

2. use JSON library

def jsonString = '{"syntax":true,"email":"test@test.local","status":true,"domain":true}'
def json = JSON.parse(jsonString)
println json

All records are serializabled

happy end :-)

Tags:

HTTP Request in Grails

Posted: Thu, Mar 24 04:39 AM (PDT)

Simple function how you can make HTTP request in Grails

def httpPostRequest(String address, String data, String referer = "http://www.google.com", method = "POST", userAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13") {
	method = method?.toString()?.toUpperCase()
	if (method != "GET") { method = "POST" }
	try {
		def url = new URL(address)
		def conn = url.openConnection()
		conn.setRequestMethod(method)
		conn.setRequestProperty("User-Agent", userAgent)
		conn.setRequestProperty("Referer", referer)
		conn.doOutput = true
		Writer wr = new OutputStreamWriter(conn.outputStream)
		wr.write(data)
		wr.flush()
		wr.close()
		conn.connect()
		return conn?.content?.text
	} catch (e) {
		println e
		return false
	}
}

Now, try to use our function

def content = httpPostRequest("http://www.atlas365.com", "test=my%20first%20test")
if (content) { println content } else { println "Error!" }

This example show us "How we can get the web page http://www.atlas365.com/ by POST request with test parameter". The test parameter is equal "my first test"

Tags:

Grails email address validation

Posted: Wed, Mar 23 06:43 AM (PDT)

Perfect Grails plugin "grails email validator"

This plugin

  • Check if domain exist in DNS
  • Check domain MX records
  • Check if email address is exist and valid

The plugin is available on GitHub: https://github.com/tomaslin/grails-email-validator

Tags:

Create fixed size thumbnails with ImageMagick

Posted: Thu, Mar 10 03:41 AM (PST)

First get Image Magic and install it. You'll find the binary release for any platform accompanied with installation instructions on the Image Magic website.

The Image Magic tool we use is convert. It lets us apply various filters and operations to the images in just one step. Open terminal and go to the directory where you placed the images. What we are going to do is to resize all pictures to 100×100 pixels keeping proportions (no stretch or squash) and then extend the canvas size to exactly 100×100 pixels so that all thumbnails have the same size.

convert -resize 100x100 -gravity center -extent 100x100 -background white big_cover.jpg small_cover.jpg

-resize 100x100 it's self explanatory. Note that the image is not stretched to fit the given dimensions.

-gravity center centers the thumbnail in the canvas.

-extent 100x100 extends the proportionally resized image to fit exactly 100×100 pixels.

-background white create a white canvas to the thumbnail. If the image does not fit completely the 100×100 space, convert will fill the empty space with the specified color.

PS: For better quality, we recommended use PNG format

Tags:

MongoDB Java driver how to use findAndModify in Grails

Posted: Wed, Mar 9 10:50 AM (PST)

An example how to use findAndModify with MongoDB Java driver in Grails

def getAutoIncrementId(String key = "mycounter") {
	def Id = mongoService.getCollection("mycollection").findAndModify([ "key": key ] as BasicDBObject, [ "\$inc": [ "value" : 1 ]] as BasicDBObject)
	return Id?.value?.toInteger()
}

Good luck :-)

Tags:

Redis sessions store for Tomcat

Posted: Wed, Mar 9 01:17 AM (PST)

Do you need store your Tomcat sessions in database?

That is solution for you! Redis database is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

How do I use it?

Download, extract and compile Redis database with:

$ curl -O http://redis.googlecode.com/files/redis-2.2.2.tar.gz
$ tar xzf redis-2.2.2.tar.gz
$ cd redis-2.2.2
$ make

The binaries that are now compiled are available in the src directory. Run Redis with:

$ src/redis-server

You can interact with Redis using the built-in client:

$ src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"

Our Redis database is ready.

Next step: download the latests build Redis Store for Tomcat at:

http://github.com/xetorthio/RedisStore/downloads

Copy jar into the lib folder of your tomcat installation directory, then edit conf/server.xml file and within your context tag add the following lines:

<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="true" maxActiveSessions="1" minIdleSwap="1" maxIdleSwap="1" maxIdleBackup="1">
    <Store className="org.apache.catalina.session.RedisStore" 
        host="localhost"
        port="6379"
        password="something"
        database="0"
    />
</Manager>

Make sure that whatever you store in the session is Serializable.

Tags:

Suppress Tomcat error pages using Nginx

Posted: Tue, Mar 8 06:26 PM (PST)

You need to add proxy_intercept_errors on to nginx configuration.

listen          10.10.10.10:80;
server_name     www.example.com;
location / {
		proxy_pass      http://127.0.0.1:8180;
		proxy_set_header        Host            $host;
		proxy_set_header        Client-IP       $remote_addr;
		proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_intercept_errors on;
}
location /images/ {
		root /usr/local/apache-tomcat-6.0/webapps/ROOT/;
		expires max;
}
location /css/ {
		root /usr/local/apache-tomcat-6.0/webapps/ROOT/;
		expires max;
}
location /js/ {
		root /usr/local/apache-tomcat-6.0/webapps/ROOT/;
		expires max;
}
error_page 500 502 503 504 404 = /404.html;
location /404.html {
		rewrite ^ http://www.example.com/ permanent;
}
Tags: