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 tips (4)

Tuesday
Oct182011

Roo (in the) Corner - new features in trunk...

I've been spending my time readying Roo in Action for publication. Turns out, the Roo team had other ideas - including lots of new things you may want to be aware of if you are looking to support Roo 1.2 once it is released.

Keep in mind these changes are in-flight. If you don't need to work on trunk, DO NOT WORK ON TRUNK. This is something other platform afficianados do - for example, the Rails development community commonly calls this working on the "edge". So, let's get edgy.

There are some really, really cool things in here. I've seen them move toward opening up for all modes of development - some want JSF, so there is a JSF add-on. They use PrimeFaces, and a dialog motif for adding new elements. I'm sure they will tweak this as it goes along, but it looks more like the GWT or Flex mode of editing I saw before.

Breaking Changes (so far) - you may need to edit your code - I know I have to for now, but this is a temporary pain for some consistency gain within Roo.


  • @RooEntity -> @RooJpaActiveRecord

  • @RooWebScaffold - now a .scaffold. package after .controller.

  • @RooConversionService - now a .converter. package after .controller.


Additions


  • New @RooEquals - and a shell command for equals - this has been here for a little while, but is something that can be of use when defining models or other objects that need to be compared. You can exclude fields from the factoring of the comparison.

  • new entity flags (recent anyway) to set entity name, table, and other attributes on entities - this is great, and includes the ability to define transaction manager names for cases where you are working with multiple JDBC datasources - nice! Also, it lets you specify the entity manager - so if you have two persistence units to separate transaction managers (reporting database -vs- transactions) you have that option. Again, not a huge deal, but lets you stay within Roo to get things done, without digging into code for a configuration option. You can even set the table name, entity name, etc...

  • New settings for the json command - --deepSerialize and --rootName - I am not sure if these have been here long, but they are good to know about.

  • New —packaging element in project - includes POM or JAR right now. Also includes --parent. This could be great, as I think they are going to implement multi-pom support in Roo 1.2. We'll stay tuned on that, and perhaps write a quick blog entry on what we've found.

  • New support for database dot com - a new database provider - I don't know much about it.

  • New date field support for both dateTimeFormatPattern AND dateFormat - I am unsure that the scaffold would deal with dateTimeFormatPattern.

  • JSF scaffolding in place - uses PrimeFaces for the widgets - this is interesting, and has a different look and feel, native to PrimeFaces. But, it does exactly the same work as the scaffold in MVC. So, if you're looking at complexities and benefits of each, go for it. The CI build server is here, and you just need to follow these rules to get it to use trunk.


It was so easy to switch between JSF and MVC for my testing, I used these two scripts:

Roo with MVC

 

project --topLevelPackage foo.bar.mvc --packaging JAR --projectName mvcrules
jpa setup --database HYPERSONIC_PERSISTENT --provider OPENJPA
entity jpa --class ~.model.Course --testAutomatically
field string --fieldName name
field date --fieldName runDate --type java.util.Date --dateFormat SHORT
web mvc setup
web mvc all --package ~.mvc quit
Roo with JSF
project --topLevelPackage foo.bar.jsf.sortarules --packaging JAR --projectName jsfsortarules
jpa setup --database HYPERSONIC_PERSISTENT --provider OPENJPA
entity jpa --class ~.model.Course --testAutomatically
field string --fieldName namefield date --fieldName runDate --type java.util.Date --dateFormat SHORT
web jsf setup
web jsf all --package ~.jsf quit

I will attempt to update this article as I find new things... No promises, as the primary artifact is the book. But hopefully this is a warning shot across the bow that change is indeed a-coming.

Tuesday
Aug232011

Debugging add-ons via the Roo shell

Trying to debug your Roo add-ons (which are OSGi bundles)?  Here's a simple way.  Just add the old remote debugger flags to the front of the <code>java</code> invocation of the Roo shell in your roo.sh script (comment out the working version). These are the last two lines of the script. Back up your script file before you do this.  I use:

# Hop, hop, hop...
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005 ...
#java -Dis.apple.terminal=$APPLE_TERMINAL $ROO_OPTS -Droo.args="$*" ...

Then, connect to the debugger with your favorite IDE as a remote debugger. I use IntelliJ with port 5005 localhost. I have set this up so that it pauses while starting up, so that I can attach the debugger. You can set suspend=n if you don't want it.

Nice thing is that you can use the osgi start command to load your add-on, set your breakpoint, then stop right in the command that you're executing. Use it to play around with Roo source to find out how their add-ons work.

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...

Saturday
Mar222008

A few tips for Grails Database Setups...

Here are a few quick tips for setting up the Grails datasources in grails-app/conf/DataSource.groovy:


  • To log all Hibernate queries, use
    loggingSql = true 
    either in the initial dataSource closure, or in a specific connection pool (Development, Test, Production)
  • If you didn't have time to create a database and are just prototyping domain relationships, don't worry about this file yet! Just open up BootStrap.groovy in the same directory, and wire up your domain classes like this:



    class BootStrap {
    def init = { servletContext ->
    def p1 = new Employee(firstName: "Ken",
    lastName:"Rimple",
    likesCoffee:true).save()
    }
    ...
    }

    This example above uses the embedded Hypersonic SQL in-memory database. Each time you spin up the application server, the default entry for the development instance creates the tables, and on the way out, drops them (create-drop). You could choose to switch to MySQL, for example, and use Create on one startup. Then, once you're done, switch to update. This will ensure that the data you've created stays in the database (and you can comment out the original BootStrapping code: don't delete it unless you want to type it in all over again once your database gets screwed up).

  • Keep in mind, anything you put at the initial dataSource closure gets inherited into the specific configurations. So, you might have the same database vendor in all three environments: use the same driver.
  • You can have different environments, and not just three. Change the environment names, and when you start up, pass the -Dgrails.env=production or -Denv=supersecretprobation flag to grails run-app and you'll use those configurations.