Jun 07 2009

Spring Framework XML Schema Extensions…

Category: JavaPhil @ 8:20 pm

Seems like every time I dig into Spring, I learn something new. This week, it was the Spring Util schema. Like most developers, I never take the time to read the manual and usually only have enough time to get the job done. Unfortunately, the rush to get done typically highlights some features that I really did not understand or used improperly. I seem to get a lot more out of reading the documentation after seeing how all of the pieces go together. Fortunately, I’m usually not satisfied with this level of mis-understanding, so you are forced to read about how I fixed my mistakes!
Generally, if you are only using the IoC container feature of Spring (dependency injection), you can usually get by using the simple bean schema. I have messed around with Aspect Oriented Programming (AOP) integration using the AOP schema, but never used it in a real project and I always use the Transaction annotations, so I never bother with the Transaction schema either! When I started integrating the Spring Security framework into my last project, my Spring XML files started looking a little different, I started qualifying all of my bean tags.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
                         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
                         http://www.springframework.org/schema/security
                         http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
<security:global-method-security
secured-annotations="enabled" jsr250-annotations="enabled">
</security:global-method-security>
<beans:beans id="dateTimeBean" class="org.beilers.DateTimeBean">
</beans:beans>
<beans:beans id="timeDependentBean" class="org.beilers.TimeDependentBean">
<beans:property name="currenttime">
<util:property-path id="name" path="dateTimeBean.currentTime" />
</beans:property>
</beans:beans>
</beans>

I will write about the Spring Security framework in future post, but I wanted to highlight the Spring Util schema. I ran into a scenario last week where I wanted to use a property in an existing bean, to set a value in another bean; I could not pass in the bean, only the property. With the standard bean tags, there is no way to navigate a bean property path, such as bean.bean2.property. I knew there had to be solution to this problem, it seemed too common. With a little Google-ing help from a friend, we ran across the Util schema. There are some really convenient tags to help you manage your Spring configuration files. In the above example, I demonstrated the property-path tag to demonstrate path navigation. There as also other tags for accessing constants and fields, creating reusable lists and maps. Make sure you give this document a read, it can save you time and make your code cleaner and even add some type-safety to your XML.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Jun 02 2009

The Best Eclipse Plug-ins

Category: EclipsePhil @ 8:50 pm

I’ve ran across several blogs that listed their favorite Eclipse plug-ins.  Since I am such a huge Eclipse fan and am always preaching about the power and benefits, it seemed like a good idea for me to document my preferences and experiences. First, you need to start with the Eclipse Java EE version, probably the Ganymede version (3.4), but Galileo (3.5) will be released next week. This Eclipse bundle will give you more than you need, but is the best starting point. Out of the box, Eclipse has many useful features:

  • Mylyn – Task focused development support; here is some background information.
  • Web Standard Tools – Gives you all of the nice editors for XML, HTML, JSP, etc.
  • J2EE Standard Tools – Provides support for J2EE projects, such was the Servlet and EJB.
  • Remote System Explorer – Excellent plug-in for accessing remote systems. It enables you to remotely edit files and provides shell access, including SSH.

Here is my personal Top 10+ list of Eclipse Plug-ins:

Category Plug-in Overview
Code Quality Checkstyle Simple to use. Great for keeping the code consistent and helps enforce many good coding standards. My only dislike of this tool is the suppression implementation. Hopefully they will move to the PMD annotation style. A major new version (5.0) was just released, I have not tested it yet.
Code Quality PMD Little more complex to setup than Checkstyle, but is probably my favorite plug-in. It looks at the structure of your code, evaluating cyclomatic complexity, jUnit usage, and attribute scoping. It has some overlap with Checkstyle, but both tools together give you a complete solution.
Build Support Ivy I have blogged about Ivy in the past. Not my favorite plug-in, but required when using Ivy within Eclipse. If you work on multiple projects or do a lot of prototyping, Ivy is an awesome time saver.
Construction Spring IDE If you develop Spring-based applications, you will want to install this plug-in; it is a must have! The plug-in has numerous helpful views; and makes creating and managing your context files much simpler.
Construction Log4E Log4E make Java logging significantly easier, no more cutting and pasting from other classes. The free version supports the common logging frameworks, but unfortunately not the current open-source community favorite, SLF4J.
Construction Subversive This plug-in is used to integrate Subversion into the Team Perspective/View. It also appears to no longer be required with Eclipse 3.5.
Construction Subversive Team Provider There are two options for integrating Subversion into Eclipse, you can choose either the Tigris or Polarion implementation. The Tigris plug-in seemed easier to get working, but has less features than the Polarion implementation. I started with Tigris, but have settled on the Polarion version about a year ago.
Construction Implementors This plug-in allows you to navigate from any interface to an implementation of that interface. Especially helpful when you are programming with the Spring Framework. This feature is finally part of Eclipse 3.5, so you might not needs this one any more.
Testing Clover Clover is my only commercial plug-in; Clover is used to collect code coverage metrics. You have to be a little careful when using this plug-in. Never let Clover instrument the entire project, Eclipse will most likely become completely unresponsive and unusable. If you have a large project, I highly recommend using Eclipse Working Sets to selectively control which files you collect coverage data on.
Testing Findbugs This is actually on my to do; I have been very happy using Findbugs thru Ant, but have not had a chance to try out the plug-in.
Database SQL Explorer A database explorer tool is included with the Java EE Eclipse bundle, but it seems to have some usability issues. Most developers seem to be very dissatisfied with the included version and prefer the SQL Explorer plug-in. Probably not perfect, but it works good enough for us Java guys.

Just a random link of several more plug-ins, http://www.plentyofcode.com/2007/07/most-useful-top-50-eclipse-plug-ins.h6tml There were a few plug-ins on the list that looked interesting, maybe you will think so too. Make sure you read the comments!

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 26 2009

Eclipse – Project Facets

Category: EclipsePhil @ 7:38 pm

This Eclipse feature has been around for a couple years, but seems to stay hidden from most developers; probably because they have not had a chance to take advantage of the Dynamic Web project type. It seems like once a project is setup, nobody ever wants to change it! The Dynamic Web project type is used in conjunction with the Eclipse Web Tools Platform (WTP) plug-in, which has been on my “Upcoming” list for some time now…

<HISTORY>I was a huge fan of the MyEclipse plug-in suite a few years ago; it was a predecessor to the nicely bundled Eclipse distributions that can be downloaded today. MyEclipse provided a very elegant Eclipse / Weblogic integration capability; as well as many other nice features that otherwise were difficult to manually enable. I worked with many different teams and it was always a hassle to convince them to purchase or convert their projects to the structure required by MyEclipse. As I became more familiar with the Ganymede release and the maturing Web Tools Platform plug-in, this Eclipse bundle seemed to be a much easier to sell and better alternative. MyEclipse is still a very popular and well put together product; be as I recall, it always took them too long to catch up with the current Eclipse versions, which I was fond of using as well.</HISTORY>

To use WTP, your project needs to have some additional features, namely Facets. Facets are used to define characteristics and requirements for Java EE projects. Originally, only Java EE projects had Facets; but this seems to be changing. I recently added some J2EE Module Dependencies to a web project, Eclipse enabled Facets in the simple Java project included as a dependency. To convert an existing project to a Faceted project, you need to manually modify your .project file. It is best to only enable Facets and let Eclipse add the additional nature; these natures will be added as you enable extra characteristics. To convert a Java Project to a Web Project, modify the .project file and add the following two lines.

<nature>org.eclipse.wst.common.project.facet.core.builder</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
 

You will not notice any visual difference in your project after making this change. However, if you open up your project’s properties and search for the word facet, you will see a new configuration option. At this point, you can select the Dynamic Web Module option and configure your runtime environment (Tomcat, Jetty, etc).

If you have successfully converted your project, you will see a small globe appear on the project folder icon. You can now add the project to the Servers view and easily deploy the project in your locally configured runtime environment. I have glossed over some of the WTP setup, but will cover that in another post. I thought it was important to explain Facets; I had previously wasted significant time, manually converting projects to Dynamic Web projects. Unfortunately, the manual approach only worked about 50% of the time. Once I learned about Facets, it made my life a lot easier!

FYI, the (S) on the folder, next to the globe, indicates a Spring IDE plug-in enabled project.  If you are developing Spring-based applications, you have to install this plug-in; it makes creating and managing your context files many times simpler.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 25 2009

Galileo – Eclipse 3.5 Coming Soon?

Category: EclipsePhil @ 8:09 pm

I only played with Galileo for about 10 minutes and I am already very intrigued. Based on my last post, I wanted to see if I could get Ivy and Eclipse to work better together and explore the new features. The first difference appears to be the way that plug-ins are installed and managed. Eclipse 3.4 significantly changed the way plug-ins were installed and it looks like they are changed again. Plug-in management was never as smooth as NetBeans. NetBeans provides a fully integrated solution for searching through available plug-ins, with click and go installation. The new Eclipse implementation looks promising, maybe not as polished as NetBeans, but a step in the right direction. As shown to the right, you can now view all of the available plug-ins in a much more controlled and usable approach. Managing additional software sites is much cleaner than before too.

At first glance, there seems to be a lot of small, subtle changes, rather than any big, must have features. The Eclipse release process appears to be taking longer and longer; the first milestone release was last August! This is the first time I have not jumped on the milestone builds, preferring to stick with the Ganymede release for my daily usage. Another small change is the way the network proxy panel works; it actually seems more complicated than it was before! They finally added (or re-implemented) one on my favorite plug-ins,  the “open implementation” option. How could that feature not been part of Eclipse before this? It is an absolute necessity when programming with Spring. Overall, I think Galileo looks a little more polished than before; I will start using it for my daily work and try to find more interesting new features to report on!

A new to me feature… After adding the IvyDE plug-in to Eclipse, the next step is to add the Ivy managed dependencies to the project. I found a new project properties panel, Java EE Module Dependencies. I thought this was a new feature, but it appears this feature was available in Eclipse 3.4 too. I hoped this was the answer to my Ivy problem! The panel allows you to pick other projects and/or their class path entries to be added as web library dependencies; it suggested that these dependencies would be resolved at deployment time. I gave it a try, but unfortunately it only half worked. The dependent project part worked perfect; making a JAR file out of the secondary project and copying it over to the exploded WAR’s WEB-INF/lib directory. This seems like a good solution when working with external projects, especially when you are activity integrating them into your primary project. The unfortunate part is that Eclipse still completely ignored the Ivy dependencies; not copying any of the Ivy resolved JAR files to the WEB-INF/lib directory. What a drag! I will have to continue my quest for a workable Ivy / WTP solution!

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 24 2009

Blogging with Live Writer

Category: BloggingPhil @ 3:42 pm

imageAs a developer, I prefer the Ubuntu experience over the Windows experience. However, when I’m updating the checkbook and paying bills, I don’t see many good, non-Windows options. I have been blogging with ScribeFire for quite some time and have been very happy with it . A read a blog on Live Writer some time ago and installed it; foimager some reason I never used it,

I decided to give it a try this weekend and have to say, it is pretty nice. Functionally they are pretty much the same, both integrating nicely with WordPress. Subtle differences include:

  • ScribeFire saves the drafts on the server, where as Live Writer saves them locally on your computer.
  • Not that it is a big deal, but Live Writer seems to have better preview support, at least with my current theme.
  • Live Writer also integrates nicely with Live’s maps and photo albums. Images are actually easier to integrate with in Live Writer too, more directly editable properties.
  • Live Writer also support HTML tables, which you have to create by hand with ScribeFire.
  • The spelling checker seems better in Live Writer too. Unfortunately, neither one has an integrated thesaurus.

So, if you are blogging on Windows and want to use a nice little editor, give it a try. I think you will be generally surprised by this Microsoft product.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 24 2009

Still on the Jetty Bandwagon… Go Embedded?

Category: Eclipse,Software DevelopmentPhil @ 2:23 pm

image I was searching for some information on using the Eclipse IvyDE plug-in and found a post that reminded me of some work I did last summer. For the most part, I’m happy with the way the IvyDE plug-in works, but sometimes you have to be a little tolerant of its usability issues. Every so often, IvyDE seems to forget about my configuration and refuses to add libraries to the class path. My only option is to remove Ivy Dependency Manager and re-add it to the class path.  One problem that I’ve been unable to solve, is the integration of an Eclipse Web Tools Platform (WTP) project and Ivy; I cannot get the Ivy resolved libraries added into a “Dynamic Web Project”, making them available to the Tomcat. I have tried a dozen different configurations and settings with no success. Hopefully, I will get this working in the near future. If anyone has this working, please give me some tips!

The real thought behind this post was echoed in this post by Daniel Spiewak, So Long WTP, Embedded Jetty For Me. I was really fired up about Jetty last summer. When compared to my experience developing Weblogic-based applications, the utter simplicity and flexibility of Jetty was amazing. I was working on a custom Servlet-based web service framework and decided to do my development with Jetty. I created a very small Java program that configured Jetty to deploy my Servlet, in about 20 lines of code! The best part is there was no special Eclipse project type, no special environment, and zero deployment work; making debugging and testing especially easy.  I never used the word embedded when I talked about Jetty, but that was exactly what I wanted. I always deployed in the Weblogic container because of our corporate standards. I should have explored this a little more, further highlighting the point that Weblogic and all of its complexity is truly unnecessary.

Following the BEA Bible, you end up with specific machines, specific file systems, specific networking, and hardwired clusters. Combine that with an environment that is highly controlled, it can take a dozen change control tickets and multiple days to bring up a new instance. Not exactly what I call agile or responsive. How cool is would it be to just drop a WAR file on a machine (any available machine), launch java to bring up a web server, add it to the load balancer and instantly expand your processing capacity? Pretty powerful idea, I think.

Embedding a web server is a good idea when building a web-based application, both for development and operational reasons. A good example is the Hudson Continuous Integration tool. Hudson is distributed as a single WAR file that you can pop in any Servlet container; but it also includes an embedded web server. This approach is becoming more and more common, as several open-source and commercial products are shipping their products with embedded web servers. The real benefit is flexibility. It literally took me seconds to get Hudson up and running; no messing around with Tomcat, no configuring security realms, no anything! It allowed me to focus on Hudson, rather than the environment to make it work. Down the road, if I want to deploy Hudson in the standard application server environment, it should be an easy switch, This is quite different from my recent experience installing a few open-source code review tools; installing multiple Python packages, configure an Apache web server, setting up database servers, etc. I don’t think I have to say much more; the better choice is pretty obvious.

image It is pretty hard to beat the Eclipse WTP – Apache Tomcat integration as a development environment, but directly embedding Jetty into your environment (no WTP) would make the environment even simpler. I have been trying to encourage teammates to develop from a container independent perspective, demonstrating higher productivity with no additional risk to the project. If we can move from large, monolithic applications to smaller, self contained services, the attractiveness of Jetty goes way up. The flexibility of running a moderately sized collection of small, independent services, verses a small tightly coupled clusters of monoliths, has to be an attractive architectural vision.

Unfortunately, many corporations don’t eagerly embrace open-source software solutions, preferring to pay for name recognition and guaranteed support. I personally feel that Jetty is a viable option, but it seems to be relatively unknown to most developers. Apache Tomcat and JBoss have a much higher exposure level, giving them more perceived viability. Jetty is no slouch, check out the Powered by Jetty page. Hopefully, this and Daniel’s post demonstrate there are alternatives to the J2EE Silver Bullet, and that we don’t really need to do everything by the J2EE book. There are a lot of simple alternatives out there for us to take advantage of, all we have to do is keep an open mind!

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 21 2009

Unbelievably Simple Java Zip Example… And What About Reuse?

Category: Java,Software DevelopmentPhil @ 5:15 pm

I was working on a typical web portal application today and needed to support a multi-file download. Luckily, I had some code which I had used several times before. I started to tweak it for my specific requirements, realizing it was such a bad fit, I quickly tossed it out. My previous implementation worked with physical files and was tightly coupled to a legacy framework. This time, the files were already in memory. I was hoping to find some code that allowed me to build the zip file in memory, rather than dealing with the file system and temporary files. Since the portal user could only download a limited number of files at one time and the files were very small, I didn’t have to worry about memory constraints.

Bottom line, I found the perfect piece of code on Trip over IT. Within 15 minutes, my application was downloading a sweet little zip file! The code was so simple and concise, I had to share it. I will definitely put the code in my tool box of handy snippets. 

Here is a provocative thought: What is the point of a reusable library? Do we focus on reuse because we continually over-design and over-build our software, thinking that we are saving time by building these reusable libraries? Are there alternatives? What about simple, small, and disposable code? Don’t be so attached to your masterpiece. I promise, it will not look so elegant tomorrow! All you really need is Google to find some code to start with. I found this little snippet of code, changed it to fit my problem, and I was done within a few minutes, no support and minimal overhead. Maybe the real reuse is my memory and ability to relocate this snippet in the future… Or am I just crazy?

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 19 2009

How to customize your jUnit Behavior and Interaction

Category: Java,Misc,Testing,UbuntuPhil @ 8:17 pm

I have tried to walk through the jUnit source code a couple of times, trying to figure out how to implement my own behavior; only to give up in frustration (no I did not read the documentation, real developers don’t do that, they Google!) Why would I want to implement my own behavior? Well, it always seems to center around integrating with Spring. I usually want/need to do control the way the context is being created or do something immediately before the context is loaded or as the context is loading; something that might not be possible not possible using a @BeforeClass annotation.

This problem was actually related to my previous blog on Implementing Custom Scopes in Spring. Because I implemented some beans using the session scope, I kind of created a catch-22 scenario;  I have tried to capture the problem in bullet form:

  • Each jUnit test needs the ability to specify the specific test user (role, user info, etc.) that is relevant for that individual test
  • The test user profiles are configured and controlled by a Spring managed bean
  • All beans are lazy-init = true and injected into the unit test using the @Resource annotation
  • The session scope beans need to have the SecurityContextHolder configured with the appropriate principal (test user), before they are created
  • So, the problem is: How do you specify the test user, before the session scope beans are created and injected into the unit test class?

In a normal execution environment, using the Spring Security filters and a Servlet, the SecurityContextHolder would have been assigned using the authenticated principal, before creating any Spring dependencies. Because I created my own custom scopes for unit testing, the SecurityContextHolder was null and the session scope beans constructor was failing an assertion (principal != null). I could have easily fixed this by adding a pre-authenticated user to the SecurityContextHolder, using some static method approach,. However, because my mechanism for handling test users was itself a Spring bean, I had no possible way of specifying before the beans were injected into my unit test.

When jUnit 4.0 was released, it added several new constructs that make some very elegant solutions. I don’t think most developer’s ever look beyond the base jUnit functionality; fortunately it seems to solve 99% of the typical test scenarios. The new constructs are actually specified via annotations, they are the @RunWith and @TestExecutionListeners. My example code, can probably be made a little cleaner, but my main goal was to get the unit tests working. Because you don’t directly create any of these objects, you have to be aware of the timing; implement your customizations at  the correct point in the lifecycle. Another interesting problem, is that you don’t actually create the Spring Context, but you can interact with it via listeners.

First, we need a class which extends DependencyInjectionTestExecutionListener. This base class is required when using Spring and provides several override-able methods. I needed to configure the SecurityContextHolder, before any beans were injected into the unit test; I could accomplish this by utilizing the injectDependencies method. To support my testing needs, I added two (2) properties to the sub-class (this could have been cleaner); one to specify a user from a “user provider” factory, and a simpler one that used the user id of the person running the test. As you can see from the code, before an beans are injected into the unit test, I have access to the Spring context. This allows me to request the “user provider” factory and then request a specific test user. At this point, I can now assign the user to the SecurityContextHolder; all before any of the session scope beans are created.

public class AuthorizedTestExecutionListener extends DependencyInjectionTestExecutionListener {

    private TestUserAuthorization defaultAuthorization;
    private String                junitAuthorization;

    public void setJunitAuthorization(final String junitAuthorization) {
       this.junitAuthorization = junitAuthorization;
    }

    public void setDefaultAuthorization(final TestUserAuthorizationdefaultAuthorization) {
       this.defaultAuthorization = defaultAuthorization;
    }

    @Override
    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
    protected voidinjectDependencies(final TestContext testContext) throws Exception {
       if (StringUtils.isNotBlank(junitAuthorization)) {
           final Authentication login = new UnitTestAuthenticationToken(this.getClass().getSimpleName());
           SecurityContextHolder.getContext().setAuthentication(login);
       }
       else if (defaultAuthorization != null) {
           finalTestUserModuleManager manager = (TestUserModuleManager) testContext.getApplicationContext()
                    .getBean(defaultAuthorization.testUserManager());
           final SecureUserInterface user = manager.find(defaultAuthorization.principal());
           final Authentication login = new UnitTestAuthenticationToken(user);
            SecurityContextHolder.getContext().setAuthentication(login);
        }

       super.injectDependencies(testContext);
    }
}

Next, we need to extend SpringJUnit4ClassRunner. This class is responsible for for creating the Spring test context and  DI listener class.  By over-ridding the  createTestContextManager, you have the opportunity to configure the test execution listeners.  I  also created two custom annotations, TestUserAuthentication and  JUnitAuthentication.  Using either one of these annotations, I could provide run-time meta-data  to my  custom AuthorizedSpringjUnit4ClassRunner; the meta data was then used to configure my custom  AuthorizedTestExecutionListner.

public class AuthorizedSpringjUnit4ClassRunner extends SpringJUnit4ClassRunner {

    public AuthorizedSpringjUnit4ClassRunner(final Class<?> clazz) throws InitializationError {
       super(clazz);
    }

    @Override
    @SuppressWarnings("PMD.ConfusingTernary")

    protected TestContextManager createTestContextManager(final Class<?> clazz) {

       final TestUserAuthorization defaultUser = clazz.getAnnotation(TestUserAuthorization.class);
       final JUnitAuthorization jUnitUser = clazz.getAnnotation(JUnitAuthorization.class);

       final TestContextManager context = super.createTestContextManager(clazz);

       for (final TestExecutionListener l : context.getTestExecutionListeners()) {
           if(AuthorizedTestExecutionListener.class.isAssignableFrom(l.getClass())) {
               if (defaultUser !=null) {
                    ((AuthorizedTestExecutionListener) l).setDefaultAuthorization(defaultUser);
                }
               else if (jUnitUser != null) {
                    ((AuthorizedTestExecutionListener) l).setJunitAuthorization(clazz.getSimpleName());
                }
            }
        }
       return context;
    }
}

Once you understand what all of the pieces do, they are super easy to customize to provide enhanced behavior. I think my solution provided a very clean, elegant solution for providing test specific user profiles, on a test by test basis.

@RunWith(AuthorizedSpringjUnit4ClassRunner.class)
@TestExecutionListeners(AuthorizedTestExecutionListener.class)
@ContextConfiguration(locations = {//
"/com/beilers/resources/spring/contexts/jUnitContext.xml" //
})

public class UnitTestHelper {
...
}
https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 18 2009

WordPress Code Publishing Plugin

Category: BloggingPhil @ 12:01 am

I thought I would be fancy in my previous post and tried to use a WordPress plug-in to make my code look pretty. I downloaded WP-Syntax and gave it a try. Seemed simple enough <pre lang=”java”>…</pre>. Don’t know what the problem was, but it just toasted my code!  I think it might have to do with remote publishing,  using the XML API. I must have messed with it for about 30 minutes, before I finally gave up and resorted back to simple HTML. I thought I would try one more plug-in tonight; it was called Syntax Hilighter Evolved. The usage is similar to the WP-Syntax, but I finally got this one to work using the built-in WordPress editor.

My next post will be about creating your own Java 1.5 Annotations and adding new behavior to your unit test suite. I thought it was actually a pretty cool exercise… but that is just me!

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TestUserAuthorization {

String principal();

String testUserManager();
}

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 17 2009

Unit Testing Custom Spring Scopes

Category: Java,TestingPhil @ 6:45 pm

I recently worked on a JSF-based application that was integrated with Spring, both the Core Framework as well as the Spring Security Framework. I certainly don’t have it all mastered, but the experience has given me multiple topics to blog about! We decided to let Spring manage all of the beans, rather than making JSF manage some of the beans and Spring manager the rest. I liked the consistency and thought it would make unit testing easier. Spring provides two basic scopes, singleton and prototype. When you add Spring Security into the mix, you get two additional scopes, one for session and another for request.

This should have been no big deal. To my surprise, when I wrote my first unit test, I discovered the session and request scopes were not supported; the bean factory threw an unsupported scope exception when I asked for the bean. Googling did not lead to any exact answer, but I found lots of examples; many developers seem to implement a thread scope. I simplified one of the many implementations I found, as I only need to support unit testing.

The first step is to build your own class that implements the Spring Scope interface. I created a generic class, such that I could use it for any custom scope.

public class CustomScopeHandler implements Scope {

     private final Map<String, Object> hBeans = new HashMap<String, Object>();

     public Object get(final String name, final ObjectFactory factory) {
        Object result = null;

        if (hBeans.containsKey(name)) {
            result = hBeans.get(name);
        }
        else {
            result = factory.getObject();
            hBeans.put(name, result);
        }

        return result;
    }

    public Object remove(final String name) {
        Object result = null;

        if (hBeans.containsKey(name)) {
            result = hBeans.get(name);
            hBeans.remove(name);
        }

        return result;
    }

    public String getConversationId() {
        Assert.state(true, “Needs to be implmented – ConversationId”);
        return “N/A”;
    }

    @SuppressWarnings(“PMD.DoNotUseThreads”)
   public void registerDestructionCallback(final String name, final Runnable callback) {
        Assert.state(true, “Needs to be implmented – DestructionCallback”);
    }
}

The next step is to add your custom scopes to the IoC container. Using the Spring CustomScoptConfigurer class, you can easily add as many scopes as you like. Pretty simple! Now you can execute your unit tests as you would have initially expected. One thing to be aware of, this implementation treats beans as if they are singletons. You could easily eliminate the Map and return back new instances on each invocation. It all depends on your specific needs, mine were pretty simple.

      <bean class=”org.springframework.beans.factory.config.CustomScopeConfigurer”>
            <property name=”scopes”>
                  <map>
                        <entry key=”request”>
                              <bean class=”test.scope.CustomScopeHandler” />
                        </entry>
                        <entry key=”session”>
                              <bean class=”test.scope.CustomScopeHandler” />
                        </entry>
                  </map>
            </property>
      </bean> 

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


« Previous PageNext Page »