The Holy Java

Notes of a passionate Java EE developer

Posts Tagged ‘groovy’

Exposing Functionality Over HTTP with Groovy and Ultra-Lightweight HTTP Servers

Posted by Jakub Holý on April 4, 2012

I needed a quick and simple way to enable some users to query a table and figured out that the easiest solution was to use an embedded, ligthweight HTTP server so that the users could type a URL in their browser and get the results. The question was, of course, which server is best for it. I’d like to summarize here the options I’ve discovered – including Gretty, Jetty, Restlet, Jersey and others – and their pros & cons together with complete examples for most of them. I’ve on purpose avoided various frameworks that might support this easily such as Grails because it didn’t feel really lightweight and I needed only a very simple, temporary application.

I used Groovy for its high productivity, especially regarding JDBC – with GSQL I needed only two lines to get the data from a DB in a user-friendly format.

My ideal solution would make it possible to start the server with support for HTTPS and authorization and declare handlers for URLs programatically, in a single file (Groovy script), in just few lines of code. (Very similar to the Gretty solution below + the security stuff.)

Read the rest of this entry »

Posted in Java, j2ee | Tagged: , , | 4 Comments »

Groovy Grape: Troubleshooting Failed Download

Posted by Jakub Holý on April 2, 2012

If you use the Grape’s @Grab annotation to get dependencies for your Groovy scripts at runtime and their retrieval fails with the exception “General error during conversion: Error grabbing Grapes — [unresolved dependency: ...not found]” and a useless stack trace then you migth want to know that you can configure Ivy to log all the details of what is going on (what it is trying to download, where from, …), for example in the interactive groovysh shell:

groovy:000> org.apache.ivy.util.Message.setDefaultLogger(new org.apache.ivy.util.DefaultMessageLogger(org.apache.ivy.util.Message.MSG_DEBUG))
groovy:000> groovy.grape.Grape.grab(autoDownload: true, group: 'org.eclipse.jetty.orbit', module: 'javax.servlet', version: '3.0.0.v201112011016')
...
WARN: ==== ibiblio: tried
WARN:   http://repo1.maven.org/maven2/org/eclipse/jetty/orbit/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.orbi
...

You can likely also increase the log level by setting the system property ivy.message.logger.level to 4 (debug, see the Ivy Message class.)

(For the list of arguments that grab supports see GrapeIvy, namely the method createGrabRecord [btw, ext and type are ignored unless you also set classifier])

Posted in General, Java | Tagged: | Leave a Comment »

Tips And Resources For Creating DSLs in Groovy

Posted by Jakub Holý on November 13, 2011

Paul King had a very good presentation (last year’s slides) at JavaZone about why to use Domain-Specific Languages and how to create internal DSLs in Groovy. I’d like to list here few tips that he has mentioned but before we get to that, why would you want to create a DSL? Martin Fowler answers that in his Domain-Specific Languages book (2010). Some of the reasons are to have a higher-level, more focused and conscise representation that also domain experts can read and perhaps even write. You  have certainly already used a DSL such as regular expressions, CSS, SQL, Spock‘s BDD tests, build instructions in Gradle – these are rather technical but sometimes DSLs are also created to be used by business users, f.ex. for anti-malaria drug resistance simulation. (Want more DSLs in Groovy?).

Paul mentions one important thing – you can always make your DSL better, i.e. more fail-proof (case insensitive, support plural endings, …) and secure and more like a natural language but it all comes at a cost and you must evaluate when the cost overweights the benefit (beware the 80:20 rule).

Some of the Groovy DSL implementation tips:
Read the rest of this entry »

Posted in General, Java | Tagged: , | 2 Comments »

Groovy: Use @Canonical to Get Compiler-generated Equals, HashCode and ToString

Posted by Jakub Holý on November 2, 2011

Groovy makes it extremely easy to create Java beans with getters, setters, equals, hashCode, and toString:

@groovy.transform.Canonical
class Call {
   def method
   def args

   /* // custom impl. reusing the auto-generated one:
   String toString() {
      _toString().replaceFirst("^.*?Call", "")
   }*/
}

You can then do:

// Auto-gen. constr. with positional arguments:
def call1 = new Call("someMethod", "someArgs")
def call2 = new Call(method: "someMethod", args: "someArgs")
assert call1.getMethod() == call1.method
assert call2.equals(call1)
assert ([call1, call2] as Set).size() == 1 // hashCode

As you might have noticed, you may provide your own implementation of toString and reuse the auto-generated toString by calling _toString().

References

JavaDoc for @Canonical. You can also use separately any of: @ToString. @EqualsAndHashCode, @TupleConstructor. And may be check also the other available AST annotations such as Immutable and Synchronized and perhaps also groovy.beans‘s Bindable and Vetoable annotations, if you need true Java Beans.

Posted in General, Java | Tagged: | 1 Comment »

Groovy: Creating an Interface Stub and Intercepting All Calls to It

Posted by Jakub Holý on November 2, 2011

It’s sometimes useful for unit testing to be able to create a simple no-op stub of an interface the class under test depends upon and to intercept all calls to the stub, for example to remember all the calls and parameters so that you can later verify that they’ve been invoked as expected. Often you’d use something like Mockito and its verify method but if you’re writing unit tests in Groovy as I recommend then there is a simpler and in a way a more powerful alternative. Read the rest of this entry »

Posted in Java, Testing | Tagged: , | Leave a Comment »

Only a Masochist Would Write Unit Tests in Java. Be Smarter, Use Groovy (or Scala…).

Posted by Jakub Holý on October 18, 2011

If this post irritates you, here's st. positive to concentrate on

I like writing unit tests but Java doesn’t make it particularly easy. Especially if you need to create objects and object trees, transform objects for checking them etc. I miss a lot a conscise, powerful syntax, literals for regular expressions and collections, conscise, clojure-based methods for filtering and transforming collections, asserts providing more visibility into why they failed. But hey, who said I have to write tests in the same language as the production code?! I can use Groovy – with its syntax being ~ 100% Java + like thousand % more, optional usage of static/dynamic typing, closures, hundreds of utility methods added to the standard JDK classes and so on. Groovy support for example in IntelliJ IDEA (autocompletion, refactoring …) is very good so by using it you loose nothing and gain incredibly much. So I’ve decided that from now on I’ll only use Groovy for unit tests. And so far my experience with it was overwhelmingly positive (though few things are little more complicated by the positives more than compensate for them). Read on to find out why you should try it too.

(The arguments here focus on Groovy but I guess similar things could be said about JRuby, Scala etc. – with the exception of Java code compatibility, which you only get in Groovy.)

Few examples

Some of the example below use some Groovy magic but don’t be scared. You can write Groovy just as if it was Java and only learn and introduce its magic step by step as you need it.

Bean construction:

def testBean = new Customer(fname: "Bob", sname: "Newt", age: 42)
// Java: c = new Customer(); c.setFname("Bob"); c.setSname("Newt"); c.setAge(42);

(Of course this starts to pay of if either you don’t want to create a constructor or if there are “many” properties and you need to set different subsets of them (constructor with 4+ arguments is hard to read).)

Reading a file:

assert test.method() == new File("expected.txt").getText()
// Java: buffered reader line by line ...; Note: == actually uses equals()

Checking the content of a collection/map:

assert customerFinder.findAll().collect {it.sname}.sort() == ["Lizard","Newt"]
// Java: too long to show here (extract only surnames, sort them, compare ...)
assert getCapitalsMap() == ["UK" : "London", "CR" : "Prague"]

Regular expressions:

assert ("dog1-and-dog2" =~ /dog\d/).getAt([0,1]) == ["dog1", "dog2"]

  • Or more fail-safe regexp:
    assert ("dog1-and-dog2" =~ /dog\d/).iterator().toSet() == ["dog1", "dog2"].toSet()
    
  • With a match group:
    assert ("dog11-and-dog22" =~ /dog(\d+)/).iterator().collect({it[1]}).toSet() == ["11", "22"].toSet()
    

Read the rest of this entry »

Posted in Java, Testing | Tagged: , , , | 9 Comments »

Note to Self: Running GroovyConsole with a Maven Project’s Classpath

Posted by Jakub Holý on October 2, 2011

It’s pretty useful to have the ability to eperiment interactively with some API using the (desktop) Groovy Console. If the API is in a Maven project, just add dependency on Groovy to your pom.xml:

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>1.8.2</version>
</dependency>

And execute the console from the project’s folder using the exec plugin:

mvn exec:java -Dexec.mainClass="groovy.ui.Console"

Enjoy.

Posted in Tools | Tagged: , , | Leave a Comment »

Inspect Your Webapp in a Live Environment Interactively with GroovyConsole

Posted by Jakub Holý on September 27, 2011

Have you ever needed to check the state of your webapp’s objects/Session/.. to find out why the hell something doesn’t work or have you had to learn a weird 3rd party API that is only available on the server? Then you were doomed … until the publication of GroovyConsole. JeeUtils GroovyConsole provides a JSP page that let you execute any Groovy/Java code on the server side, with access to server-side objects like request/session etc.

Here is a screenshot of my recent troubleshooting session, where I needed to check the state of a session-scoped JSF Managed Bean:

Read the rest of this entry »

Posted in j2ee, Java, Tools | Tagged: , , , | Leave a Comment »

Migrating from JRoller to WordPress

Posted by Jakub Holý on May 22, 2010

This post describes how to migrate a blog from JRoller.com to WordPress.com. The steps are:

  1. Backup JRoller via the util by La tortue cynique
  2. Export from WP
  3. Convert JRoller to a fragment of the WP format
  4. Add proper header and footer to the generated WP import file
  5. [optional] download images, perhaps upload them somewhere and modify URLs accordingly
  6. Import it into WP
  7. Check formatting, add tags…

Read the rest of this entry »

Posted in General | Tagged: , , , , , , | 3 Comments »

Most interesting links of April

Posted by Jakub Holý on May 4, 2010

The most interesting technical links I’ve encountered in April:

  • Getting Started with Tdd in Java using Eclipse [Screencast] – you will see not only TDD in practices but also a number of best practices applied and some inspirational novelty (at least for me) ideas  such as creating one test class per test configuration (and thus multiple test classes for a single “business” class); I really recommend this even if you are not interested in TDD
  • NoSQL links (as everybody these days, I’m also at least observing the NoSQL movement):
  • Testing
    • Easy data-driven testing with Spock – the Spock framework based on the popular JVM scripting language Groovy (99% Java + 1000% added) introduces a custom domain-specific language (DSL), which makes testing of a method using different data incredily easy and readable, with all the power of Groovy at hand; see the post and you will see immediately what I mean

That’s all for this month, stay tuned.

Bookmark and Share

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Posted in General, Java, Top links of month | Tagged: , , , , | Leave a Comment »