Skip to main content

Posts

Lancashire Tech Talks #7 - Behaviour Driven Development, AI For Ordinary Folk & The Mobile Is Dead

At 6pm on Thursday evening I attended the seventh Lancashire Tech Talks (@LancsTechTalks) based at Graham & Brown in Blackburn. It was a tech meetup entitled "Behaviour Driven Development, AI For Ordinary Folk & The Mobile Is Dead" with three guest speakers and they also provided food and drinks.
Graham & Brown have a great conference room big enough to seat over a hundred people and there were not many empty seats once the talks had started. The room is nicely decorated (not surprising really considering Graham & Brown are a wallpaper and wall-covering company) but the room was also light and airy.
When I arrived there was a good buzz in the room with people conversing in small groups, and the organisers and speakers setting up. Cold soft drinks and beers were provided and what I particularly liked was that recycling of the cans and bottles was being encouraged.

The evening started with the organisers introducing themselves and plotting out the course of the…
Recent posts

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(location…

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 XML of …

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 examples:

Beware of JavaScript's parseInt function - 010 does not equal 10...

I use JavaScript & jQuery quite a bit in my day job helping to add a bit of 'shiny' to our web applications. One feature that I added recently kept a track of the percentages that you had typed in the form.  It told you at the bottom of the page how much percentage you had left - I used JavaScript's parseInt function to help me in this respect.

As the application passed through system test it was found that if you typed '020' as a percentage my application said that you had 84% left to assign rather than the expected 80% - any ideas what's going on?

Yes that's right - the leading zero was causing parseInt to treat the number as an octal (base 8) number and so 020 was two lots of 8 = 16. It appears that this octal recognition is being deprecated but who knows when it will actually go so for now I've had to add ", 10" (i.e. a decimal radix) to the end of all of my parseInt calls:
parseInt(percentage, 10); Double check any code that you use wh…

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 property 'obj…

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 sized chun…

Always note DNS server settings offline

Had a strange experience this evening - complete loss of the internet. My router was suggesting that I had ASDL connectivity, and even an IP address but I wasn't able to load any websites. After a bit of debugging with the help of a remote friend I figured out that I wasn't able to connect to my OpenDNS name servers and so google.com wasn't resolving for me.

I updated my router with Google's DNS settings and was back in play - just goes to show that what appears to be an ISP outage can be a case of name servers not being available at that time.

Make sure you make a note of a few free DNS server details (i.e. both OpenDNS and GoogleDNS) offline so you can try them out if you ever end up 'offline'!

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'}">

Keyboard shortcut for 'paste as plain text' in Pidgin

I use Pidgin at work for communicating with my remote colleagues and I regularly paste code snippets and log file output into the Pidgin window. Often the text formats completely wrong and you end up sending the recipient a page of garbage rather than the real text.

Pidgin has a right-click context menu option for getting round this called 'paste as plain text' which normally does the trick but what if you normally use CTRL-V to paste your text in? After 2 seconds of experimentation today I found that CTRL-SHIFT-V is the keyboard shortcut for 'paste as plain text', I now feel complete...

Embedding a Google Docs spreadsheet in Blogger

Blogger is an excellent free blogging platform but if you want anything 'dynamic' then it starts to get in the way. One thought I've had recently was to see how I could share information captured in Google Docs Spreadsheet with Blogger.

I've a few ideas which will take a few posts to explain, so let's start with the most basic - embedding a Google Spreadsheet direct into Blogger.

Access the spreadsheet in Google Docs that you want to expose in Blogger, I've chosen a simple table of the most popular programming languages in 2010:


Next you'll want to share this spreadsheet with the rest of the world by publishing it as a web page:


Now you need to select the "HTML to embed in a page" option and copy the HTML code into the clipboard:

 Open a new post in blogger and ensure that the "Edit HTML" tab is selected and paste the code in:


Now publish your post and your spreadsheet will be visable in your blog post:



I didn't say it would be pretty…

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.criterion.Restricti…

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 nameIterate 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 'items' attribute of th…

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 files as all…

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.
Part 5 can be…

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 beansThe addition of autowire="byType" or autowire="byName" XML attributes@Autowired annotations inside normal classes declared as beans in XML@Autowired annotations inside @Component-based classesN…

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