Category Archives: Groovy

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 http://www.arquetipos.co.cr/blog/files/grails-image-tools-1.0.3.zip

Domain-Class

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 && pictureInstance.save()){
String imagepath = grailsAttributes.getApplicationContext().getResource("images/").getFile().toString() + File.separatorChar + "${pictureInstance.id}.jpg"
downloadedfile.transferTo(new File(imagepath))

imageTool.load(imagepath)
imageTool.thumbnail(140)

imageTool.writeResult(imagepath, "JPEG")
imageTool.square()
flash.message = "Picture ${pictureInstance.id} created"
redirect(action:show,id:pictureInstance.id)
}
else {
render(view:'create',model:[pictureInstance:pictureInstance])
}
}

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

<td><img src="${createLinkTo(dir:'images', file: pictureInstance.id+'.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
>>>None

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!


# javazquez.com
==========MERGE SORT========

-------------RUBY----------------

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)
  end
  result.concat((left.length > 0 ? left : right))
  return result
end

ary=[1,5,14,3,2,45,2,0,01,-1]
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]):
            result.append(right.pop(0))
        else:
            result.append(left.pop(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-------------
-module(mergesort).
-export([ms/1,msTestSuite/1]).

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

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

%to test, run mergesort:msTestSuite(run).
msTestSuite(run)->
	[mstest1(run),mstest2(run),
	mstest3(run),mstest4(run),
    mstest5(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++]
		}
        else{
			result += rht[rcnt++]
		}
     }
    if(lcnt < lft.size()){ 
		result +=  ms(lft[lcnt..< lft.size()]) 
	}
    else{
		result += ms(rht[rcnt..< rht.size()])
	}
    return result
}

sl=[3,88,5,3,2,1,-2,2]
println ms(sl)



# javazquez.com
========QUICKSORT========

-----RUBY----------------
def quick_sort(ary)
  return ary if(ary.length <= 1)
  greater,less = [],[]
  pos = rand(ary.length)
  pivot = ary[pos]
  ary.delete_at(pos)
  ary.each{|item|
       (item < pivot) ? less << item :greater << item}
  return (quick_sort(less) << pivot).concat(quick_sort(greater))
end

ary=[1,5,14,3,2,45,2,0,01,-1]
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)

ary=[1,5,14,3,2,45,2,0,01,-1]


----------Erlang Quicksort--------------
-module(quicksort).
-export([qsort/1]).

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()))
	lst.each{item-> 
		if(item < pivot){ less.add(item)}
		else{greater.add(item)}
	}
	return quickSort(less)+[pivot]+quickSort(greater)
}
print quickSort([1,5,14,3,2,45,2,0,01,-1])


Recursive Directory Search with Ruby and Groovy

A while back I was bored and decided I need to brush up on my Ruby chops. I had been wanting to play with threads for quite some time and couldn’t think of anything that would be a fun project to do…until this crazy idea hit me.  Wouldn’t it be cool if could generate multiple threads to search different servers for any file of my choosing?” The code I wrote doesn’t directly do this, but with some minor tweaks it could be done.

I took that idea and ran with it using Ruby. After I finished coding, I thought I would try writing it from scratch using my second favorite language, Groovy (Ruby is my first).  I have to admit, writing the Groovy code was more intuitive because of the baked in file/directory iterators. I refactored my Ruby code a few times and ended up using the find module to maximize performance. Below is the code, and as always, I am open to suggestions on other ways of doing it 😀

Ruby code
 

#########################
#  Juan Vazquez
#  http://javazquez.com
#########################
require 'find'
class DirectoryWizard
  attr_accessor :root_dir,:exts, :thread_cnt, :thread_tracker, :count
  #initialize with a root , and file extensions
  def initialize(root, t_count,*extensions)
    @root_dir, @exts, @thread_cnt , @thread_tracker, @count = root, extensions, t_count, [], 0
  end

  def start_looking
    begin
      puts Dir.entries(@root_dir).select{|dir_item| is_in_ext(dir_item) }
      list_dirs(@root_dir).each do|di|
        @thread_tracker << Thread.new(@root_dir+di){|directory| 
                                             recursive_file_search(directory) }
        wait_for_running_threads  if(@thread_tracker.size > @thread_cnt)
      end
      wait_for_running_threads
    rescue Exception => e; puts e;
    end
  end
  def recursive_file_search(directory)
    Find.find(directory){|dir_item|
      if(is_in_ext(dir_item))
       @count+=1
       puts dir_item
      end
    }
  end

    #return array of immediate subdirectories excluding . and ..
  def list_dirs(directory)
   Dir.entries(directory).select{|fh|(!is_p_c_directory?(fh) && 
                                          File.directory?(directory+fh))}
  end

  #return an array of all file/directories excluding '.' and '..'
  def list_contents(directory)
    Dir.entries(directory).delete_if{|x| is_p_c_directory?(x)}
  end

  #is Parent or Current Directory
  def is_p_c_directory?(filename);(filename =="." || filename == "..");end
  
#return an array of files that match ext
  def is_in_ext(dir_item); @exts.detect{|ext| dir_item.match(ext)}; end
 
 def wait_for_running_threads
    @thread_tracker.each{|th|th.join}
    @thread_tracker=[]
  end
end #end class


t= DirectoryWizard.new("\\\\server\\e$\\profiles\\",16,'filename')

t.start_looking

puts "Done with Program count is #{t.count}"

Groovy Code

import java.util.regex.*;
class DirWiz{
   def root_dir, exts, thread_max_cnt, thread_tracker, count

   public DirWiz(String basedir, int t_count, List extensions){
        this.root_dir = basedir
        this.exts = compile_regex(extensions)
        this.thread_max_cnt = t_count
        this.thread_tracker = []
        this.count=0
    }
    def start_looking(){
      try{
          def dir = new File(this.root_dir)
           check_for_files(this.root_dir)
          //recursively search directories
           dir.eachDir{ subDir->
            //thread it off
           if(this.thread_tracker.size() > this.thread_max_cnt){
               this.thread_tracker.each{it->it.join()}
               this.thread_tracker=[]
           }
           this.thread_tracker << Thread.start{
                 subDir.eachFileRecurse{ fh -> 
                    check_using_compiled_regex(fh.canonicalPath)
                 }
           }
        }
      }catch(Exception e){
        println("error ${e}")
      }
      this.thread_tracker.each{it->it.join()}
      println("Done")
    }
   def print_if_match(String file){this.exts.each{ext->
                if(file=~ext){this.count+=1;println(file)}}
   }
   def check_using_compiled_regex(String file){
    try{
	def var = this.exts.find{it.matcher(file).matches()}
	if(var){this.count+=1;println(file)}
    }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def check_for_files(String dir){
      try{ new File(dir).eachFile{ file ->
	        check_using_compiled_regex(file.canonicalPath)
        }
      }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def compile_regex(List list){
    List ret_list=[]
    list.each{ ret_list <<    Pattern.compile(it,Pattern.CASE_INSENSITIVE)}
    return ret_list
   }
}


def t = new DirWiz('c:\\',16,[".*\\.jpg.*"])//look for jpegs
//def t = new DirWiz('\\\\server\\dir\\',16,["filname"])
t.start_looking()

println("Done with the program total number of files is ${t.count}")


 

 

Rotating Java Images

I am working on a swing flickr app and thought I would share some code to help those that are new to java gui programming( like me) and get them on their way to making their killer application.

I’ll start off with my first problem,  “How do I show an Image?” After looking through Java forums and going through my Java books, I settled on using Image Icons in JLabels. The next thing I wanted to do was rotate the image 90 degrees. I used Java’s Graphics class to accomplish this. The following groovy code loads 100 JLabels containing a JPEG of Pixar’s Wall-e that I had in the same directory rotated 90 degrees.

import java.awt.image.BufferedImage
import javax.swing.*
import java.awt.*;
import java.util.*;
import java.awt.image.AffineTransformOp
import java.awt.geom.AffineTransform

class ImageButton extends JLabel{
	ImageIcon picture

public ImageButton(ImageIcon icon){
	super(icon)
	this.setBackground(Color.BLACK)
	this.setForeground(Color.BLACK)
	this.picture=icon
	this.setPreferredSize(new Dimension(120,100))
}

public void rotateImage( int angle) {
	int w = this.picture.getImage().getWidth()
	int h = this.picture.getImage().getHeight()
	BufferedImage bi = new BufferedImage(w,h,
                      BufferedImage.TYPE_INT_RGB)
	Graphics bg = bi.createGraphics();
	bg.rotate(Math.toRadians(angle), w/2, h/2);
	bg.drawImage(this.picture.getImage(),0,0,w, h,
			0,0,w, h, null);

	bg.dispose()//cleans up resources
	this.setIcon(new ImageIcon(bi))
	this.setPreferredSize(new Dimension(this.picture.getIconHeight(),
                       this.picture.getIconWidth()))
	}
}

JFrame f= new JFrame()
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
JPanel panel=new JPanel();
def img= new ImageIcon("walle.jpg")
(1..100).each{i->
	def btn=new ImageButton(new ImageIcon(img.getImage()
                        .getScaledInstance(120,100,4)))
	panel.add(btn)
	btn.rotateImage(90)//rotate the image now
	println i
}

panel.setBackground(Color.BLACK)

f.setSize(300,400)
f.getContentPane().add(panel)
f.setVisible(true)

 

My first few attempts at the code gave me out of memory Heap errors. I unknowingly had BufferedImage references hanging around.  Once I realized this, I cleaned up my code and remembered to call dispose() on the graphics bg object and everything came together quite nicely.