Category Archives: code

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 ‘’ )
authSite.auth.basic ‘user’, ‘pwd’
println authSite.get( path:’testAuth.html’ )

Fun with Python

Hey there fellow developers πŸ˜€
I have been working with Python lately(specifically Python3) and wanted to share some things I thought were pretty cool from an outsider’s(learning the language) perspective. I hope the following helps with getting to know this great language.. Enjoy

#construct a tuple using()

#contruct a list using [] 
 lst= [1,2,4]

#iterate a string and print each character
for i in "This is a String":
#getting the length of a string 
print ("length is",len("12345"))	

#test x is in a range
if(3< x <10 ):
	print( "I am true")
	print( "I am false")
#test membership

if "2" in "1234":
	print("I am in the string")
if int("2") in [1,2,3,4]:
	print( "I am in the list")

print( "hithreetimes, "*3)

#using math class
import math

#print all methods

#named Tuples
import collections
Movie = collections.namedtuple("Movie","title rating")
collection =[Movie("Jaws", 4.0)]
collection.append(Movie("Toy Story", 5.0))
for movie in collection:
	print("I watched {0} and gave it {1} stars".format(movie.title,movie.rating))

#sequence unpacking
head, *rest = [1,2,3,4,5]
print("head is {0} and rest is {1}".format(head,rest))

#passing and unpacking parameters
def fullname(f,m,l):
	print("First Name ="+f)
	print("Middle Name ="+m)
        print("Last Name  ="l)

fakenamelist =["Homer","J","Simpson"]

#list comprehensions (print all odd numbers from 0 to 99)
print( [item for item in range(0,100) if item % 2])

#named parameters
def count_animals(number,*,	animal="ducks"):
	return "{0} {1}".format(number,animal)
print( count_animals(3,animal="cows"))
print( count_animals(3))

print(sorted([-1,2,-3],key=abs)) #same order

line = input("enter something.. ")
print("your line was " ,line)

I have been using python for web requests and recommend using the httplib2 library. It has a lot of really nice features.

Ruby’s variable variables

Hello everyone,

This is a quick post that should help developers new to Ruby. It may also help out those that have been away from the language for a while. Its just a quick reference to Ruby’s variables and their respective scopes. I know I had a chart to keep it all straight when I first encountered the language.

  1. @ An instance variable
  2. [a-z] or _ A local variable
  3. [A-Z] A constant
  4. @@ A class variable
  5. $ A global variable

This information is easily found on the net if you know what you are looking for. I just posted it to help make it even easier to find for those that are new to Ruby, or new to code writing πŸ™‚ .

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.


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.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) {
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}"
}//end for


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

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()
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 ))


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)


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

Adding and Resizing Images with Grails

Here is a quick post on how to upload images within your Grails project to your file system(rather than your database). It seems simple enough, but I ran into a few snags as I was working on one of my projects. Just wanted to provided a working example for those that are entering the Grails territory for the first time. Happy Coding!

I am using the imageTools plugin which you can read more about here

NOTE: The imageTools plugin has been criticized for its low quality of output. ImageMagick may be a better fit for you project(s). My particular project didn’t call for high quality pictures. A quick google search for “imagemagick for grails” should get you started on your way.

I am using version 1.0.3 in the example below

to install, I ran the following command from my grails application’s root directory

grails install-plugin


class Picture {
byte[] imagefile
//Any other stuff you want to track


Controller Code for Saving an image

def save = {

def downloadedfile = request.getFile('imagefile')
def pictureInstance = new Picture(params)
def imageTool = new ImageTool()

if(downloadedfile &&{
String imagepath = grailsAttributes.getApplicationContext().getResource("images/").getFile().toString() + File.separatorChar + "${}.jpg"
downloadedfile.transferTo(new File(imagepath))


imageTool.writeResult(imagepath, "JPEG")
flash.message = "Picture ${} created"
else {

Code for displaying the image in both the ‘show’ and ‘list’ views

<td><img src="${createLinkTo(dir:'images', file:'.jpg' )}" /> </td>

Mergesort and Quicksort with Dynamic Languages

The other day I was flipping through an algorithms book and came across a section on sorting. I remembered that I had a blast writing them c++ during my undergrad and thought it would be fun to write them in a couple of different languages. I settled on writing a quicksort, and mergesort.
Interesting notes:
1) Python(2.5) returns a None type when appending a value to an empty list which forced me to use ‘+’
>>> ex= [].append()
>>> print ex

2) Groovy gave me a java.util.ConcurrentModificationException when I transcribed my Ruby code to Groovy. Because of the fact that I was deleting items from a list that I would read in later(while loop which checks size of left and right), I got this error. Accounting for that, the groovy code is pretty nasty.(anyone that would like to provide a better example without relying on the built in Collections.sort(list) would be welcome)

Here is my code… enjoy!

==========MERGE SORT========


def merge_sort(ary)
  return ary if (ary.length <= 1)
  half = ary.length/2
  left = merge_sort(ary[0...half])
  right = merge_sort(ary[half..ary.length-1])
  result =[]
#compare first left and first right
  while left.length > 0 and right.length > 0
    result << (left[0] < right[0] ? left.shift : right.shift)
  result.concat((left.length > 0 ? left : right))
  return result

p merge_sort(ary)

-----------Python Mergesort-------------

def merg_sort(lst):
    if(len(lst) <= 1):  return lst
    left = merg_sort(lst[:len(lst)/2])
    right = merg_sort(lst[len(lst)/2:len(lst)])
    result = []
    while len(left) > 0 and len(right)> 0:
        if( left[0] > right[0]):

    if(len(left)>0): result.extend(merg_sort(left))
    else: result.extend(merg_sort(right))

    return result

print merg_sort([8,7,43,2,5])

--------Erlang Mergesort-------------

break([]) -> [];
break([L]) -> [L];
break(List) ->
    {Left, Right} = lists:split(length(List) div 2, List),

merge(L, []) -> L;
merge([], R) -> R;
	 Lh < Rh -> [Lh | merge(Ltail,[Rh|Rtail])];
	 Lh >= Rh -> [Rh | merge(Rtail,[Lh|Ltail])]

%to test, run mergesort:msTestSuite(run).

mstest1(run)-> ms([3,2,1]).
mstest2(run)-> ms([3,3,3,1]).
mstest3(run)-> ms([]).
mstest4(run)-> ms([1]).
mstest5(run)-> ms([123,0,-1,23,2,34,5,678,7,5,8]).	 

-------------GROOVY MERGESORT--------
def ms(lst){
    if(lst.size() <= 1){return lst}
    def sz=lst.size()
    int half = (int)(sz/2)
    def l = lst [ 0 .. < half]
    def r = lst [ half.. < sz]
    def lft = ms(l)
    def rht  = ms(r)
    def result = []  
    def rcnt = 0
    def lcnt = 0
   while( lcnt < lft.size() && rcnt < rht.size()){
        if(lft[lcnt] < rht[rcnt]){
        	result += lft[lcnt++]
			result += rht[rcnt++]
    if(lcnt < lft.size()){ 
		result +=  ms(lft[lcnt..< lft.size()]) 
		result += ms(rht[rcnt..< rht.size()])
    return result

println ms(sl)


def quick_sort(ary)
  return ary if(ary.length <= 1)
  greater,less = [],[]
  pos = rand(ary.length)
  pivot = ary[pos]
       (item < pivot) ? less << item :greater << item}
  return (quick_sort(less) << pivot).concat(quick_sort(greater))

p quick_sort(ary)

----------Python Quicksort--------------

import random
def quickSort(lst):
	if(len(lst) <= 1):return lst
	greater = []
	less = []
	pivot = lst.pop(random.randint(0,len(lst)-1))
	for item in lst:
		if(item < pivot): less.append(item)
		else: greater.append(item)
	return quickSort(less)+[pivot]+quickSort(greater)


----------Erlang Quicksort--------------

qsort([]) ->[];
qsort([Pivot|T]) ->
		lists:append( [qsort([X || X <- T, X < Pivot]),
		[Pivot], qsort([X || X <- T, X >= Pivot]) ).

-------GROOVY QUICKSORT--------------
def quickSort(lst){
	if(lst.size() <= 1){return lst}
	def greater = []
	def less = []
	def pivot = lst.remove(new  Random().nextInt(lst.size()))
		if(item < pivot){ less.add(item)}
	return quickSort(less)+[pivot]+quickSort(greater)
print quickSort([1,5,14,3,2,45,2,0,01,-1])

Fun with Python and Gmail API

Yesterday I decided to play with Gmail’s API in order to grab my contacts. To my surprise, it was a snap. Google has instructions for python Here, I wrote my example using Python 2.5 on OS X. Once I had unzipped the GData contents, I just changed to the GData directory and ran
sudo python install
and I was ready to go.

Python Documentation for GDATA

# Google GMAIL API example
import gdata.contacts.service

user = ''
pwd = 'password'
client2 = gdata.contacts.service.ContactsService()
# Authenticate using your Google Docs email address
# and password.
client2.ClientLogin(user, pwd)
contacts_feed = client2.GetContactsFeed()

# NOTE: The GetContactsFeed does not give back
# all contacts.
# This 'problem' can be solved by looping
# until the contacts_feed.GetNextLink
# returns None.
while(contacts_feed) :
for x in contacts_feed.entry:
ret = contacts_feed.GetNextLink()
contacts_feed = client2.GetContactsFeed(ret.href) if(ret) else ret

print "here are your %d contacts" % len(l)
for contact in l:
print "%s -> %s" % (contact[0],contact[1])


here are your xxxx contacts

Ruby to Python Primer

If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It’s not Ruby πŸ˜€ , but it can get the job done. Here is a quick list of similarities between the two languages. I hope it helps… don’t forget to this list in the comments section πŸ˜‰

#-----find object methods-----
s="hello, I am a string"

puts s.methods

print dir(s)

#find out more about a method using python

#-----view object's class-----


#------Iterate hashes-------

h.each{|key,value| puts "#{key}, #{value}"}

for key,value in h.iteritems():
print key, value

#---ternary operators

condition ? var = x : var = y

#python.. not exactly an operator, but you get the meaning
#---- var = y if condition is false
var = x if condition else y

s="hello, I am a string"
puts "Length of string is #{s.length} or #{s.size}"

puts "Length of hash is same as string, #{h.length} or #{h.size} "

print("This is the length of a string %s" % len("string"))
print("number of key/value pair= %d" % len({'one':1,'two':2}))

#---slicing lists/arrays

l[1..3] #=>[2,3]

l[1:3] #=>[2,3]

#--print string multiple times-----

4.times{print "hello"} #=> hellohellohellohello

print("hello" * 4) #=> hellohellohellohello


So for my own geeky pleasure, I decided to try writing cgi scripts with Ruby, Python, PHP, and Perl. Β All had readily accessible documentation on how to POST to a https URL but ruby. My first thought was to look at the Net:HTTP documentation found HERE.

The one example I wanted was not listed. I did some searching around and pieced together the following code. I hope this is as big a help to you as it was to me. Looking at it, It seems pretty intuitive….but if your like me, sometimes you need it spelled out πŸ˜€

As a side note, setting path to path = ‘/../’ is my work-around for a script that is mapped to rather than ‘/some_POST_handling_script.rb’

#Juan Vazquez ->
require 'net/http'
require 'net/https'
http ='', 443)
http.use_ssl = true
#path(a.k.a) ->'
path = '/some_POST_handling_script.rb'
data = 'badguy=Gargamel'

headers = {'Content-Type'=> 'application/x-www-form-urlencoded'}

resp, data =, data, headers)

puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data