Spot the bug… October 28, 2009
Posted by Phill in Other Stuff.Tags: bugs, java, operator precedence
add a comment
Have you ever written something really stupid but not noticed it for ages?
Witness this statement of mine I wrote a month or so ago. The point of the code is to append a prefix to an existing description, or the empty string if the description is null.
description = prefix + " " + description == null ? "" : description;
Can you spot the error?
It turns out that Java was looking at this statement like this:
description = (prefix + " " + description) == null ? "" : description;
D’oh! Not what I intended! I changed the statement to put brackets round the description == null ternary statement and it seems to work.
Just goes to show, brackets are generally a good idea when making statements like this – it’s too easy to make mistakes with operator precedence otherwise!
JAI October 19, 2009
Posted by Phill in General J2EE.Tags: imageio, jai
add a comment
Recently I had a project where I needed to use Java Advanced Imaging (JAI) to convert TIFF files into JPG. (Unfortunately Java doesn’t provide a TIFF decoder out of the box).
I had an issue today whereby I needed to deploy the application on a server (it’s a web app). I kept coming up with errors about JAI not being able to find the TIFF decoder:
java.util.NoSuchElementException
at javax.imageio.spi.FilterIterator.next(Unknown Source)
For anyone who is Googling it!
Anyway, it turns out that I had got jai_core.jar and jai_codec.jar in my WEB-INF/lib folder (these are both part of the standard JAI Distribution), but for some reason I also needed jai_imageio.jar (which is part of the JAI-ImageIO package).
I can’t quite fathom why you need so many JAR files, but it seems to work now, so there you go. Hope this helps someone else out!
Wicket September 17, 2009
Posted by Phill in Frameworks, General J2EE, Presentation Layer.Tags: jsf, wicket
add a comment
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.
Enterprise Swing Best Practices August 6, 2009
Posted by Phill in Presentation Layer.Tags: best-practices, gui, swing
3 comments
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?
Using Spring Security in a Swing Desktop application June 12, 2009
Posted by Phill in Frameworks, Spring.Tags: desktop, spring security, swing
3 comments
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.add a comment
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: active directory, java, ldap
add a comment
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: database, junit, prevent, Spring, transaction
add a comment
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).
Creating JAR files with dependencies February 16, 2009
Posted by Phill in Other Stuff.Tags: jar, one-jar, package
add a comment
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.xmlbuild file into my build file - Create a
manifest.mffile with theOne-Jar-Main-Classset - 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.