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:

Executing External Processes From Grails

Posted: Thu, Mar 10 04:12 AM (PST)

Simple exec method as shown below to run sub processes from groovy / grails. If you run the standard exec like:

def cmd = "/bin/ls -la"
def proc = cmd.execute()
proc.waitFor()

But I have other advanced solution for you. Where you can read response from your executed program. See below:

def command = "/bin/ls -la"
StringWriter stringWriterOutput = new StringWriter()
StringWriter stringWriterError = new StringWriter()
Process proc = command.execute()
stringWriterOutput << proc.in
stringWriterError << proc.err
proc.waitFor()
Tags: