jump to navigation

Fun with Spring, GWT and Annotations March 4, 2010

Posted by Phill in Frameworks, Spring.
Tags: , , , ,
comments closed

Recently I’ve been porting across some of our monolithic IceFaces application to a more modular GWT application. (There’s nothing wrong with IceFaces as such, but for several reasons I don’t think it’s the right fit for us any more).

It’s been going pretty well so far, although I’ve only been working on it for a few days. I’ve got the GWT-Widget server library up and running as well, which integrates nicely with Spring for RPC. (It basically means you don’t have to define a new servlet in web.xml for each RPC server you want, you can just define them as Spring beans).

However, it does mean that you have to create a mapping for each Spring bean that you want to publish and define it in the application context XML, which isn’t really ideal for modular applications: I’d quite like them to be detected automatically with annotations, that way if you have another module on the classpath it will automatically be picked up.

So, I created another annotation (@RPCService) and annotated my RPC endpoints with it. The annotation, as its value, had the URL of that endpoint (i.e. “/user” for the users RPC service)

Then, my initial thought was to use Spring to scan the classpath and load each one up. I’ll cut a long story short here and say that was all unecessary: if your RPC classes are defined in the application context (via XML or annotations, it doesn’t matter), all you need to do is get an instance of the Application Context and call getBeansWithAnnotation.

This makes things really simple: I have a bean set up which has an initialise method that uses that method to get all classes annotated with my RPCService annotation, finds out their URLs, and then configures the GWTHandler servlet to map those beans.

Dead easy! And very useful to do, if you’re using the GWT-Widgets library.

Edit: After reading the documentation it seems that what I’ve done is essentially re-implement what’s already available in the library. Still, hopefully it will come in useful if you need to do something similar for another usage…

JSF, Float, and f:convertNumber February 16, 2010

Posted by Phill in Frameworks, Presentation Layer.
Tags: , , ,
comments closed

I’ve been having some fun issues with JSF and converting Float issues. Essentially the problem occured when converting a primitive float type to a java.lang.Float type in my value object (I was trying to updating a float value from an inputText field). I kept getting errors like:

java.lang.IllegalArgumentException: argument type mismatch

Anyway, I found an answer which seems to work, but rather than post it directly here I’ll simply link to the original question on StackOverflow (in case someone posts a better answer subsequently!).

These kind of issues are one of the many reasons why JSF has gone down in my estimation… it’s not a bad framework, it just seems to make what should be simple things massively complicated! That said, JSF 2.0 looks good, so maybe it will solve these kind of issues.

Wicket September 17, 2009

Posted by Phill in Frameworks, General J2EE, Presentation Layer.
Tags: ,
comments closed

The past few days I’ve been prototyping for a new project we’re starting up at work. Previous web projects we’ve done have mainly been using JSF, however for this project I’ve been looking into Apache Wicket.

My first impressions are, I like it. I like it a lot, in fact. It seems to achieve a much more clean separation between code / components and HTML than other frameworks do. It does take a while to get your head around it though – I’ve only been working with it for a few days so am still finding my way round!

But I expect I will blog up some info when I’ve got my head around it.

Using Spring Security in a Swing Desktop application June 12, 2009

Posted by Phill in Frameworks, Spring.
Tags: , ,
comments closed

It seems like there’s very little support (in terms of documentation) for using Spring Security in a Swing (or general Desktop) application. All the documentation I could find assumed that Spring Security was going to be used in a web application.

However, it’s very possible to use the security framework in a Swing application – a little custom code is required, but then, that is only to be expected!

Essentially what we did is create a LoginUtils class, which had an authenticate(username, password) method. This referenced the Spring AuthenticationProvider (we’re using a custom LDAP AuthenticationProvider, but you can use whichever suits your needs).

This is what the code looks like:

public Authentication authenticate( String username, String password )
 {
 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( username, password );

 Authentication auth = _authProvider.authenticate( token );
 if (null != auth)
 {
 SecurityContextHolder.getContext().setAuthentication( auth );

 _eventPublisher.publishEvent( new InteractiveAuthenticationSuccessEvent( auth, this.getClass() ) );

 return auth;
 }
 throw new BadCredentialsException( "null authentication" );
 }

You can then call this method from wherever you want in your application (for example, from a Login action) and your user will be logged in.

Both _authProvider and _eventPublisher are dependency-injected properties.

Notice the _eventPublisher.publish(…) call.  You do not need this if you have nothing listening out for those events. However, if you do not publish them then they will not be published, so it’s worthwhile doing – particularly if you’re writing a security framework!

The other important thing is – and this is something which caught me out first time round – is that the SecurityContextHolder by default uses a ThreadLocal pattern. For a Swing application you will want the Global pattern. Put this somewhere in your code (i.e. a static initializer, or your main method):

SecurityContextHolder.setStrategyName( SecurityContextHolder.MODE_GLOBAL );

This means that the Authentication object will be available to your entire application – if you don’t do this, objects on a different thread to the one you logged in on will not be able to ‘see’ your credentials. For a while I couldn’t figure out why my Authentication object was coming back as null, until I realised!

Note: this post is application to Spring Security 2.0.4. At the time of writing, version 3 is only at milestone 1 so I have not tried it yet!

Creating a lazy-loading tree with IceFaces July 7, 2008

Posted by Phill in Frameworks, Presentation Layer.
Tags: ,
comments closed

I tried a number of things to make a lazy-loaded tree in IceFaces, but I couldn’t quite get it to work. There are probably better ways of doing it, but I found something which is pretty easy: when you create your lazy-loaded TreeNodes, for each node which hasn’t had its children loaded yet just create a dummy child. In other words, if you don’t want a node to be lazy-loaded, just add a TreeNode child in which says something like “Loading…”. You will also need to subclass DefaultMutableTreeNode to add in a boolean property – something like childrenLoaded.

Then, in your JSF page, set the tree actionListener property to be “#{beanName.expandListener}” and create the relevant method in your backing bean:


public void expand( ActionEvent e )
    {
        Tree tree = (Tree) e.getSource();

        TreeNode node = tree.getNavigatedNode();
        if ("expand".equals( tree.getNavigationEventType() ))
        {
            _treeModel.loadChildren( node );
        }
    }

… assuming, of course, that your TreeModel has a “loadChildren” method on it. Your mileage may vary. You will, of course, need to check whether the children have already been loaded for that node. But it’s still probably the easiest method that I’ve found so far!

More on JSF and Spring Integration: MessageSources June 18, 2008

Posted by Phill in Frameworks.
Tags: , , ,
comments closed

A couple of days ago I wanted to move my application messages file out of the classpath into WEB-INF for some reason which I can’t actually remember now. Anyway, Spring definitely supports loading message files from WEB-INF, but I don’t think JSF does (I think it loads resources from the classpath).

Plus, it makes sense to have all messages loaded from the one MessageSource – that way, if I add another messages file, the configuration will only need to be changed in one place.

After a bit of Googling, I managed to get it to work. If you want to have JSF using a Spring MessageSource, you will need to use the following class: MessageSourcePropertyResolver. Copy and paste that into your codebase somewhere. Then, edit your faces-config.xml file and add in the appropriate element:

<application>
<property-resolver>
      com.package.MessageSourcePropertyResolver
   </property-resolver>
</application> 

Then, you can use the MessageSource in your JSF pages like this:#{messageSourceBeanName[‘message.key’]}

Tip: I don’t like typing out “messageSource” every time I want to use a message in a JSF page – I always used the shorter “msg” before. You can do this with Spring – just alias your MessageSource bean with the name “msg”. For example,

<alias name=”messageSource” alias=”msg” />

JSF Issues May 14, 2008

Posted by Phill in Frameworks.
Tags: , ,
comments closed

The project I’m currently working on is using JSF and IceFaces. It’s been a while since I used JSF, and I’d forgotten just how annoying it can be at times. The problem is always using frameworks that write the HTML for you: if you don’t have so much control over what is actually output to the browser, if you have a problem (which you inevitably will) fixing it will not be a simple matter.

Take today, for example. I wanted to include a custom JavaScript on an IceFaces page. Simple enough, you would think. Unfortunately, I had a problem where it would only work once you’d refreshed the page! Bizarrely, Firebug showed the JavaScript as existing in the JavaScript body – but it didn’t seem to actually be loaded by the browser.

I think this might be a problem with the way IceFaces loads things up using AJAX, but either way i’m none too impressed. The solution for the time being is to actually use a <redirect/> tag in my faces-config.xml (as suggested on this thread), this isn’t an ideal solution but it seems to work for the moment.

Although JSF does make some development quicker, the amount of time you lose to stupid problems like this probably negates any gains you made originally.

For the next web based project I do, I think I will try something like Spring WebFlow or Wicket, which both look like very interesting frameworks and don’t suffer from the same issues as JSF (although undoubtedly they have their own issues!)

JSF and IceFaces April 4, 2008

Posted by Phill in Frameworks.
Tags: , ,
comments closed

I mentioned a couple of posts ago that I was trying out Google Web Toolkit. Well, I’ve come to the conclusion that Google Web Toolkit is not the right solution for this particular project.

The problem was mainly one of scope: I think GWT, due to the way it’s designed, is more for small-to-medium size projects at the moment. The project which I am currently working on is small at the moment, but we will need to integrate various other things with it in the future and it will grow.

I did look at Echo2 as well (thanks to Dalibor for pointing it out to me), and that does look good – more like it would be able to handle larger applications, due to the way the page is loaded – but I don’t think it’s exactly what we need at the moment either.

What we have done is use JSF with IceFaces. IceFaces is a “Web 2.0” framework for JSF, i.e. it provides a set of JSF components which are AJAX-enabled. It was a bit of a struggle to get working with Tomcat 6.0, but I got there in the end!

Anyway, I’ve been using it for a couple of days now and I really like it. The AJAX is handled completely transparently to you – you just design your JSF application as you would do normally, and IceFaces will handle the AJAX. As an example, it’s really this simple to add an AJAX based table to your JSF page:

1. Use an IceFaces “dataTable” component
2. Have an IceFaces commandButton call the backing bean to populate the table with data (for example, search results)
3. The data table is updated automatically without needing a page refresh
4. …
5. PROFIT!

    Ok, I admit it, items 4 and 5 are not part of it. But still, I think it’s pretty good going.

    There is a bit of configuration to do before you start, but then that’s the same with pretty much any framework I know!

    What I’m trying to do at the moment is set up a “Loading” message, i.e. when you click on a button which will execute a long operation (for example, doing a text comparison on a lot of database fields) a loading message will be shown. By default no message is shown, and I can’t find a way of automatically displaying one for every call (ala DWR).

    Google Web Toolkit March 18, 2008

    Posted by Phill in Frameworks.
    Tags: , ,
    comments closed

    First off, in the “other news” department, I’ve started a new job recently. The main application here is based around Java Swing, however we are porting certain parts of it to the web and so I will continue to blog about JEE based things as and when they come up!

    The past day or two I’ve been looking at Google Web Toolkit. It’s a relatively new way of looking at AJAX application development: you develop all the code in Java, which then gets compiled by the Google compiler and translated into JavaScript. There are various benefits to such an approach, including having the type safety of a statically typed language in JavaScript, being able to unit test, that kind of thing.

    From my experiences recently it seems like a very useful tool for certain types of application. I will try and organise my thoughts and blog about it in the near future!

    Guice: A few thoughts July 2, 2007

    Posted by Phill in Frameworks, Spring.
    Tags: , ,
    comments closed

    I’ve just had a quick look at Google Guice (Guice is pronounced like ‘Juice’). It’s a dependency-injection framework, similar to the Spring Framework. However, it does have some differences. My initial thoughts on this I’ve tried to vaguely collate below. I apologise if I’m not making much sense, it might be better if you have a read through the Guice User’s Guide first!

    Pros:

    • Guice uses annotations and code rather than an XML file to manage dependencies. So, for example, I can write a method like with the signature: setDependencies(SomeClass dependency1, SomeClass2 dependency2) and just add the @Inject annotation to it. Guice will automatically detect populate the dependencies.
    • Guice is apparently a lot faster than the Spring Framework at initialisation. Because Spring has to parse in an XML configuration file, I can well believe this: parsing XML takes a lot more processing power.
    • Guice doesn’t index beans by name, it indexes them by class. So, to use an example, in Spring I might use the following code to get a bean:DataSource dataSource = (DataSource) applicationContext.getBean("DataSource");Whereas in Guice I would use something like the following:DataSource dataSource = injector.getInstance(DataSource.class)

      The Guice version is a lot cleaner (it avoids the cast) and less error-prone (using Strings is always liable to mis-spellings and typos)

    Cons:

    • Guice, at the moment, doesn’t contain a lot of the helper classes. Spring is much more comprehensive – there is absolutely no comparison at the moment. Of course, I don’t think Google want to compete on that level with Spring, and it’s probably not fair to draw that comparison, but I think it’s worth making the point at least. If you go with Guice you may have to use Spring anyway (for e.g. JDBC access, which you can do: Spring is quite modular).
    • I think the main reason for me preferring Spring at the moment is that in Guice, the dependency information is mainly stored in application code: you have to implement the ‘Module’ interface, which then loads up the classes and performs all the mapping required etc. The main difference between the two methods is that in Spring, this metadata (telling it which classes need which methods injected) is held in an XML file.If I want to configure a DataSource (for example), in Spring it’s fairly easy: you define the DataSource bean and have it load its properties from a properties file (or just specify them in the XML). In Guice, you would have to specify those properties either in application code or write a Provider which loaded up properties. Either way is not ideal.I think storing metadata outside of application code is the best way to go for Flexibility – if you want to change the dependencies in a Guice application, you would have to recompile it. This is really not desirable.This is why I will be sticking with Spring for the time being!

    There probably are a fair few things I haven’t mentioned, but I’ve only looked at Guice for an hour or two – not really in any great depth (as you can tell!). I will definitely be keeping an eye on Guice because I think it’s got a lot of potential – but for now, I think Spring is the framework for me!