Search This Blog

Friday, September 20, 2013

MyBatis: mapping a map

As some of you will know I am a huge fan of MyBatis. I have used it in a lot of projects and it never failed me. I like how you are in control of the SQL and the flexibility this brings by mapping result sets to classes instead of mapping tables to classes.

Recently I wanted to map some columns from a table to actual typed properties of an object, and some columns to a property of type Map within that same object. Consider the following class:

public class Person {
    private String firstName;
    private String lastName;

    private Map dynamicProperties;

    // Getters and setters omitted.
}

and the following query:

select firstname, lastname, pref_1, pref_2, pref_3 from person;

The following resultmap maps the result of the query to the Person class:

<resultMap id="personDynamicProperties" type="map">
        <result column="pref_1" property="pref_1"/>
        <result column="pref_2" property="pref_2"/>
        <result column="pref_3" property="pref_3"/>
    </resultMap>

    <resultMap id="personResult" type="Person">
        <result column="firstname" property="firstName"/>
        <result column="lastname" property="lastName"/>
        <association property="dynamicProperties" resultMap="personDynamicProperties"/>
    </resultMap>

Friday, July 12, 2013

Java 7 try-with-resources

Java 7 provides better resource management for resources that need to be closed when finished working with, for example files, streams, database connection and sockets. This language construct is called the try-with-resources statement. The mechanism that makes this work is called the AutoCloseable interface. The Java 7 resource classes all implement this interface. The signature of this interface looks like this:

public interface AutoCloseable {
    void close() throws Exception;
}

It declares one method, close(), which is automatically invoked on objects managed by the try-with-resources statement.

Although Java 7 resource classes implement this interface, a lot of time the libraries you use do not because the library is not updated to use the AutoCloseable interface or the project cannot simply update to a newer version.

Most of the time this is easy to solve. Just subclass the resource that should be able to participate in the try-with-resources statement. Take the ITextRenderer (form the Flying Saucer project) as an example. When finished working with the ITextRenderer, the finishPDF() method should be called. Normally you would do that in a finally block. By creating a new class extending from ITextRenderer and implementing the AutoCloseable interface this class can participate in automatic resource management. The AutoCloseableITextRenderer looks like this:

public class AutoCloseableITextRenderer extends ITextRenderer implements AutoCloseable {
    @Override
    public void close() {
        super.finishPDF();
    }
}

Extending the original class makes the most sense since the subclass is an ITextRenderer. You would use composition if the class cannot be extended because it is final.

And this is how you would use it:

try (final AutoCloseableITextRenderer iTextRenderer = new AutoCloseableITextRenderer()) {
            ByteArrayOutputStream out; // contains the data to be converted to PDF, not shown here.

            iTextRenderer.setDocumentFromString(new String(out.toByteArray()));
            iTextRenderer.layout();
            iTextRenderer.createPDF(pdfOutputStream);
            pdfOutputStream.flush();
        }

Thats all. Please note that I did not throw an exception from the close() method in the AutoCloseableITextRenderer. The Javadoc of the AutoCloseable interface says the following about this:
While this interface method is declared to throw {@code Exception}, implementers are strongly encouraged to declare concrete implementations of the {@code close} method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.

Thursday, June 20, 2013

Height problem when rendering an ExtJs 4 application in a custom div

This post is verified with Ext Js version 4.

ExtJs applications can be run in the whole browser window or in a small part of a larger application, for example in a div. You may want to render an ExtJs application in a div if you have a common HTML structure with navigation capabilities outside the ExtJs application. To render an ExtJs application to a div do the following:

  • create an HTML which contains the div where the application is rendered
  • Create an app.js file which is the actual ExtJs application. 
Below is an example of an index.html with a div named appContent where the ExtJs application is rendered to:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Sample app</title>
    <script type="text/javascript" src="extjs/ext-debug.js"></script>
    <script type="text/javascript" src="extjs/ext-theme-neptune.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id="appContent" class="app-content">

</div>
</body>
</html>

And here is an example of app.js which renders the application to a div:

Ext.application({
    name: "SampleApp",
    launch: function () {
        Ext.create("Ext.panel.Panel", {
            renderTo: Ext.getElementById("appContent"),
            autoCreateViewPort: false,
            layout: {
                type: "hbox",
                align: "stretch"
            },
            id: "appContainer",
            listeners: {
                beforerender: function () {
                    Ext.getCmp("appContainer").setHeight(Ext.get("appContent").getHeight());
                    Ext.getCmp("appContainer").doLayout();

                    Ext.EventManager.onWindowResize(function () {
                        Ext.getCmp("appContainer").setHeight(Ext.get("appContent").getHeight());
                        Ext.getCmp("appContainer").doLayout();
                    });
                }
            },
            items: [
                {
                    xtype: "label",
                    text: "Sample App",
                    flex: 1
                }
            ]
        });
    }
});

Please notice the listeners section. What I noticed was that with some layouts (for example the hbox, vbox and borderlayout) the application did not occupy the whole size of the div. When I rendered the same application using a viewport the application size was a large as the browser window.

The beforerender listener fixes this issue. It basically sets the height of the application container to the height of the div and calls doLayout to update the view. This same logic is also added to the onWindowResize event to adjust the size of the application when the browser window is resized. This fixed the problem for me.

Saturday, March 23, 2013

How to: web service mock with SoapUI

Introduction

A lot of organizations use web services (WSDL) for system integration. Often those services are developed alongside the application that uses those services. Instead of waiting for those services to be developed, the application which consumes the web service can develop a mock implementation of the service to test against.

Several strategies

There are several strategies for developing mock services from a WSDL. One of these strategies is using SoapUI. SoapUI is able to consume the WSDL and generate a mock service from it. After the mock service is created, the application in question can consume this mock service and start using it.

The advantage of mocking this way, is that the application makes a full HTTP network round-trip when calling the respective service. All relevant components within the application (WSDL client, parsing the response message) are covered.

Instead of describing how to mock a web service using SoapUI, I created a small screencast demonstrating this. The screencast can be found here: Web service mocks with SoapUI

I think this screencast is more clear and easier to follow than written text. To be effective I keep my screencasts shorter than 5 minutes. Descriptive subtitles are also included. Please let me know if you like this format.

Final thoughts

Besides speeding up development, mocks/stubs may also be used to put the system in a known state which enables automatic integration testing.



Wednesday, March 13, 2013

Reasons for IntelliJ

Introduction

I often get the question why I use Intellij in favor of another IDE, in this case Eclipse. Most of the time I answer that question by demonstrating some features of IntelliJ and showing how integrated everything is. This got me thinking about what are the actual reasons that I use it. This post will try to make that clear and help others decide if the switch is worth it or not.

Some background

I had been a long time Eclipse (7+ years) user before I made the jump to IntelliJ. Before Eclipse, I worked with Rational Application Developer, WSAD, JBuilder and Visual Age for Java. Compared to these IDE's, Eclipse was a joy to use. I could, for example, generate getters and setters, which was not possible in one of the older IDE's (we are talking about more than 10 years ago). Although I quite liked Eclipse I always thought there were some deficiencies. Mainly in the following areas:
  • Why was there no core functionality bundled with the standalone Eclipse variant? For example Subversion and Maven integration.
  • Why was it always painful to setup an Eclipse version to your liking with all the required plugins? With every new version I spent always nearly half a day setting up my IDE. This is unacceptable I think. The more plugins and functionality the harder it got.
  • Updating to a new version was sometimes painful. Plugins that stopped working for example.
  • I never quite liked the concept of a workspace. I already organize my projects on disk so I do not need a workspace concept.
  • I did not like the idea of different perspectives. Why do I have to think about the context I am working in? For example: working with Java and Flex in one project. When I am in the Flex perspective my Java code completion/refactoring did work in Java files. Context should be file or even fragment driven.
Please note that the above are personal opinions and may vary between users. Despite of this I was quite productive in Eclipse and liked the performance of it. Also note that these observations are from a couple of versions back. Things may have changed.
Around 2007/2008, a colleague of mine introduced me to Intellij, I think it was version 7 back then. My first reaction was I don't need another IDE. He showed me some features, like code inspections, and I said I would give it a try. My main obstacle back then was the price. That year I also gave a talk at the Dutch Java User group conference. Every speaker received a free IntelliJ license from JetBrains. I then decided I would give it a try. After the first two or three days I thought I would give up. I had to learn all new key-bindings and I was less productive. I persisted and after a week or so I begun seeing the benefits of it. After version 7 I upgraded to 8, 9 without any problem. Things could be different. At the moment I work with the latest version, 12.1 EAP. Below are some of my reasons why I do most (if not all) of my development work in IntelliJ.

Major features
  • It is an integrated solution. I do a lot of different development work with a lot of different technologies, for example: Java, HTML/CSS/JavaScript, Android, Grails/Groovy, Flex, Subversion, Git, Maven, Ant etc. This is all possible with IntelliJ out-of-the box. There is no need to install separate plugins, which saves me a huge amount of setup time. Just download and install it and you're good to go.
  • The editor itself. I invest heavily in knowing all the shortcuts. By knowing all the shortcuts I can code very fast. The instant code completion (not having to hit Ctlr-space all the time) is a joy to work with. Just type a couple of characters and hit Tab to complete the code. When I generate code, the cursor almost always is in the correct position to begin typing again. No need to touch the mouse or whatever.
  • Code inspections and analysis tooling build in. I find it important to keep my code clean and bug free. The build in inspections and the ability to auto solve them are a really nice addition. Besides this you also have a dependency matrix viewer to get a quick overview of the dependency structure of your application and a duplicate code checker.
  • Live templates. Live templates greatly increase coding speed. To make the most of it, I highly recommend creating your own templates. This is very easy. Just select a piece of code and select Save as Live template from the Tools menu. Press Ctrl/Cmd+J to view the live templates.
  • Maven/Gradle integration out of the box. Just import a Maven project and Intellij knows the modules, dependencies etc. You can easily generate a dependency diagram from the Maven pom file to view all the dependencies at a glance. See figure 1 for an example of the Maven dependency viewer.
  • Some handy tools. I often use the database editor and the RESTful web service test utility. The database editor has code completion in SQL and table creation. With the RESTful web service tester you can easily test HTTP services. The response can then me immediately saved and formatted as JSON or XML.
  • Powerful refactorings and structural search & replace. IntelliJ knows a lot about my code. For example in Android: when I rename an image in the values/hdpi folder, it also renames the corresponding images in the mdi and xhdpi folder but also updates my XML views and code references to that image.
  • Tasks and Contexts. I use IntelliJ in combination with YouTrack (there are more issue trackers that IntelliJ can integrate with). It is really easy to start working on an issue. IntelliJ creates a new context that tracks the files that belongs to that specific issue. I can mark the issue in progress and when I commit my changes it takes the comments from the context and uses this as the commit comments. It also changes the status of the issue to resolved when done working on the issue. All from within the IDE itself, no need for context switching.
Figure 1: Maven dependency viewer

Smaller features

And then there are the smaller but just as important features which increase my productivity:
  • Stacked clipboard. You can have multiple entries in your clipboard. Just hit Ctrl-Shift-V to show the clipboard stack.
  • Column mode in the editor. This comes in handy when working with fixed structure files like CSV for example.
  • Darcula theme. This is one of the best dark themes I encountered. A dark theme is especially useful when coding in the evening with the lights dimmed. It is less stressful for the eyes I think. See figure 2 for an example of the Darcula theme.
  • Stack trace analyzer. Just copy a stack trace from the clipboard and IntelliJ analyses it and matches it with the code to easily navigate to the problem at hand.
  • Unit test and coverage integration.
  • And many more.
Figure 2: IntelliJ Darcula theme

Final thoughts

This article describes the reasons why I use IntelliJ as my primary development tool of choice. Please note that this is my personal opinion. Also, this is obviously not an exhausted list. I would like to hear from you why you choose IntelliJ.


Monday, February 11, 2013

Evaluating new frameworks, libraries and technologies

Introduction

New frameworks and libraries are developed so fast it is nearly impossible to evaluate all of them. This can make it hard to judge whether a particular technology is worth investing (time) in. This post gives you some tips which may help when evaluating new technology.

Conceptual level

Although there are many different libraries and frameworks, most of them can be grouped based on some conceptual differentiation. The following concepts may help to give an idea of this conceptual differentiation:

  • Component based frameworks
  • Request/response based frameworks
  • Object Relational Mapping
  • Map-reduce
  • Key-value stores
  • Messaging
  • And many more... 

When evaluating a specific technology it helps to identify to which concept or concepts it belongs. Before further analysis of a particular technology, make sure you understand the concepts. Without this understanding it is almost impossible to do an objective analysis. Understanding these concepts requires an investment in time. Usually in the form of reading, watching presentations, experimenting, training and talking to others. Understanding the concepts will make it easier to objectively evaluate a particular technology.

Simpler is usually better


One of the key actions in evaluating a particular technology is to determine if and how it satisfies the given requirements. A lot of frameworks and libraries provide a 1 minute introduction, a 5 minute guide, a 30 minute tutorial and more. I really like these sorts of introductions since it usually gets you up-to-speed quickly. Besides getting up-to-speed quickly, a more important factor is the complexity of the given solution. I really like the idea of "Make things as simple as possible, but not simpler".

The starter guides, as mentioned above, present the readers with a relatively simple case or problem to demonstrate the key features of a given technology. To find out if a certain technology will fit I suggest to look at the complexity of the solution for the cases in the introduction guides.

In my opinion, if the solution for a relatively simple case or problem is complex and not easy to understand, how can a solution to a more complex problem be easy to understand? This complexity comes of course in various flavours:

  • How much code do I need to write to get even the simplest things done?
  • How many classes do I need to extend? 
  • What and how much configuration should I write?
  • What is the quality of the documentation?
  • How can I easily test my solution?
  • Etc.

If the solution to a simple problem is indeed simple and easy to understand, it is worth investigating more time to find out if the technology satisfies your requirements. If the solution to a simple problem is not simple and not easy to understand, think long and hard before investing more time in it.

Conclusion


New frameworks and libraries are developed so fast it is nearly impossible to evaluate all of them. To speed up the decision process make sure you understand the technology at the conceptual level. Once you understand the conceptual level, experiment with the technology using introduction guides if they are available.

If, from those introduction guides, solutions to a given problem are simple and easy to understand, it may be well worth spending more time investigating the particular technology for more complex problems. If not, proceed with care.

As always, your mileage may vary.