Groovy Bar & Grill

December 9, 2008

ReverseEcho.groovy

Filed under: Groovy Grill — jawild59 @ 10:23 pm

There’s a great line from the movie, The Truman Show, that explains why Truman never questioned his life circumstances: “We accept the reality of the world with which we’re presented.” It’s the same with Java. We didn’t know how tedious it was until Groovy showed us a better way.
Just how tedious is Java. Let’s look at an example that prints out the reverse of the command line arguments (e.g. “This is a test” prints out as “tset a si sihT”)


public class ReverseEcho {
  public static void main(String[] args) {
    for (int i = args.length - 1; i >= 0; i--) {
      for (int j = args[i].length() 1; j >= 0; j--) {
        System.out.print(args[i].charAt(j));
      }
      System.out.print(" ");
    }
  }
}
  

When you don’t know any better, well, that’s what you have to do: set up nested for loops and traverse in reverse. You’re happy as a bit in a bucket until Groovy comes along and presents a new reality.


args.reverseEach {
  print "${it.reverse()} "
}

Yep, Groovy really makes it that easy. args is an implicitly defined list that contains the command line arguments. reverseEach() is a shortcut (a concept mostly absent in Java) for reverse().each() and iterates over each element in the list in reverse order. reverse() is also a GDK method on string and does exactly what you might think, it creates a new string which is the reverse of the original.

Fibonacci.groovy

Filed under: Groovy Grill — jawild59 @ 6:49 pm

One of the ugliest constructs in Java is the for loop. The enhanced for in Java 5 improved readability but Groovy has alternatives that are even better. Let’s take a look. Here is Java code (from Java Examples in a Nutshell, 2nd Ed.) that prints the first 20 Fibonacci numbers:


public class Fibonacci {
  public static void main(String[] args) {
    int n0 = 1, n1 = 1, n2;
    System.out.print(n0 + " " + n1 + " ");

    for (int i = 0; i < 18; i++) {
      n2 = n1 + n0;
      System.out.print(n2 + " ");
      n0 = n1;
      n1 = n2;
    }
  }
}
  

Typical stuff; for is utilized to execute a loop a certain number of times, in this case eighteen. Groovy handles this much better.


def list = [01]

20.times {
  print "${list.last()} "
  list << list.sum()
  list = list.tail()
}

Because everything’s an object in Groovy, 20 is an Integer with all the extra methods supplied by the GDK. The times() method effectively executes the closure 20.intValue() number of times.

There’s some cool stuff going on with the Groovy list too; Instead of using 3 variables to track 2 values, we use a variable size list. Each iteration of the closure prints the last element in the list. Next, we sum up all the list elements and push the value onto the end of the list. list.trail() then lops off the first element in the list so we’re left with the next two numbers in the Fibonacci series.

August 18, 2008

gMd5Sum

Filed under: Groovy Grill — jawild59 @ 6:35 am

I’ve written a Groovy version of winMd5Sum, a MD5 checksumming utility.

Visit the gMd5Sum page for download and more.

One of my objectives was to explore Java’s system tray feature (so you’ll need Java 6.) It works (clicking on the red X in the upper right hand corner minimizes the application to the system tray) but SwingBuilder has no implementation (as far as I can tell) so it’s coded wholly outside SwingBuilder. I haven’t attached a popup menu to the tray icon yet, that’s on the roadmap.

SwingBuilder has some hidden features that aren’t necessarily very intuitive. For example, I set the system look and feel with this code:

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

until I ran across this (much Groovier) method:

swing.lookAndFeel 'system'

source code is now available on the google code site.

October 6, 2007

Grails != Groovy

Filed under: Groovy Bar — jawild59 @ 7:45 am

Anyone remember the Amiga? My memory may be a bit fuzzy, but I remember its architecture as being light-years ahead of its time. One of its most remarkable features was its ability to display millions of colors at a time when the PC was limited to 16. Because of its advanced color and graphic capabilities, it eventually became the basis for NewTek’s Video Toaster, an advanced (for its time) and inexpensive (for its time) video processing system. We’re talking at least 15 years ago, when video on the PC wasn’t even a pipe dream.

So, where am I going with this? The Amiga’s strengths were its downfall. It was relegated to a niche market and eventually withered on the vine. It seems to me that a disproportionately large portion of the buzz around Groovy (what buzz there is) is centered around Grails. Now, Grails may be great, but Groovy is so much more. If Grails becomes the primary reason to adopt Groovy and then loses its head-to-head bout with ROR, Groovy may go the way of the Amiga: excellent but ignored.

April 11, 2007

Groovy TimeBox

Filed under: Groovy Grill — jawild59 @ 5:05 am

Here’s my humble solution to the TimeBox quiz posted over at GroovyQuiz.

Screenshot

Screenshot

A couple of things I think are noteworthy

  1. Populating a comboBox with a range is slick. comboBox(items:1..12) results in Integers with values 1 – 12 inserted into the combo box model. Getting the selected value is even slicker: cb.selectedItem.
  2. SwingBuilder doesn’t make it any easier to work with layout managers, at least as far as I could see. Not that I expected it to but it would have been nice.
  3. Lesson learned: ’5′ as Integer is NOT the same as ’5′.toInteger().
  4. Because I used SwingWorker, Java 6 is required.

download and rename to Timebox.jar

[Update: Rather than repost code as I make changes, I'll provide a link to download the code and include a current screen shot so you can determine if you've got the most recent version]

March 7, 2007

Grails Finds Multiple ApplicationBootStrap Files

Filed under: Grails — jawild59 @ 9:42 pm

GRAILS-920

[Update: Three weeks and no affirmation about this issue. I get the same error  on my work PC, so I don't think it's my environment. Nevertheless, I upgraded to Java 6 U1 and now I merely get the "native2ascii" error. Grails is unusable since I can't generate any views. Guess I'll wander over and take a look at GWT.]

February 26, 2007

Groovy Principle of Least Surprise Violation?

Filed under: Groovy Bar — jawild59 @ 9:21 pm

Anyone else surprised this code works?

class Book {
private title
}

def book = new Book()
book.title = 'Principle of Least Surprise'
assert book.title == 'Principle of Least Surprise'

Since title is private, shouldn’t I have to access it via getters and setters?

September 14, 2006

Groovy Category Example

Filed under: Groovy Grill — jawild59 @ 9:43 pm

I cut my Java teeth on an old edition of Java Examples in a Nutshell. I thought it might be a good exercise to translate some of the Java code to Groovy. By the second example in the book I realized I was right. The example prints out every number from 1 to 100, except that if the number the number is divisible by 5 it prints “fizz,” if it is divisible by 7 it prints “buzz,” and if it is divisible by both 5 and 7 it prints “fizzbuzz.”

Like most examples in the book, the Java code is not exactly exemplary, as evidenced here:

public class FizzBuzz {
    
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            if (((i % 5== 0&& ((i % 7== 0))
                System.out.print("fizzbuzz");
            else if ((i % 5== 0)
                System.out.print("fizz");
            else if ((i % 7== 0)
                System.out.print("buzz");
            else
                System.out.print(i);
        System.out.print(" ");
    }
}

I like self-documenting code so rather than use comments to explain the logic, I try to write code that is readable by non-programmers. Using a Groovy Category to add a method to an existing Java class makes that job easier. Since the Category examples on the Groovy site are not very intuitive, I thought I’d share an example here:

use (Multiplicity.class) {
  range = 1..100
  range.each {number ->
    if (number.isMultipleOf(5&& number.isMultipleOf(7)) {
      print "fizzbuzz"
    else if (number.isMultipleOf(5)) {
      print "fizz"
    else if (number.isMultipleOf(7)) {
      print "buzz"
    else {
      print "${number}"
    }
    print " "
  }
}
  
class Multiplicity {
  static boolean isMultipleOf(Integer dividend, Integer divisor) {
    dividend % divisor == 0
  }
}

This is what I like about Groovy. Not only is there less code (fewer keystrokes) but (and maybe more importantly) there is less to read in order to grasp the logic.

August 29, 2006

Groovy Log Splitter

Filed under: Groovy Grill — jawild59 @ 9:46 pm

Matt and Blaine are having fun writing Ruby log splitters. I couldn’t pass up the opportunity to write one in Groovy, so here it is:

  baseFilename = args.size() ? args[0"split.log"
  maxLines = args.size() == ? args[1500000
  fileCount = 0
  lineCount = 0
  inputFile = new File(baseFilename)
  writer = newWriter(baseFilename)
  inputFile.eachLine {
    if (lineCount >= maxLines) {
      writer = newWriter(baseFilename)
    }
    writer.append("${it}\n")
    lineCount++
  }
  
  def newWriter(filename) {
    lineCount = 0
    new File("${fileCount++}_${filename}")
  }

August 16, 2006

Extraneous Period in Groovy println

Filed under: Groovy Grill — jawild59 @ 1:26 pm

Update: Looks like it’s a problem in GroovyTestCase. testXXX() method always outputs a “.”

Update: Ah. It’s JUnit’s text-based test runner that is the culprit. Guess I shouldn’t exclusively use the GUI runner.

GROOVY-1463.

Running this test:

class PrintlnTest extends GroovyTestCase {
  void testSomething() {
    def name = GroovyTestCase.class.simpleName
    assertEquals(GroovyTestCase.class.simpleName, name)
    assertTrue(name.length() == "GroovyTestCase".length())
    println name
    println name
  }
}

produces this output:

.GroovyTestCase
GroovyTestCase

Time: 0

OK (1 test)

Anyone have a clue?

Older Posts »

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.