Archive for the ‘J2EE’ Category.

Grails Tip: Colored output

I really enjoy coding in Grails.  When working with dynamic languages, there is always a bit more uncertainty to what the type of particular variable is – especially when calling code that someone else has written.  Now, you can always just fire up the debugger to find out but often times it is overkill.  Groovy has great support for finding out all about your object using dump(), inspect(), and toString() usually returns something useful from a GDK class.  Usually a quick println is just the right thing for me to figure out what is going on, and then I remove the statement.

The problem with a quick println is that it is often difficult to quickly differentiate your log lines from that of Grails or Hibernate.  Of course you can turn those log levels off, but always like to see the SQL Hibernate is generating during development.  In order to make my logging stand out, I have started adding this to BootStrap.groovy:

   1: def init = { servletContext ->

   2:     ...

   3:     Object.metaClass.printlnRed = { s ->

   4:         def ansi = new Ansi(Ansi.Attribute.BRIGHT, Ansi.Color.RED, Ansi.Color.BLACK);

   5:         ansi.outln(s);

   6:     }

   7:     ...

   8: }

This will allow me to call “printlnRed ‘Some String’ from any Groovy object in my Grails application.  The Ansi class comes from the LGPL licensed jibs library.  Of course you will want to find out what colors work the best for you.  Don’t forget to remove your println’s – you don’t want to clutter up your code for others.  If it is something worth keeping in the application, use Log4J instead.  You can still get colors by configuring your appenders to use Ansi colors as well – there are numerous examples of how to do this including one in Ant.  FYI, I doubt this works in Windows.

Groovy and Camel for Monitoring ActiveMQ

I often have the need communicate with backend systems for simple tasks, but do not want to end up going to all of the trouble of creating an application.  For database, I used to just use Perl and DBI for simple tasks, but even setting up DBI can be some work depending on your database server.  What I really like is being able to quickly write a script in a single file and run it with no setup necessary — that is what makes Groovy and Camel with Grape such a great combination.

Let’s look at a simple script for monitoring ActiveMQ advisory messages:

   1: import org.apache.camel.*;

   2: import org.apache.camel.impl.*

   3: import org.apache.camel.language.groovy.*

   4: import org.apache.camel.component.activemq.*

   5: import org.apache.activemq.camel.component.*

   6: import org.apache.log4j.*

   7:  

   8: @Grab(group='org.apache.camel', module='camel-groovy', version='2.0-M2')

   9: @Grab(group='org.apache.camel', module='camel-jms', version='2.0-M2')

  10: @Grab(group='org.apache.camel', module='camel-core', version='2.0-M2')

  11: @Grab(group='org.apache.activemq', module='activemq-all', version='5.2.0')

  12: @Grab(group='org.apache.activemq', module='activemq-camel', version='5.2.0')

  13: class Routes extends GroovyRouteBuilder {

  14:   public void configure(){

  15:         def log = { exchange -> if (exchange) println exchange } as Processor;

  16:  

  17:         from("activemq:queue:ActiveMQ.Advisory.>").

  18:           process(log);

  19:     }

  20: }

  21:  

  22: def camelCtx = new DefaultCamelContext()

  23: camelCtx.addComponent("activemq", ActiveMQComponent.activeMQComponent("tcp://127.0.0.1:61616"))

  24: camelCtx.addRoutes(new Routes())

  25: camelCtx.start()

 

All you have to do is save this to a file and run “groovy Script.groovy” – no uploading JAR files or classpath setup required thanks to Grape.  You can see in the script how simple it is to define a Camel processor using Groovy coercion.  With a few modifications, I also use this script as a base for draining dead letter queues, moving message from one queue to another, etc.

Of course, just printing out advisory messages is not all that useful.  Say you want to get notified by email when there is a slow consumer.  Just add dependencies for the necessary mail JARs and and change your route:

   1: from("activemq:queue:ActiveMQ.Advisory.SlowConsumer.*").

   2:   mail("smtp://monitor-list@mycompany.mailserver")

With all of the different Camel components, there are a lot of things you can do with the information – send an IM, log to a database, or write to a file.

NHibernate Profiler now supports Hibernate

I have had the privilege of doing some work for Ayende for the past month to add support for Hibernate to his excellent NHibernate Profiler.  What does this mean exactly?  Well, Hibernate is now supported as a first class citizen in the profiler.  We have tried to make sure that there is a 1:1 feature mapping between the NHibernate and Hibernate support.  I am happy to report that all applicable warnings and information that you receive for NHibernate is also displayed for Hibernate.  There are of course differences between NHibernate and Hibernate — such as Hibernate does not support statement level batching options, multiquery, or future queries – which is reflected in the documentation.

Since many developers use Hiberante with Spring, we have tried to make Spring integration as seamless as possible.  If you are using  Hibernate with Spring, configuring your application to be profiled is as simple adding a JAR and a custom attribute to your Spring configuration.  Here you can see where I have added support for profiling to an Appfuse demo project:

   1: <!-- Hibernate SessionFactory -->

   2: <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

   3:     <property name="dataSource" ref="dataSource"/>

   4:     <property name="configLocation" value="classpath:hibernate.cfg.xml"/>

   5:     <property name="hibernateProperties">

   6:         <value>

   7:             hibernate.dialect=${hibernate.dialect}

   8:             hibernate.query.substitutions=true 'Y', false 'N'

   9:             hibernate.cache.use_second_level_cache=true

  10:             hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

  11:         </value>

  12:         <!-- Turn batching off for better error messages under PostgreSQL -->

  13:         <!-- hibernate.jdbc.batch_size=0 -->

  14:     </property>

  15:     <hprof:profiler />

  16: </bean>

 

This, of course, is just one of the many different ways that you can configure the profiler.  Here is a screenshot of me profiling an Appfuse application.  The top few sessions are profiling unit tests and the remaining sessions (with the URLs) are profiling the web application:

nhprof-appfuse 

Currently, the product is in closed beta and we are looking for beta testers.  If you are interested, then please contact either Ayende through his blog and he will get you all setup.  Other places you can provide feedback are the user group and the feedback site.  Although I may be a little biased, I think this application can add a lot of value for anyone who is using NHibernate and Hibernate.

Writing ExtJS apps in Java or C#

I don’t mind programming in JavaScript, but there are definately some annoyances. I definately miss code completion, refactoring support, etc. You pretty much have to have a window open for the docs to make sure I you are using the API correctly. It can also be pretty frustrating when you fat finger a config object and your widget does not behave like you want it to. Visual Studio 2008 seemed promising with its Intellisense feature for JavaScript, but it does not appear to play nicely with libraries besides Microsoft AJAX (http://extjs.com/forum/showthread.php?p=61484). If you want comments with your code completation, it also has to follow the Microsoft style of XML documentation (ExtJS uses JSDoc format).


I was thinking about this when I read Joel’s latest post yesterday:

What’s going to happen? The winners are going to do what worked at Bell Labs in 1978: build a programming language, like C, that’s portable and efficient. It should compile down to “native” code (native code being JavaScript and DOMs) with different backends for different target platforms, where the compiler writers obsess about performance so you don’t have to. It’ll have all the same performance as native JavaScript with full access to the DOM in a consistent fashion, and it’ll compile down to IE native and Firefox native portably and automatically. And, yes, it’ll go into your CSS and muck around with it in some frightening but provably-correct way so you never have to think about CSS incompatibilities ever again. Ever. Oh joyous day that will be.

And then when I read Nikhil’s post today where he goes on to say that we already have a something like that — Script# and GWT. These tools are great, but the problem becomes converting existing libraries to Java or C# so that they can be used.


There are two promising ExtJS wrappers, one for Script# and one for GWT, extsharp and GWT-EXT. From what I can tell, it looks like GWT-Ext was ported from the ExtJS libraries. extsharp uses a different conversion strategy — it creates C# classes from the parsed JavaScript source and includes the original comments. Take a look at the pictures on the main page of extsharp, and you will see the benefit of being able to write Ext apps using code completion.


I am not sure I would use these libraries in a production application — yet. The one thing that they have going for them is that once they have generated Javascript for you, you could always stop using them. Then be in no different of a spot from hand coding Javascript yourself. I’m going to keep on eye on these tools and see how they progress.

No annotations for servlets?

I was looking at the following article on java.net about the proposed annotations that J2EE 5 will support. I wonder why they are not adding annotations for servlets. If you are writing a simple application, sometimes there is no need to implement an MVC approach. Take servlets that just return JSON or XML to a XMLHttpRequest. Now if your project is already using MVC, then by all means integrate it. Something like what I listed below seems to make a lot of sense to me:



@Servlet(name="My Servlet", urlMapping="/myservlet.jspx")
public class MyServlet extends HttpServlet {
...


There is really no reason why I should have to write something to web.xml everytime I want to add a servlet (especially the verbose way you have to define servlets now). Imagine being able to just add the Spring MVC or Struts JARs to your classpath and having them work without configuring anything in web.xml.


Dynamic dropdowns with extjs using servlets and json-lib

If you have not discovered extjs yet, then you are missing out. I’ve been working with extjs for a couple of months now, and I am very happy with the results — and so are the customers. There are a number of advantages to using Javascript UI components for your web application including:

  • you do not have to recompile after every change (just hit reload)
  • it does not matter what backend framework you are using — you just need to be able to post and retrive JSON or XML data
  • it does not matter what view you are using (Freemarker, Velocity, JSP’s, etc)
  • json-lib makes working with json-lib easy
  • you can do a lot more functionality with a lot less code


The demo shows how to easily do dyanmic drop down boxes with extjs and using servlets to provide the JSON. I used json-lib to create the JSON.


Here are a couple of images of the demo. Just unzip the archive, run “mvn jetty:run”, and go to http://localhost:8080/. You have to have Maven 2 already installed and setup. I have a number of other examples on using extjs with Java including a nice tree reordering demo where I save the nodes to a Hibernate backend that I will try to find some time to post.






Eclipse and OutOfMemory

I have run into the same problem that seems to be plaguing a number of other Eclipse users lately (http://www.jroller.com/page/phidias?entry=eclipse_running_out_of_memory, http://www-03.ibm.com/developerworks/blogs/page/JEE?entry=eclipse_out_of_memory). This problem was happening rarely for me running Eclipse 3.3M4, but it started happening to me at least 5 times an hour (if not more frequent) when I upgraded to Eclipse 3.3M6. This is nothing new for me. I have been using Eclipse since version 2.0 and have run into OOM errors before — although usually it was because I did something dumb like download a new version and forget to alter the heap size. (Just for fun, try running the old Motif version of Eclipse 2.0. Eclipse has really come a long way.).


I started searching around for fixes for the problem, but I wanted to understand what was going on since I log a lot of hours with Eclipse. I am running Eclipse 3.3M6 (I20070323-1616) on a 2.8GHZ P4 with 4GB of RAM under Windows Vista using JDK 1.5.09. The plugins I have installed are Mylar, Hibernate Tools, Subversive, WTP, and Spring IDE.


My first settings to change were the minimum heap size to 128MB (-Xms128m) and the maximum heap size to (-Xmx512m). I have seen some recommendations to set the minmum size to 512m. I would toggle Window -> Preferences -> General -> Show heap status to on first. Watch your heap usage and see what you normally trend at before setting it to a higher number. If you are only working with small to medium size projects, then you should be fine at that number. As a benchmark, I was able to take my heap up to 150M by running a Project -> Clean on both Spring and Hibernate’s source code at the same time, running it in the background, and opening other projects. I also checked out some large projects with Subversive and ran some standard tasks editting in Mylar. I am sure there are more heap intensive plugins that you are probably running, so best bet is to turn on the status and tweak later.


After verifying that did not fix the problem, I altered the PermSize and MaxPermSize parameters (-XX:PermSize=128m -XX:MaxPermSize=128m) to be 128M. This solved me problem I have now been running Eclipse happy for 7 hours without a crash. If you make these changes and are still having problems, use the -XX:+HeapDumpOnOutOfMemoryError setting to generate a heap dump (for more information on debugging heap dumps, go here and here.


Below is a screenshot I snapped using JConsole to show that my PermGen space does indeed trend over the default setting of 64m. The J2SE 5 version of JConsole did not seem to play nice with Vista, so this is attached to my 1.5.09 JVM using the JDK 6 version of JConsole.





Some other recommendations for fixing the problem include using IBM or JRockit to run Eclipse. Apparently, those JVMs have no concept of PermGen space and the PermGen data is stored directly on the heap. It is then subject to garbage collection like the objects stored in the heap. If I was starting an application from scratch, I would probably use JRockit but most of us are stuck with Sun’s JVM.


Off of the top of my head, I can probably name no more than ten options you can pass the JVM on the command line to configure garbage collection, JMX, system properties, etc. I have been working on J2EE applications for years and a company where we migrated applications from Java 1.2, 1.3.1, 1.4.2, and 1.5. I dealt with a lot of OOM errors in our web applications and did a decent amount of JVM tuning. Having said that, how many Eclipse users know that there are options that can be passed to the JVM for tuning? I would guess that there are a large number of users who have never dealt with tuning JVM parameters at all. Those same users probably also do not realize that there are other JVM options besides Sun’s JVM to choose from.


I was thinking about this as I was looking through this bug in Eclipse Bugzilla. Some of the comments on the bug suggest that this is an Eclipse problem, some of them suggest that it is a Sun problem. However, this is going to be a big annoyance for Eclipse users going forward unless someone fixes it. I do not see anything happening on the Sun side (nor am I sure that they can do anything without significantly changing their JVM), but it would be nice to see Eclipse either 1) present the user with a warning on the splash screen with a link to configuring their JVM properly for Eclipse 2) have a warning that goes off when the PermGen size get’s beloww 5%-10% with a help link on how to fix the problem.

Spring MVC form tag library and template support

A really useful UI feature of Webwork (now Struts 2) was templates. ASP.NET also provides similar functionality through CSS Control Adapters.Templates allow you to customize the HTML output by the form tag libraries. This feature was really useful for my development team because it allowed everyone to generate accessible (508 compliant) HTML for forms without having to know anything about accessibility. Just implement the templates once and make sure the whole team uses the accessible theme.


Spring MVC has the idea of themes, but does not allow for customizing the HTML output by the form tags. I created an issue in Spring JIRA describing what should be included in the feature. Templates would be a nice addition, but I would settle for a hook to provide custom HTML. A template mechanism could be implemented if that functionality is added.


If you are reading this, vote for the feature.

Unit Testing SimpleFormController

I could not find this very easily searching Google. At first, I figured you could just set the formSubmission property to true but it is a read-only property. I ended up checking out AppFuse’s source code because I figured the solution would be there. It was a good guess. The trick is to make sure your MockHttpServletRequest is a POST when testing a form submission. Seems kind of obvious now =).



request = new MockMultipartHttpServletRequest();
request.setMethod(WebContentGenerator.METHOD_POST);