The UrBlog

John's Ramblings about Software Development

Add a Context-param to Grails

With the recent Spring vulnerability, we thought it would be a good idea to disable EL in our Grails application. To do this, we need to add a context-param to the beginning of the generated web.xml file. Rather than using install-templates, I used the eventWebXmlEnd event to insert it. XMLSlurper would have been nice, but it does not have a simple way to insert a node at the beginning. So instead I used the XmlParser and came up with the following.

Welcome to the UrBlog Reborn

Welcome to my new blog hosted on Github! I’ve moved a number of the posts from my old blog. If you want to see all my old posts, the old blog is here.

Grails Script to Generate JAXB Classes

I think Groovy’s MarkupBuilder is great and I use it often. Sometimes though, I need to generate a complex XML document that conforms to an XSD. MarkupBuilder often leads to markup and business logic being mixed together much like HTML and Java code gets mixed in complex JSP pages. In cases like this, I like to use JAXB instead. I can generate classes from the XSD, load up an object model and let JAXB generate the markup.

It’s fairly easy to create a script to handle generating the JAXB classes for you. JAXB comes with a handy Ant task that takes your XSD and generates classes. The trick is passing the build classpath to the task. There is a “grailsSettings” variable available in scripts that contains BuildSettings. We can get the list of build dependencies files from this class to generate the classpath. Here is a simple example that takes the Microsoft books.xsd in the etc/schema directory and generates the code to the src/java directory:

UPDATE: Sometimes having the JAXB jars on your path can cause problems with your application. In those cases, you call the generation class directly:

Converting XML to Flat Files With Groovy

When integrating systems, you often need to convert data from one format to another. For example, you may receive data from a web service in XML and need to convert it to a flat file for a legacy system. It’s usually not as simple as just moving data from a tag to a column either. There’s often calculations and formatting required. Most often the code has the work of parsing, converting and formatting all mixed together. With a dynamic language like Groovy which has closures, we can abstract much of that work. For our example, we’ll take a subset of the Microsoft sample books.xml file:

We would like to provided a mapping for each column that allows us to pull data out of the XML file and define the width of the column. We’ll keep it simple to start with by assuming a fixed width flat file with all columns left justified. Following is a simple mapping using an array of maps:

Each closure should get a GPathResult to a “row” in the XML file. The closure should return the text that should go in the column. We’ll need to supply the tag that identifies the tag in the XML file to pass to the closure. Following is an example test using our books data:

The implementation is fairly simple. We process each “tag” in the XML. For each mapping, we set the delegate for the closure to a map with the tag name and the GPathResults for that tag. The closure can then be executed to get the text for the column:

The above piece of code abstracts the processing into 8 lines of code. It is a testament to the power of a dynamic language that provides closures.

An Easier Way to Exclude Methods From Grails JMX Plugin Services

The Grails JMX plugin is a great way to quickly make a service available through JMX. Things get trickier when you want to only expose a few methods on the service. The plugin provides the option to list methods to exclude, but you need to list all of them including the ones Grails added to the service. Fortunately, we can use the metaclass to help us out. We can add a list of the few methods we want exposed and then use to that to generate the list of exclude method as follows:

Grails Clean-test-app Script

I’ve been developing Grails apps in Spring Tool Suite. STS will compile your Groovy code as you save it just as Eclipse does for Java code. This is great during coding, but can cause issues when it’s time to check in. If you deleted a class and then run test-app, that class may not be cleared from your target/classes and tests may pass that shouldn’t. Before checking in, I now need to run clean, then refresh-dependencies, then test-app. To save some time, I created the following script that will do it all at once. Now I can just run clean-test-app.


Using Spring as a Factory Method

One common strategy in object-oriented program is to use the dependency inversion principle to decouple high level code from the low level details. To demonstrate this, let’s use the movie example from Martin Fowler’s Refactoring book.



After some initial refactoring, we have a Movie class that can calculate it’s charge based on days rented:

// From book: 'Refactoring' by Martin Fowler
public class Movie {

   public static final int CHILDRENS = 2;
   public static final int NEW_RELEASE = 1;
   public static final int REGULAR = 0;

   double charge(int daysRented) {
      double result = 0;
      switch (getPriceCode()) {
    case Movie.REGULAR:
       result += 2;
       if (daysRented > 2)
          result += (daysRented - 2) * 1.5;
       break;
    case Movie.NEW_RELEASE:
       result += daysRented * 3;
       break;
    case Movie.CHILDRENS:
       result += 1.5;
       if (daysRented > 3)
          result += (daysRented - 3) * 1.5;
       break;
    }
    return result;
   }

}

Next we replace the switch statement with polymorphism using the state pattern:

// From book: 'Refactoring' by Martin Fowler
public class Movie {

   public static final int CHILDRENS = 2;
   public static final int NEW_RELEASE = 1;
   public static final int REGULAR = 0;

   public static Price newPrice(int priceCode) {
      switch (priceCode) {
         case REGULAR:
        return new RegularPrice();
     case NEW_RELEASE:
        return new NewReleasePrice();
     case CHILDRENS:
        return new ChildrensPrice();
     default:
        throw new IllegalArgumentException();
    }
   }

   double charge(int daysRented) {
      return newPrice(getPriceCode()).charge(daysRented);
   }

}

public interface Price {
   double charge(int daysRented);
}

public class RegularPrice implements Price {
   public double charge(int daysRented) {
      double result = 2;
      if (daysRented > 2)
         result += (daysRented - 2) * 1.5;
      return result;
   }
}

public class NewReleasePrice implements Price {
   public double charge(int daysRented) {
      return daysRented * 3;
   }
}

public class ChildrensPrice implements Price {
   public double charge(int daysRented) {
      double result = 1.5;
      if (daysRented > 3)
         result += (daysRented - 3) * 1.5;
      return result;
   }
}

This requires us to create some sort of factory method to decide which Price to create based on the Movie type (such as newPrice in the example). Usually this occurs in a static method with a switch statement on type. In a large program where Price is used multiple times, this is an advantage because we only have to change the one switch statement. But what if we could get rid of that switch statement also?

If you are using Spring, you can take advantage of the replace-method tag. You can pass it a class implementing MethodReplacer to replace a method in the class. That method could be an abstract factory method. Let’s modify our Movie class so that newPrice is an abstract method:

// From book: 'Refactoring' by Martin Fowler
public abstract class Movie {

   public static final int CHILDRENS = 2;
   public static final int NEW_RELEASE = 1;
   public static final int REGULAR = 0;

   public abstract Price newPrice(int priceCode);

   double charge(int daysRented) {
      return newPrice(getPriceCode()).charge(daysRented);
   }

}

Now we create a handy method replacer utility class that joins a prefix with the first argument to create a bean name and looks up the bean in the context:

public class BeanFactoryMethodReplacer implements MethodReplacer, ApplicationContextAware {

   private ApplicationContext context;

   private String prefix;

   public void setApplicationContext(ApplicationContext context) throws BeansException {
      this.context = context;
   }

   public void setPrefix(String prefix) {
      this.prefix = prefix;
   }

   public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
      String bean = (prefix != null) ? prefix : "";
      bean += args[0];
      return context.getBean(bean);
   }

}

Finally, we register the method replacer, the movie with the newPrice method replaced and beans for each Price. We use “price” as a prefix. The name of each price bean should be “price” + the number code for it’s type:

<bean id="movie" class="Movie">
   <replaced-method name="newPrice" replacer="factoryMethodReplacer">
      <arg-type>int</arg-type>
   </replaced-method>
</bean>

<bean id="factoryMethodReplacer" class="BeanFactoryMethodReplacer">
   <property name="prefix" value="price"/>
</bean>

<bean id="price0" class="RegularPrice"/>

<bean id="price1" class="NewReleasePrice"/>

<bean id="price2" class="ChildrensPrice"/>

Spring has now become our factory method. As new price codes are added, we can just register the Price class as a bean without having to manually change a factory method.

Custom Scheduling in Spring

Spring 3.0 has simplified task scheduling. As part if this, they have deprecated the MethodInvokingTimerTaskFactoryBean and ScheduledTimerTask. Instead you create a scheduler that implements the TaskScheduler interface and uses a Trigger to specify when a task is scheduled to run. The XML and annotations allow you to specify fixedDelay, fixedRate or cron string. These are fixed at run time. This works great for triggers that are fixed at run time, but does not allow you any way to modify these at run time. The TaskScheduler interface provides methods to schedule a task with a trigger, so this gives us an opportunity to pass in a custom trigger that can have it’s trigger interval changed at run time. There are a number of ways to configure this. Here is a simple way I came up with that uses a single bean to schedule the task and change the fixedDelay at run time. This extends the example provided on the Spring blog noted earlier.



First we need a class that takes the scheduler, task and starting delay. For simplicity, it will also implement the Timer interface.

public class DynamicSchedule implements Trigger {

   private TaskScheduler scheduler;
   private Runnable task;
   private ScheduledFuture<?> future;
   private int delay;

   public DynamicSchedule(TaskScheduler scheduler, Runnable task, int delay) {
      this.scheduler = scheduler;
      this.task = task;
      reset(delay);
   }

   public void reset(int delay) {
      if (future != null) {
         System.out.println("Cancelling task...");
         future.cancel(true);
      }
      this.delay = delay;
      System.out.println("Starting task...");
      future = scheduler.schedule(task, this);
   }

   @Override
   public Date nextExecutionTime(TriggerContext triggerContext) {
      Date lastTime = triggerContext.lastActualExecutionTime();
      Date nextExecutionTime = (lastTime == null)
         ? new Date()
         : new Date(lastTime.getTime() + delay);
         System.out.println("DynamicSchedule -- delay: " + delay +
              ", lastActualExecutionTime: " + lastTime +
              "; nextExecutionTime: " + nextExecutionTime);
      return nextExecutionTime;
   }

}

Note the reset method which stops the scheduled task, changes the delay and then restarts the task. If you are changing the delay to a shorter delay, you want to restart with the new delay so it happens immediately. Alternately, you can skip canceling the task and the new delay is picked up on the next execution.

The rest of the code is the same, except for the SchedulerProcessor which has the @Scheduled annotation removed from the process method:

@Component
public class ScheduledProcessor {

   private final AtomicInteger counter = new AtomicInteger();

   @Autowired
   private Worker worker;

   public void process() {
      System.out.println("processing next 10 at " + new Date());
      for (int i = 0; i < 10; i++) {
         worker.work(counter.incrementAndGet());
      }
   }

}

In the XML configuration, we add a name to the scheduler and create the DynamicSchedule. We pass it the scheduler, the process method (wrapped in a MethodInvokingRunnable) and the default delay:

   <context:component-scan base-package="com/test" />

   <task:annotation-driven />

   <task:scheduler id="scheduler" />

   <bean id="dynamicSchedule" class="com.test.DynamicSchedule">
      <constructor-arg ref="scheduler" />
      <constructor-arg>
         <bean class="org.springframework.scheduling.support.MethodInvokingRunnable">
            <property name="targetObject" ref="scheduledProcessor" />
            <property name="targetMethod" value="process" />
         </bean>
      </constructor-arg>
      <constructor-arg value="3000" />
   </bean>

Now we can add a separate process that changes the delay to a random delay to test it out:

@Component
public class ScheduleChanger {

   @Autowired
   private DynamicSchedule dynamicSchedule;

   @Scheduled(fixedDelay=30000)
   public void change() {
      Random rnd = new Random();
      int nextTimeout = rnd.nextInt(30000);
      System.out.println("Changing poll time to: " + nextTimeout);
      dynamicSchedule.reset(nextTimeout);
   }

}

When you run this and view the output, you will see where the dynamic schedule trigger is fired and where the schedule gets changed.

An Introduction to Node.js

Node.js is an evented I/O server built on Google’s V8 JavaScript engine. Node provides a simple way to build highly scalable server applications. This article will provide an introduction to Node along with installation details and a first server. more…

Scaling With Single Threading

The free lunch is over. To speed up applications we are told we must write multithreaded programs and avoid mutable state. Functional programming can help with it’s immutable state. There’s also Erlang with the Actor model or Clojure with it’s software transactional memory. One other option to consider is single threading your code. Following are a few examples where single threading was used to scale applications.

more…