Spring, Hibernate and leaky abstractions

By Confusion on Friday 20 February 2009 22:33 - Comments (3)
Categories: Java, Software engineering, Views: 6.482

The advantage of using frameworks/libraries like Spring and Hibernate is supposed to be that they take care of the nasty details and that you only need to think about what you wish to do on a much higher level. However, abstractions are always leaky and when you run into a problem, you still need to understand about the nitty-gritty details.

This week, I ran into the following problem: my Spring/Hibernate based application locked up. It was reproducible and seemed to depend on the number of queries that had taken place. So I started Tomcat with
-Xrunjdwp:transport=dt_socket,address=8000

told Eclipse to connect to that socket (debug remote application) and suspended operation after the application frooze. The result was clear: no more connections in the connection pool and an infinite wait until one would be available.

Now this application is reasonably old and has worked succesfully for quite a while. Everything seemed to be in order, until, after looking at the Javadoc of the HibernateDaoSupport class for the umpteenth time, it suddenly hit me: the latest DAO used getSession() instead of getSessionFactory().getCurrentSession() to obtain a session. While the first could very well be a shorthand for the latter, it most certainly isn't. I noticed the difference when I reviewed the differences when updating from Subversion and read the appropriate Javadoc, but I wasn't paying enough attention to realise that the difference between these ways of obtaining a Hibernate session was a nitty-gritty detail that was very important.

Using grails on an existing database

By Confusion on Thursday 12 February 2009 22:12 - Comments (3)
Categories: Java, Software engineering, Views: 18.609

I've encountered the following problem several times: I needed to inspect or alter data in a database, but there is no interface to this data. Todays problem was that I needed to edit some html in a SQL server database, but the so called 'Enterprise Manager' did not display these fields, complaining about the 'grid buffer size'. Of course it turned out to be impossible to find out how to increase that value and using the Query Manager to edit large text fields isn't very convenient either.

Now I could write some custom Java to perform the specific actions that were required, but I would be hard pressed to provide full CRUD capabilities within a reasonable period of time and I certainly wouldn't have a GUI. After searching a bit for frameworks to generate CRUD with editing controls for an existing database, I decided to give grails, a Ruby on Rails type framework based on the JVM language Groovy, a go.

Now firstly, it is important to realize that such frameworks are usually bent on specifying a domain model, which is then used to generate the database. When used with an existing database the generator code will often try to modify your database. In case of grails, by adding an 'id' and 'version' column. If you generate the skeleton for a grails application (see the quick start, there will be a database configuration file in grails-app/conf/DataSource.groovy. When you modify this file to add your configuration, be sure to comment the lines saying

Groovy:
1
dbCreate = "update" // or "create" or ...



The order of operation is as follows: create domain objects, generate default views and controllers and modify them appropriately. There is a tool called GRAG that can help you to reverse engineer your domain objects from your database and although it produced some odd results in my case, it will certainly help you on your way. A domain object may look like this:

Groovy:
1
2
3
4
5
6
7
8
class Email {
    static mapping = {
         table 'emails'
         id column:'email_id'
         version false
    }
    String content
}


The 'mapping' element is required because I'm not following the defaults: if the table was called 'email', the id column was called 'id' and the table would have a 'version' column, it would not have been necessary.

After having created domain objects, you need to run
grails generate-all Email

to generate a controller and a view. Follow with
grails run-app

and you've got a CRUD application running for this table and its two fields.

Of course, you'll often need a bit more than this, but for instance changing the input element for the html field to a large enough textarea and adding some functionality to properly (un)escape html was easy.

Is there more bad PHP than bad Java?

By Confusion on Sunday 8 February 2009 11:34 - Comments (7)
Categories: Java, Software engineering, Views: 4.346

Bad code is code that invites future bugs due to being incomprehensible or fragile. Although this is mostly the result of a lack of forethought and design, I think that in some programming languages it is much easier to write such code than in others.

I think there are three main reasons why a language may be more bad-code-prone than others: lacking namespaces, using dynamic typing and providing functional programming possibilities. Now I am not argueing that it is an inherent feature of such languages that they result in bad code. Rather, I think that these languages provide more, and easier, ways to shoot oneself in the foot. Dynamic typing and functional programming provide easy ways to circumvent the restrictions imposed by a proper design, while the lack of proper namespaces does not allow you to implement a proper design at all.

As a result, I think it requires more skill and thought to write good code in languages like PHP and Javascript then it does in a statically typed, 'restricted', language like Java. However, these are precisely the languages that less skilled programmers use more often, because they seem simpler. Consequently, there is necessarily more bad PHP than there is bad Java.

Ultrashort JAXB tutorial

By Confusion on Tuesday 3 February 2009 20:49 - Comments (3)
Categories: Java, Software engineering, XML, Views: 7.266

Today I had to use JAXB for XML-object binding. While searching for an introduction, I noted that most articles handling JAXB seemed to be overly long and concerned with all kinds of asides that detracted from the basics, which were all I needed. Therefore I now present: an ultrashort JAXB tutorial.

I will expect you know:
  • What XML-object binding is and why you would want to use it.
  • How to use Java and solve classpath issues and such
  • How to use Linux (or translate the instructions to Windows).
  • How to determine intermediate steps I left out (like 'extract the zip')
Requirements:
  • An XML file that you wish to 'unmarshal' into an object tree. Example:
    XML:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    <?xml version="1.0" encoding="UTF-8"?>
    <rootElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://some.sensible.url/foo"
        xsi:schemaLocation="http://some.sensible.url/foo foo.xsd">
    
        <subElement>
            <foo>1</foo>
            <baz>2</baz>
        </subElement>
        <subElement>
            <foo>2</foo>
            <baz>4</baz>
        </subElement>
        
    </rootElement>

  • An XML Schema description of the structure of the XML. Example:

    XML:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    <?xml version="1.0" encoding="UTF-8"?>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" 
        targetNamespace="http://some.sensible.url/foo" 
        xmlns:f="http://some.sensible.url/foo" 
        elementFormDefault="qualified">
    
        <element name="rootElement">
            <complexType>
                <sequence>
                    <element name="subElement" type="f:subElement"
     maxOccurs="unbounded" />
                </sequence>
            </complexType>
        </element>
        
        <complexType name="subElement">
            <sequence>
                <element name="foo" type="int" />
                <element name="baz" type="int" />
            </sequence>
        </complexType>
    </schema>

Tutorial
  1. Use a Java 6 SDK (which has JAXB) or download JAXB (and use a Java 5+ JDK)
  2. Generate the objects from the xml schema by issuing
    jaxb-ri/bin/xjc.sh -p com.company.app.pakkage.of.objects \
    -d /path/to/com/company/app/pakkage/of/objects \
    /path/to/xml-structure.xsd
  3. Assuming the root element of your xml is named 'rootElement' (and available as com.company.app.pakkage.of.objects.RootElement):

    Java:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    package com.company.app;
    
    import java.io.File;
    import javax.xml.bind.*;
    import com.company.app.pakkage.of.objects.*;
    
    public class Example {
    
        public static void main(String[] args) throws JAXBException {
            
            final JAXBContext jaxbContext =
                JAXBContext.newInstance("com.company.app.pakkage.of.objects");
            final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            final RootElement rootElement =
                (RootElement) unmarshaller.unmarshal(new File("/path/to/xml.xml"));
        }
    }

  4. Profit.

Using vim to edit remote files

By Confusion on Tuesday 20 January 2009 07:22 - Comments (7)
Category: Software engineering, Views: 5.365

As I know there are many editors out there that can edit remote files, I figured I'd find out whether my favorite editor supported that feature. Of course it did :). Just use
ftp://user@server/path/to/file

to locate the file, enter the password and happily edit away. Every :w will upload the file anew. This also works with at least scp:// , so there's no need to install an ftp server.

One small inconvenience is the fact that if you're NATed behind a firewall, you need to use ftp PASV mode, which is not the default setting for many ftp clients. However, Google brought an easy solution: add
let g:netrw_ftp_cmd="ftp -p"

to your ~/.vimrc. This latest tip thanks to: http://alecthegeek.wordpr...etrw-in-ftp-passive-mode/

edit:
Note that the above indicates a relative path on the server. If you want an absolute path, you need to add an extra /: ftp://user@server//absolute/path/to/file