Chariot Training Classes

Training Courses

I run Chariot's training and mentoring services. We provide training in AngularJS, HTML5, Spring, Hibernate, Maven, Scala, and more.

Chariot Education Services

Technology

Chariot Emerging Tech

Learn about upcoming technologies and trends from my colleagues at Chariot Solutions.

Resources

Chariot Conferences

Podcasts

Entries in groovy (12)

Sunday
Oct212012

STS 3.1.0.RELEASE - not loving Spock / Groovy for ADJT projects

At SpringOne/2GX I tried the updated Springsource Tool Suite, 3.1.0, running a pre-4.0 Eclipse (as the STS 3.1.0 version is a bit tricky on Eclipse 4 until the 3.x - 4.0 migration bugs settle down).

Turns out there is a new error that shows up if you try to run anything Groovy within a AJDT project (which is the AspectJ Developer Tools plug-in Roo requires to compile all *.aj files when you're using them in the IDE).

You'll get:

Error compiling Groovy project: Either the Groovy-JDT patch is not installed or JavaBuilder is not being used.

I realize from talking to one of the developers at SpringOne that there have been some issues with the way Groovy handles AspectJ compiled classes, and that using Groovy within a Spring Roo project as general code it won't work properly, but this puts a damper on Spock at least from within the STS IDE. I can still run my tests from IntelliJ, however.

I'm going to post a request in the forums that we can turn off this error, so that we can use Spock for testing. So far, at least with Roo add-ons, I have used it to great effect and productivity, so at least for that use case I'd like to have an option to turn it off.

More soon.

Ken

Thursday
Jul012010

RESTing with Roo - adding Content Negotiation and REST in two easy steps (well, kinda)

Note: I don't know if I'm approaching this right... At least on Firefox, it seems to work. But on Safari, it fails. I'll revisit this soon.

Ok, here's another stream-of-consciousness post on REST support from a Roo application. I'm working on various research for our [PLUG] SpringSource Core Spring training classes, always attempting to get better examples so I can do more than just show the slides and labs, and I decided to use Roo to build myself a REST server.

Easy, I thought... Roo has RESTful URLs, and so I just have to set up the right configuration.

Kind of.

The basic steps to REST-enable a web app in Spring MVC using the built-in REST support are:

  1. Install the proper JARs for your Marshallers
  2. Install the ContentNegotiatingViewResolver

I had a bit of a hiccup figuring this out. Thanks to a great pair of threads on SpringSource's forums, here and here, I realized I had configured a few things wrong.

Setting up the example

Here's my Spring Roo log file, which you can cut and paste into a text file and then do a "roo script filename" command to set up for you.

project --topLevelPackage rest.demo --projectName spring-mvc-rest-demo
persistence setup --provider HIBERNATE --database HYPERSONIC_PERSISTENT 
entity --class ~.db.Customer
field string firstname
field string lastname
field date --fieldName dob --type java.util.Date
field number --fieldName discount --type java.math.BigDecimal --decimalMin 0 --decimalMax 1.0
controller scaffold --entity rest.demo.db.Customer --class rest.demo.web.CustomerController

Once you do that, now you're ready for some fun...

The additional dependencies for your Maven pom.xml file (you'll need to add these to the main dependencies tag section at the end...) (for XML conversion, we're using Castor, which auto-generates XML based on the reflection of JavaBean properties on your bean, and for JSON we're using the Jaskson JSON library. For this to work, you have to install spring-oxm, which isn't installed in Roo by default - I SMELL PLUGIN... RACE YA!).

<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.5.3</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.codehaus.castor</groupId>
  <artifactId>castor-xml</artifactId>
  <version>1.3.1</version>
</dependency>

Now, the Spring webmvc-config.xml file changes. This file is located in src/main/webapp, under the WEB-INF/spring directory, of course. Add this to the end of the file before the closing beans tag...

<bean id="htmlMediaType" class="org.springframework.http.MediaType">
  <constructor-arg value="text" />
  <constructor-arg value="html" />
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="order" value="0" />
  <property name="defaultContentType">
    <ref bean="htmlMediaType" />
  </property>
  <property name="mediaTypes">
    <map>
      <entry key="json" value="application/json" />
      <entry key="xml" value="application/xml" />
    </map>
  </property>
  <property name="defaultViews">
    <list>
      <bean
     class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
      <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
        <property name="marshaller">
          <bean class="org.springframework.oxm.castor.CastorMarshaller" />
        </property>
      </bean>
    </list>
  </property>

  <property name="viewResolvers">
    <ref bean="tilesViewResolver" />
  </property>
</bean>

Next, in the same file, add the order property, setting it to 1, to the instance of the AjaxUrlBasedViewResolver so that it looks roughly like this :

<bean class="org.springframework.js.ajax.AjaxUrlBasedViewResolver"
  id="tilesViewResolver">
  <property name="order" value="1" />
  <property name="viewClass"
    value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>

What you're seeing at work here in this setup is the configuration of a default media type of text/html, and a configuration of a first-level view resolver that does content negotiation first. You'll see the order setting was made to make the AjaxBasedViewResolver go first, which threw me, but that's an area for more research as I start to dig deeper into the interplay between the various view resolvers... Generally you want the JSP file-based resource view resolver to go last, as it is greedy, but Tiles changes that for us a bit. I am not 100% sure everything works as advertised - for example I need to do some AJAX testing to make sure those calls work. But for getting REST against a webapp, well, there you have it.

Testing it!

Well, that wasn't so much configuration, was it? I'm experimenting with REST using the Groovy RESTClient library at the moment (I'm going to use Spring REST Template in JUnit4 for the class, but also wanted something I could script up at a moment's notice and show them how REST works without waiting for those compile cycles...) BTW, I'm on Groovy 1.7.2 (haven't yet upgraded to 1.7.3) and the @Grab line uses Groovy's GRAPE artifact manager to install a grape from the ole' vine (puts it in ~/.groovy/grape/grapes or something)... WICKED COOL. Yes, I used my blog to say WICKED COOL. You can't stop me!

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0' )
import groovyx.net.http.RESTClient

def customers = new RESTClient( 'http://localhost:8008/demo/')
def results = customers.get (path : 'customers',
   headers: [Accept : 'application/json', "Accept-Encoding" : 'gzip,deflate'])

println results.data

Switch from JSON to XML, using application/xml as the Accept header, and you'll see it automatically respond with the appropriate datatype. Great! Now, if you use XML, change from that println statement to this:

results.data.customer.each { c ->
  println "customer:  $c.id, $c.firstname $c.lastname"
}

And if you want to test it on the browser, and see it do content negotation by file extension instead, just hit: http://localhost:8080/spring-mvc-rest-demo/customers.xml or http://localhost:8080/spring-mvc-rest-demo/customers.json to see the REST data, and http://localhost:8080/spring-mvc-rest-demo/customers to see the regular tiles views.

Enjoy...

Oh, and while I'm shilling for my training group at Chariot, please visit our course calendar if you are interested in our fall lineup - Hibernate with Spring, Spring Enterprise Integration, Core Spring, or Maven Intro and Advanced training. Thanks, and I'll refrain from using a strange chamois in any of my in-line advertisements...

Thursday
Sep032009

Using the gsql plugin for Griffon

Recently Andres Almiray has added a gsql plugin to Griffon.  This is very cool, as it lets you configure datasources ala' grails, and then inject the Groovy SQL API into your controllers.

Here is how it works:

First, install the plugin by using the instruction

griffon install-plugin gsql 1.0-SNAPSHOT

Next, configure your database connection using the ./griffon-app/conf/DataSource.groovy file, the same way you would a grails app.

Once configured, you may use the withSql closure to inject the Groovy SQL object, pre-initialized via your data source, into your code.  Here is a simple example:

def rows = [];

withSql { sql ->
   sql.eachRow("select name from city") { row ->
      rows << row.name
   }
}

There, that wasn't so hard, now was it?

Programming note:  I am recording a Chariot TechCast with Andres tonight and will have it posted sometime next week.  Thanks, Andres!

Ken

 

Wednesday
Dec032008

Grails acquired by SpringSource... A Good Thing

I've been thinking about the recent acquisition of G2One by SpringSource, and I've come to the conclusion that it was a very bold and smart move by both parties. Why? Simply because it provides benefits to both parties and gives those who need rapid web development another alternative to Rails, only that runs natively in the JVM and can access all of their existing Java EE infrastructure.

I should note that my employer, Chariot Solutions, is a consulting partner with SpringSource as well as with several other firms such as RedHat/JBoss.

SpringSource gains a lot by adding this web framework. First of all, it now has an agile web platform, based on Spring and other open source technologies, that it can support for larger corporate customers. This may bring agile web development into more enterprises, as most have shied away from Groovy/Grails simply because it was too new, ran on a maverick language (Groovy) and had a small support team.

Second, SpringSource extends its team of experts to include the talented Grame Rocher, a great addition to their team who brings an offbeat and innovative perspective to application development. I understand they may use some of his time to help them with Spring Core, and as he says in his interview on Grails Podcast Episode 72, this acquisition will actually give him more time to work on Grails than he had when G2One was independent.

From G2One's side, they gain a huge support staff, with the ability to fix bugs in the platform, add staff to commit to Grails 1.1 and beyond, and for new projects, such as revamping Grails' Eclipse plugin support. Not to mention the fact that Groovy/Grails makes the enterprise more productive, I think we will start to see a lot of new prototyping efforts as people start kicking the tires and discovering the big productivity gains that will await them once they give it a try.

If you haven't given Grails a try, and you're a Java developer, you should. It's a compelling platform for application development, and has a growing community.

Some upcoming features of Grails 1.1 mentioned in that podcast above:


  • Maven Support (Really, Graeme? Wow, I know that must hurt a bit! ;)

  • Customized templates are now honored when installed with grails install-templates

  • JSP taglib support in GSPs

  • Plugins now are stored outside of a Grails project, and the project metadata references the plugin. This means no more checking in plugin code to source code repositories. What's more, when a project is checked out, the plugins are automatically installed, ala transitive dependency management.

  • GORM now allows basic type collections like Strings

  • Data binding now can use a subset of the data from an HTTP request using the subscript operator

  • Read-only access to domain objects using DomainObj.read(id)

  • Default sorting order in Domain classes, associations

  • The new Testing Plugin is now the standard way to test in Grails.


And a whole lot more. Read up on the Grails 1.1 feature list in the Beta release notes page on Grails.org.

 

Nice job on the interview, GrailsPodcast guys!

Technorati Tags: , , ,

Friday
May022008

Setting up the IntelliJ Plugin for Groovy and Grails

The IntelliJ plugin is a great tool. However, one important thing to note is that it wants the source distribution of grails in the grails directory. Why? Because the GSP support requires the source code for the GSP tags.

Plugin Setup Process


In order to properly set up the Grails plugin, do the following:

  1. Download the grails source code zip file (which also contains the binary)

  2. Unzip the source code distribution

  3. Download the Groovy source and binary code distributions. Since the source release does not include a built binary, I had to download both the source and binary distributions and merge them together (building on my OS X machine failed). YMMV.

  4. Open IntelliJ Idea, go to the Preferences / Plugins page, and download JetGroovy and install it

  5. Restart Idea

  6. Open the Preferences / Plugins page again, and select Groovy

  7. Set the folder locations for Groovy and Grails to your new directories

There, that's it. Now, you can create Groovy and Grails projects, debug Groovy code, and use the Apple/Ctrl click trick to jump into Groovy or Grails source code.

GSP Tags


GSP tags are closures, so the plugin can't figure out attributes. That's ok, if you want to see more information, just CTRL or Apple click on the GSP tag name, and it will jump to the source code of the tag closure in the editor.