Skip to main content

Posts

Showing posts with the label Java

Setting up Spring application & webapp contexts correctly in Java integration tests

When integration testing Spring web applications you would often pull in the applicationContext.xml and the appropriate *-servlet.xml file using the @ContextConfiguration annotation within the junit test class. The problem is that this loads both sets of beans into the same context which is different from when tcServer loads the webapp for real. In a real server, the application context is loaded into the 'root' context and each servlet into it's own separate context which is dependent on the root (see my set of previous articles for more details). To properly set up the contexts in a test environment so that they are loaded and treated the same as in a running tcServer you need to tell the test that it's a webapp test using the @WebAppConfiguration annotation and then use the @ContextHierarchy annotation to set up the order in which to load the contexts: @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(

cvc-complex-type.2.4.c issues - a few things to check

I've battled with the Spring cvc-complex-type.2.4.c issue on a few occasions but with them far enough apart that I can't remember what the steps are to solve it. This time round I thought I would write it down... You are writing a Spring-based app and you have some of your bean declarations in XML (I also use annotations but that's not important here). You wire your beans, you write your code and you build your application. Everything compiles and builds correctly, you run up your app in your container (in my case the dreaded Glassfish) and BOOM: Caused by: org.xml.sax.SAXParseException; lineNumber: 30; columnNumber: 76; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'jms:listener-container'. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper. createSAXParseException(ErrorHandlerWrapper.java:198) Here are a few things to check: Check that you have a element in your XM

Java Date & Time manipulation using Apache Velocity

Apache Velocity is an excellent tool if you need to bang out a quick bit of XML output or a text file with a particular layout and you don't want to do it all in Java. You create a Velocity template with your text in it and use various place-holders for the dynamic data that will be passed into it from your Java code. Velocity them merges the two together to give you a nicely formatted custom-filled file/document/SOAP request/etc. It's a great tool but does have it's quirks and downsides and one that I hit upon recently was how to display dates in a particular format. You can call methods on any Java object that you pass to the template but only if it's in the Java bean standard format of getX() and the Date formatting methods don't follow this standard. The solution was found within the optional Velocity-Tools library - DateTool. DateTool has a number of format methods on it which can twist the dates and times into any format that you need, here are some ex

Do 'is' boolean methods work in JSPs with JSTL?

When coding in JSTL you often want to use conditional logic (I'm thinking and the like) to be able to structure your page correctly. Auto-generated getter & setter methods will normally create isX() methods for the getters of boolean values (at least in Eclipse it does) but can you access this method directly from JSTL without writing a getX() version? Does JSTL support 'is' boolean methods though? Ask a random poll of Java we developers and you will get conflicting answers so I decided to investigate, want the short answer? YES - JSTL does support accessing isX() methods directly as if you were accessing a getX() method, but only if the return type of the isX() method is a primative boolean . If you return an object of any kind (such as Boolean isObjectBooleanTrue()) then JSTL fails to find the method and will give you a rather nasty JSP exception: javax.el. PropertyNotFoundException: The class 'com.andrewbeacock.BooleanTest' does not have the pr

How to stop Eclipse reformating your Java enumerations & comments

Eclipse is a wonderful IDE for the Java language and I’ve used it daily for at least the past 4 years but it does have some 'issues'. One is regarding it’s code formatting (or reformatting) support, normally it does a great job of putting stuff in the right place but there are occasions where it just fails to get it right. Enumerations When I write enums I like to have each item on it's own row, I find it's easier to read and amend in the future: public enum Family { MOTHER, FATHER, DAUGHTER, SON; } But Eclipse has other ideas and formats it so that it looks like this: public enum Family { MOTHER, FATHER, DAUGHTER, SON; } A way to get around this (and any other times where you have a few lines of code that you don't want collapsing into one is to add the double-slash style code comments to the end of each line: public enum Family { MOTHER, // FATHER, // DAUGHTER, // SON; } Block comments I recently wanted to have a decent

Misleading wiring messages with aliased Spring DataSources

When accessing databases in Spring you commonly use a dataSource.xml file of some description to hold the XML stanzas describing the connection details to various databases or schemas. When dealing with multiple dataSource requirements you might find that more than one logical dataSource bean name actually points to the same physical connection. Rather than define multiple datasource stanzas with exactly the same details, Spring allows the use of the element to point easily to an existing bean but use a different name: <bean id="personDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@database:port:SID" /> <property name="username" value="USER" /> <property name="password" value="PASS" />

Using & comparing enumerations (enums) with JSTL

Often in your JSTL pages you will want to test a value of a particular variable before displaying something on the page. Often you are comparing against primitive types or other objects but what if you want to compare against an enumerated type ? Attempting to access the enumeration directly as Colour.BLUE doesn't work as the class/enum isn't available but what you can do it compare objects against their label or enum name. If we have a Colour enumeration: public enum Colour { RED, GREEN, BLUE } and we have a car object which has a getColour() method on it (returning the enumerated type) we can test against it in JSTL by using the specific name: <c:if test="${car.colour eq 'BLUE'}">

How to use MatchMode in your JPA/Hibernate Restrictions & Criteria queries

Back in July I blogged about how to do AND/OR type SQL queries using Hibernate AND/OR JPA using disjunctions . If you looked at the example code you will have seen that I was appending "%" as the wildcard operator in my Restrictions . Since then I've used Restrictions a couple more times and wondered if there was a better way of specifying them other than string concatenation. Well there is and it's with the use of the MatchMode class. Rather than this code: import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; Criteria criteria = session.createCriteria(Product.class); criteria.add( Restrictions.disjunction() .add(Restrictions.ilike("code", codeOrName + "%")) .add(Restrictions.ilike("name", "%" + codeOrName + "%")) ); return criteria.list(); You can now write: import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.crite

Accessing & iterating over a Java Map in a JSP page with JSTL

When you are coding JSP pages using JSTL one thing you use a lot is the <c:foreach> tag . This tag a great for iterating over Lists or Sets but what do you do when you want to display the contents of a Map ? Firstly you need to decide how you are going to use the Map. Do you want to access a 'value' stored within the Map based on a known key or iterate over the Map displaying both key and value? Access a Map based on a 'key' This one is pretty straight forward you just need to know the JSTL syntax: ${aMapFullOfKeysAndValues[yourKnownKey]} Two key points: The key is an existing JSTL variable or a quoted string You use square brackets at the end of the Map name Iterate over a Map pulling out the 'key' & 'value' This is a little more complex, note the name of the variable that is filled on each pass through the Map ('entry'): ${entry.key} - ${entry.value} Four key points: The name of the Map is placed as the 'i

Spring Autowiring & Component Scanning Problems - Part 6: The Remedy

Part 5 can be found here So what can you do about root context beans not being wired correctly? One solution is to ensure that all your root context beans have their autowiring specified via XML, either with explicit elements or autowire="byType" or autowire="byName" XML attributes, but this is a bit of a backward step considering how annotation centric Spring is becoming. You could enable component scanning (via the XML element) and go through the beans marking them with the @Component family of annotations so that the @Autowired statements are picked up. You will also need to remove the XML-based bean definitions from the context files otherwise you will end up with two conflicting beans - one loaded due to the XML declaration and another loaded due to component scanning. Or you could switch on 'annotation awareness' by adding a XML element to your root application context files. In fact you only need to add it to one of the root context fil

Spring Autowiring & Component Scanning Problems - Part 5: The Cause

Part 4 can be found here It's not clearly stated in the Spring documentation but the auto-wiring stage for DispatcherServlets only scan through the beans within it's specific application context searching for autowiring annotations (@Autowired, @Qualifier, etc.), it does not venture into the root application context to wire those beans. It sometimes appears that it does cross that root context boundary if you have root bean classes annotated with one of the @Component family and you enable your web application's component scanning to include that package. What happens is that the bean is loaded into the root application context and then an overwritten version is loaded into the WebApplicationContext . This overlaid version is then auto-wired as it lives inside the WebApplicationContext . Part 6 can be found here

Spring Autowiring & Component Scanning Problems - Part 4: Application Contexts

Part 3 can be found here Spring loads beans into application contexts. Any beans declared in XML files or any annotated classes found via component scanning are placed into a suitable application context - either the root application context or one specific to the web application that the bean is declared in. Any beans declared (or scanned for) which are not DispatcherServlet related (i.e. not -servlet.xml files) are placed into one big root application context bucket, the support for separate XML application context files is purely a convenience for you to manage the logical separation of the beans. Each DispatcherServlet gets it's own WebApplicationContext which inherits all the beans from the root application context, overlaying all the beans defined within it's web application scope (i.e. any beans within -servlet.xml) . Once all the DispatcherServlet's beans are loaded it will attempt to autowire them together and this is where the potential problems start. Par

Spring Autowiring & Component Scanning Problems - Part 3: Autowiring

Part 2 can be found here Having a load of beans instantiated in an application context is one thing, having them wired together so that they know about each other is another. Wiring can be done either using XML or via the @Autowired annotation . The annotations on their own don't cause Spring to wire the beans, you need to turn on annotation support for Spring to find them: <context:annotation-config/> When added to an application context XML file it instructs Spring to look through all the loaded beans in the relevant application context for annotations like @Autowired, @Qualifier & @Required. In a reasonably mature Spring application you could have the beans being wired together in a number of ways: Explicit <property> XML elements referencing other beans The addition of autowire="byType" or autowire="byName" XML attributes @Autowired annotations inside normal classes declared as beans in XML @Autowired annotations inside @Component

Spring Autowiring & Component Scanning Problems - Part 2: Component Scanning

Part 1 can be found here Instead of adding explicit beans to your XML files, Spring 2.5 introduced the @Component annotation family ( @Service , @Controller , @Repository – all children of the @Component parent annotation). Simply add these object-level annotations to your class definitions to mark what type of Spring bean they are. Then add the following XML snippet to the application context XML file to tell Spring where to look: <context:component-scan base-package="com.andrewbeacock"/> Spring now scans through the whole classpath for the specified package (and sub-packages) looking for @Component-based classes. Any found are created as beans and placed in the application context. This purely adds the beans to the relevant application context, it doesn't look inside the class for other annotations until it's finished loading all the remaining beans into the context. Part 3 can be found here

Spring Autowiring & Component Scanning Problems - Part 1: The Problem

Let's set the scene a little: You're a developer on a long-running Spring -based web application. It's a reasonably large application developed before annotations were a twinkle in Spring's eye and so uses XML to declare the beans and wiring. Over time the use of annotations has grown - particularly in the area of annotated controllers - and you've started to add @Autowired annotations rather than explicitly defining the wiring in the XML application context files. So now you've got a good mix of XML-defined beans and annotated ones, sometimes mixing the two together; a bean is declared in the XML context file but it's wirings are defined using @Autowired statements rather than the usual XML elements. Everything is working perfectly... You've never had a problem adding @Autowired annotations to beans until now, but a particular bean's members don't seem to get wired (you get a NullPointerException at runtime) but you don't get a wi

Something new for my blog

I'm going to try something new, a multi-post feature which is basically an article I've written for an open source journal but broken up into bite-sized pieces and posted over a couple of weeks (or so). Please comment if you like it, find it annoying, my content is completely wrong, etc. I'd like to hear from you. My series is on "Spring Autowiring & Component Scanning Problems"

How to do AND/OR type SQL queries using Hibernate AND/OR JPA using disjunctions

If you have been using Hibernate or JPA for a while you will know that the Criteria and Restrictions classes are very handy for querying the database without writing any SQL code and without worrying about the real column names (these are all captured in the annotations that you have applied to the domain objects). This is fine when you want to search for objects (rows) which are a combination of columns such as forename = "Andrew" AND surname = "Beacock" but what if you want to search for all people who either have a forename of Andrew and/or a surname of Beacock? This is where a " disjunction " comes in. This is one of the types hanging off the Restrictions class and deals with AND/OR situations. The code below is looking through the 'products' table for any product that has a code or name starting with the text supplied: import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; Criteri

jQuery tip: Selecting ids with periods in them (dots/'.')

I was messing around with jQuery today combined with a Spring form-backed bean and was finding that my jQuery was failing to work. The id of the input field bound to my Spring form was person.id . Trying to get the value entered into the input box was failing, this is what I was trying: $('#person.id').val(); The problem here is the period - '.' - jQuery see these as CSS notation and so fails to find an element with that id, what you need to do is add two backslashes ('\\') before the period to escape it, like this: $('#person\\.id').val(); See the jQuery FAQ for more details. Technorati Tags: jQuery , Spring , Andrew Beacock

Great tip regarding annotated Spring form validation & BindingResult

Found an interesting little gotcha at work last week, I was adding form validation to an annotated Spring controller , creating a custom Validator to do the work and wiring it in to the controller's method signature with the use of the BindingResult parameter (I just tacked it on the end of my existing parameters): @RequestMapping(method=RequestMethod.POST, params="action=person") public String createPerson(@ModelAttribute("person") PersonForm person, ModelMap model, BindingResult result) { // code goes here... } This resulted in a slightly odd error message: java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature! I was a little confused by this message, it was indicating that I didn't have the form's model attribute declared before the BindingResult but I certainly have. After some google searching for this error message I found a website created by a coll

Summary of March's Manchester Open Source Central User Group Meeting

I really enjoyed last night's Open Source Central user group meeting in Manchester. Both speakers were excellent and there were a lot of good ideas to take away.  Here is my summary of the evening: "Spring BlazeDS Integration" by Rick Evans He started with an overview of why build web applications with Flex & Flash : rich internet applications which look like a desktop application rather than a bunch of web pages. He then suggested that Flex & Flash applications client applications could be powered by a Spring server backend by using BlazeDS . Flex is a framework for building rich internet applications. You get the same looking application regardless of operating system or browser which can't be said for regular web-based applications. Flex applications can be deployed into the standard flash player embedded in the browser or as a desktop application via Adobe AIR.  You write Flex applications in ActionScript which is an OO language enabling a simpl