Posts Tagged Groovy

Finding Duplicate Ints: Ruby and Groovy

I am going back to my old standard playtime function, finding the duplicated integer in a set of integers. I have been playing around a lot more with Groovy lately and I realized that I had never really done a Groovy version of that little function.

1
2
3
4
5
6
def findDups( n ){
    n.sort()
    for( i in (1..n.size())){
        if(n[i] == n[i-1]) return n[i]
    }
}

In this case, I am allowing null to be the value returned when no duplicate is found. It does seem to be a more realistic value for Groovy. It’s a pretty straight forward function, along the same lines as the other languages. I thought maybe I could find some really cool feature of Groovy that would make this radically different from the Java version… nope. It does collapse nicely down to a single line though:

1
def findDups( n ){ n.sort(); for( i in (1..n.size()) ) if(n[i] == n[i-1]) return n[i] }

If you like that sort of thing.

Shortly after, I decided to do a quick little Ruby version as well:

1
2
3
4
5
6
7
def findDups( n )
    n.sort!()
    for i in (1..n.size())
        if(n[i] == n[i-1]) then return n[i] end
    end
    return nil
end

Nothing exciting in either case, but worth doing for completeness.

Popularity: 3% [?]

  • Share/Bookmark

Tags: , , ,

Groovy Unit Testing: Tools

The Java Metroplex User Group meeting last night was a presentation on unit testing and mocking with Groovy, presented by Venkat Subramaniam, a well-known author and consultant… and a great presenter to watch, by the way. In his presentation he showed various techniques for using Groovy to write unit testing for both Java classes and other Groovy classes.

Count me among the converted, but I was not sure just how easy it would be to bring Groovy into a Java project while still maintaining good Eclipse and Maven support. So, I did a quick little experiment and found out that the integration is trivial.

Say you have a maven project, we’ll call it “groover”, already hapily running maven under Java 6 and Maven 2. Add the following dependencies (assuming you dont already have JUnit 4):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.6</version>
    <type>jar</type>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy</artifactId>
    <version>1.7.0</version>
    <type>jar</type>
    <scope>test</scope>
</dependency>

You now have maven setup to run unit tests written in Groovy (assuming you have Groovy 1.7 installed locally as well).

To get everything working in Eclipse, import your project (if it’s not already in Eclipse) and be sure you have the Groovy Eclipse plug-in installed. You may also want/need the Maven Eclipse plug-in, but that is not a requirement. Once the project is imported, right click on the project name and convert it to a Groovy project. Now Eclipse is ready to go too.

Let’s proove that it works by writing a simple little class and a Groovy test for it:

1
2
3
4
5
6
7
package foo;

public class Something {
    public String doIt(String in){
        return in.concat(" gabadata!");
    }
}

and then the test is:

1
2
3
4
5
6
7
8
9
10
11
12
package foo

import org.junit.Test
import static org.junit.Assert.*

class SomethingTest {
    @Test
    void doIt(){
        def result = new Something().doIt('foo')
        assertEquals "foo gabadata!", result
    }
}

Run the test using Ctrl+Alt+X T (normal JUnit run command in Eclipse) and it works just like any other JUnit test. Run the test in a console with maven with “mvn test” and it still works just like normal.

My next thought was that surely it would not work with my coverage tools! I was wrong, coverage worked fine in both the IDE and in maven.

So, by writing unit tests in Groovy I get to write less code, have built in powerful mocking support, and no tool integration issues? Sign me up!

Popularity: 47% [?]

  • Share/Bookmark

Tags: , , ,

Blissful Development

I have been working on a personal project to create a movie catalog database for our collection of movies. Yes, there are a handful of both desktop and web-based applications available to do this, though, they all seem to be lacking in one feature or another… and I needed an interesting useful project. This project has been one of my most enjoyable personal development projects; if you have ever seen my project graveyard, you know there have been quite a few that didn’t get very far for one reason or anther, usually time and/or complexity.

I owe my development-bliss on this project to something not usually found on modern software projects (at least in my experience)… simplicity. No, not simplicity of the project goals, but of the tools and the environment. For development I am using my favorite text editor, Notepad++, Cygwin (yes, I am doing this on Windows… I have not yet found a good solid text editor for Linux, perhaps I will have to make peace with vi)… and that’s it unless you want to count Firefox. But, wait… where is the IDE, the pile of plug-ins, and tools? Well, okay… I am also using Grails along with JQuery and JQueryUI. That’s the key… Grails.

With this environment I have been able to focus on building my application, not plumbing and other mundane details. I have an almost instant turn-around on changes to domain and controller classes, as well as a simple yet flexible syntax that allows for less IDE overhead, hence the text editor. Heck, most of my actual coding has been the HTML and JavaScript for the front-end; I have modified a few scaffold controller actions, and added a few of my own, which have all been simple and straightforward. It truly is a pleasant environment to work with.

Groovy itself is quite nice, providing a much more rich syntax while still maintaining total support of Java and Java syntax. One of the features of Grails I have always appreciated is that you always have Java to fall back on if you need a bit more performance, or access to something that cannot be accessed through Groovy itself. The two languages really coexist quite nicely.

I have the core JavaDocs pretty much burned into my memory (:-)), but I wonder how less-seasoned developers would find this setup. Without an IDE you don’t get code completion or the other helpful features that help to boost the productivity of more junior developers. It’s not meant to be a hard-core developer test; I am not into that kind of stuff. I am all about making development easier… and this just feels right for Grails (and Groovy).

Java web application development has gotten too hard somewhere along the way.

Popularity: 1% [?]

  • Share/Bookmark

Tags: , , , ,

Simple Image Rotation

I did a little image rotation today so I figured I’d save my prototype code for future use. I am using Groovy to demo the code for this but the Java is exactly the same, just with a little more formality.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.awt.image.*
import java.awt.geom.*
import javax.imageio.*

def image = ImageIO.read(new File('trees.jpg'))
def w = image.getWidth()
def h = image.getHeight()

def degrees = Integer.parseInt(args[0])

def sin = Math.abs(Math.sin(Math.toRadians(degrees)))
def cos = Math.abs(Math.cos(Math.toRadians(degrees)))
def neww = (int)Math.floor(w*cos+h*sin);
def newh = (int)Math.floor(h*cos+w*sin);

def dst = new BufferedImage(neww,newh,image.getType())
def g = dst.createGraphics()

g.translate((neww-w)/2, (newh-h)/2);
g.rotate(Math.toRadians(degrees), w/2, h/2);
g.drawRenderedImage(image, null);            

if(ImageIO.write(dst,'jpg',new File('trees_rotated.jpg'))){
    rintln "Success!"
} else {
    println "Oh no!"
}

This reads in the original image file, rotates it by the specified number of degrees and corrects the translation and new image size so that image does not have any odd artifacts from the rotation.

This should work for any positive and negative rotation value.

Popularity: 1% [?]

  • Share/Bookmark

Tags:

Scaling Images With Groovy

I had the need to scale some large JPG images from my camera so I whipped up a quick little Groovy script to do the trick. Thought I would share.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// groovy ScaleImages.groovy DIRNAME SCALE%
   
import javax.imageio.ImageIO
import java.io.File
import java.awt.Image
import java.awt.Color
import java.awt.image.BufferedImage
   
class ScaleImages {
   
    static void main(String[] args){
        def directory = new File(args[0])
        if(!directory.isDirectory()){
            System.out.println("You must specify a valid directory!")
            System.exit(0)
        }
   
        def scale = Integer.valueOf(args[1])
   
        directory.eachFile {
            def image = ImageIO.read(it)
            int w = image.getWidth() * scale / 100
            int h = image.getHeight() * scale / 100
   
            def scaled = image.getScaledInstance(w,h,Image.SCALE_SMOOTH)
   
            def newImage = new BufferedImage(w,h,image.getType())
            def graphics = newImage.createGraphics()
            graphics.drawImage(scaled,0,0,w,h,Color.white,null)
           
            if(ImageIO.write(newImage,"jpg",new File(it.getParent(),"scaled_" + it.getName()))){
                System.out.println("scaled: " + it);
            } else {
                System.out.println("failed: " + it);
            }
        }
    }
}

It’s pretty simple. You load the image file to create a BufferedImage. You then create a scaled Image and draw it onto the new empty BufferedImage and save it off. I would recommend some performance enhancements if you are doing huge batches of images but for a directory containing a handful of images it works great and pretty fast. Also, note that this does not handle sub-directories of images, only the directory that you give it.

Popularity: 1% [?]

  • Share/Bookmark

Tags: ,

Cruise Control Project Operations (Groovy)

Yesterday I posted a little Ruby script for performing [CruiseControl](http://cruisecontrol.sourceforge.net) operations (see Cruise Control Project Operations); I got to thinking last night that this would also be quite easy to do in Groovy… and it was:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package cc;
   
class CruiseExec {
    private static cruiseUrl = 'http://builder:8000';
    private static projects = ['nightly-build','releases','site-build']
       
    static void main(args) {
        def operation = null;
        if(args.length == 0 || args[0] == null){
            System.out.println("No operation specified!")
            System.exit(0)
        } else {
            operation = args[0]
        }
   
        if(args.length == 2 && args[1] != null) projects = [args[1]]
     
        projects.each { project ->
            def url = new URL("${cruiseUrl}/invoke?operation=${operation}&objectname=CruiseControl+Project%3Aname%3D${project}")
            def success = url.getText().contains('Invocation successful')
            System.out.println("${project}.${operation}: ${success}")
        }
    }
}

It was very easy, easier than Ruby in fact since I work primarily in Java so I did not have to go looking up odd syntax questions as I did when writing the Ruby version. It is interesting to note that in this version I took the more Object oriented approach and wrote a class rather than a naked script. You could pull the meat out of the main method and make an even shorter script version if you are so inclined.

It’s always interesting to compare the same functionality across different languages, so I thought I’d share. Also, it does perform the exact same functionality, so you are welcome to use this version as a replacement for the Ruby version.

Again, I have attached the source code, in case the browser cut-and-paste messes things up for you:

Popularity: 1% [?]

  • Share/Bookmark

Tags: ,

Playlist Randomization

I love WinAmp; however, I have always felt that it’s playlist randomization was a little on the weak side. Not really wanting to dive into writing a C++ winamp plugin, I took the alternate approach of writing a Groovy script to randomize playlist files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// PlaylistRandomizer.groovy
import java.io.File
import java.util.ArrayList
import java.util.Collections
import java.security.SecureRandom

def songs = new ArrayList()
new File(args[0]).eachLine {
    if(!it.startsWith('#')){
        songs << it
    }
}
   
Collections.shuffle(songs,new SecureRandom())
   
def writer = new File("random_${args[0]}").newWriter()
songs.each {
    writer.writeLine(it)
}
writer.close()
   
println 'Done.'

You execute it with the file name of the playlist you want to shuffle.

groovy PlaylistRandomizer rock_n_roll.m3u

and it will generate a new, shuffled file, random_rock_n_roll.m3u.

It’s pretty simple and straight-forward. I am sure that I could spend a bit more time with it and pare it down a bit, but isn’t quick simplistic functionality one of the benefits of scripting languages?

Note: I used SecureRandom instead of just the standard Random because it provides better shuffling, though the difference is not all that significant.

For some fun and practice, I should implement the same script in Ruby.

Popularity: 1% [?]

  • Share/Bookmark

Tags: ,

Switch to our mobile site