jump to navigation

Enterprise Swing Best Practices August 6, 2009

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

I know this blog is about J2EE, i.e. enterprise Java on the server side. But the past few months I’ve been working on an “enterprise” Swing-based desktop application. I say “enterprise” because it’s virtually the same as a server-side application – the only difference is that it’s using Swing for the presentation layer.

Anyway, I wanted to post up some of the things I’ve discovered: Swing is very easy, but it seems there aren’t many “best practice” guides for building an application using it. So, here is my list of “best practices”… hope you find it interesting!

  • The Presentation Model pattern is well worth using. It creates a much more loosely coupled dependency between the GUI code and the presentation logic.
  • On a similar note, using a binding framework (such as JGoodies Binding).
  • Use Actions (i.e. subclass javax.swing.AbstractAction) for use with menus and buttons etc.
  • For laying out forms, JGoodies Forms is awesome.
  • There are benefits to using component factories, i.e. a factory method to create your different UI components such as buttons.

I think that’s about it for the moment. The only other thing is, the Spring Rich Client Project (Spring RCP) looks really interesting, and I think if I was starting a new project I’d probably use it.

What are your favourite Swing tips?

Advertisements

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!

Spring Method Security May 13, 2009

Posted by Phill in Spring.
comments closed

Another quick post. I have been using Spring Security to secure methods in a desktop application. It was a bit tricky to configure because Spring Security is based on web applications, but actually it’s not much of a problem.

However, I kept getting AccessDeniedExceptions for authenticated users. It seems that all voters had abstained, which I found puzzling because the RoleVoter should have allowed the method call.

Anyway, it turns out that the RoleVoter has a built-in role prefix (“ROLE_”) which was causing problems, as ours have a different prefix.

In order to change this you will need to code the AccessDecisionManager yourself:


<bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">
<property name="decisionVoters">
	<list>
 <bean class="org.springframework.security.vote.RoleVoter">
<property name="rolePrefix" value="MY_PREFIX_" />
 </bean>
 </list>
 </property>
 </bean>

<security:global-method-security
 secured-annotations="enabled" access-decision-manager-ref="accessDecisionManager" />

Java, LDAP and Active Directory April 20, 2009

Posted by Phill in Other Stuff.
Tags: , ,
comments closed

I was trying to connect up to a Microsoft Active Directory server using Jxplorer. I kept getting the error message:

LdapErr: DSID-0C090334, comment: AcceptSecurityContext error

It seems that in the “User DN” field I was entering the username. This doesn’t work. Instead, you must use the fully qualified name, i.e. username@domain.com.

Just a quick post, hopefully this will be useful to someone else!

JUnit, Spring, and database transactions March 9, 2009

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

Quick post: I have a suite of tests running against the database. All of these tests need to run in a transaction – which is then rolled back at the end.

However, due to unusual circumstances I needed one specific test to run without a transaction. It turned out this is fairly easy to do in Spring, using AbstractTransactionalDataSourceSpringContextTests (a class Spring provides for running tests in transactions). You just need to override the runBare method:

public void runBare() throws Throwable
{
  if (getName().equals( "methodName" ))
  {
     preventTransaction();
  }

  super.runBare();
}

Easy when you know how! There was nothing in the docs detailing this code exactly, but I managed to figure it out with a combination of javadocs and reading the source code (probably unnecessary, but still).

Grinder: It pays to read the FAQs… February 23, 2009

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

I was trying to test a web service using Grinder on a Windows machine, and kept running into “BindException: address already in use” errors. I thought it was a problem with my connection pool, so spent about half an hour messing around with the pool settings.

It turns out that I should have read the FAQs.

Doh!

Creating JAR files with dependencies February 16, 2009

Posted by Phill in Other Stuff.
Tags: , ,
comments closed

File this one under “spend a few minutes Googling without success!”

If you’re trying to package up a Java application into one JAR file for easy deployment – including all dependency JAR files – there aren’t many options.

There’s a plugin for Eclipse called “Fat Jar” which I haven’t tried out. I’ve just discovered a tool called One-Jar, which does the trick. It’s simple to use. In my case, using Ant, it was a matter of:

  • Download the One-Jar JAR file.
  • Run it (using java -jar) to extract the contents
  • Add the one jar ant task plugin .jar file to my ant lib folder
  • Import the one-jar-ant-task.xml build file into my build file
  • Create a manifest.mf file with the One-Jar-Main-Class set
  • Add in the <one-jar> task to my existing build.xml file as per the instructions.
  • And you’re done!

The ant task does a lot of the work for you so it’s nice and easy. I’d recommend it, if you’re looking for a quick way to include dependencies in a single JAR.

Ant, dependencies, and slow servers January 26, 2009

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

At work I’m working on an application which uses an Apache Ant script to build it. Unfortunately we haven’t yet got around to using Apache Ivy, however all dependencies are stored in a text file and then downloaded from a central server in the build script. Not an ideal solution but it works for our needs.

The problem comes when the central server we use to store the JAR files slows down to a crawl (which has happened quite a lot recently). The past few days, the build script has taken over 4 minutes to complete – and most of that time is spent downloading JAR files (unfortunately there are two JAR files which needed to be downloaded each time – it’s too complicated to go into now…)! So I decided to make a change to the build script.

Now, it should only download when I update the text file with the list of dependencies. How is this accomplished? By using the <condition> task:

<condition property="lib.uptodate">
<and>
<uptodate srcfile="${basedir}/lib-jarlist" targetfile="${lib.dir}/lastupdated.txt" />
<uptodate srcfile="${basedir}/lib-jarlist-compile-only" targetfile="${lib.dir}/lastupdated.txt" />
</and>
</condition>

What this code is doing is checking two files (lib-jarlist and lib-jarlist-compile-only). If either of these two files have a newer timestamp than the target file (lastupdated.txt), than the condition will be TRUE. Then, all I need to do is put this in the download dependencies target:

<target name="download-deps" unless="lib.uptodate">
(download dependencies....)
<touch file="${lib}/uptodate.txt">

So, the target will only run if one of the JAR list files have been updated. Note the touch command at the end – this is important: it updates the file timestamp so that next time the script will see the update dependencies and not go off to the slow server for them.

It’s not a perfect solution, but will do until we can move to Ivy!

Firebug ‘Gotcha’ January 5, 2009

Posted by Phill in Other Stuff.
comments closed

I was debugging a few AJAX requests recently which didn’t seem to be working. I used Firebug to check exactly what was being sent back in the request.

After about an hour to-ing and fro-ing, eventually using an HTTP Debugging proxy, I found out what the problem was: Firebug doesn’t send the submitted POST data when you need to send another request to examine the response. Or at least, it didn’t for me (for some reason) – it turns out the AJAX request was working fine, I just couldn’t work out why my POST data wasn’t showing up!

Can’t believe I wasted so much time on such a stupid thing, but there you go!

How to Over-Analyse December 15, 2008

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

Apologies for the random post, but we were having a discussion on a question on StackOverflow about how to detect whether a string is a number in Java.

I posted up a possible WTF solution involving regexes.  (You’ll have to read the original question for all the background). Someone suggested instead using NumberFormat. Jon Skeet replied with a different solution as well.

After all the discussion I thought I’d do a quick speed test. It turned out to be a rather overblown, over-engineered speed test… but it produced some interesting results 🙂

Firstly, the code. I’ve uploaded it on my website so you can check it yourself.

The code tests three methods of checking to see whether a string is a number: using a (basic) regex, using NumberFormat.parse(…), and using the JonSkeet (TM) method. Each method is called 1,000,000 times per test and each test is run five times and then averaged.

These are the results on my machine:

--------------------
Testing: Regex Tester
--------------------
2672 2578 2562 2547 2594
Average time: 2590
--------------------
Testing: NumberFormat Tester
--------------------
9641 9531 9375 9391 9578
Average time: 9503
--------------------
Testing: Jon Skeet Tester
--------------------
235 218 235 234 235
Average time: 231

Using NumberFormat is 3x slower than using a Regex – although NumberFormat will parse a greater range of numbers (i.e. it parses numbers properly rather than using a rather dumb regex). But – Jon Skeet’s method is more than 10x faster than the regex. Ladies and gentlemen, I think we have a clear winner. Jon Skeet FTW! (But then, we all knew that anyway…)

Apologies for this interruption, normal blogging service will resume yada yada yada.

(Edit: I should point out that if you want the “Correct” method of checking whether a String is a number, you should use NumberFormat. This is maintained by Sun and will account for locales etc. Basically it is the canonical way of parsing a number. The regex method is probably good if you just want to check whether a String contains digits in one line of code, quick and dirty. And the Jon Skeet method is if you want correct AND fast, and can shove that method in a utility class somewhere).