Search This Blog

Loading...

Saturday, February 8, 2014

IntelliJ: the power of structural search and replace

Sometimes you run into a situation where you want to refactor some code but cannot use the regular refactorings. For example, take the following code:

jQuery("body").on("change", "#fontSelector", "change", function () {
    var selectedFont = jQuery("#fontSelector").val();
    layoutDesigner.selectFont(selectedFont);
});

I wanted to replace the above code with the following:

jQuery("#fontSelector").off("change");
jQuery("#fontSelector").on("change", function () {
    var selectedFont = jQuery("#fontSelector").val();
    layoutDesigner.selectFont(selectedFont);
});

Sure, I could rewrite this manually. But this takes a long time with dozens of such event handling constructs, all with different selectors, events and functions. Structural search and replace to the rescue.

But instead of writing how you could do this with structural search and replace, I recorded a little screencast which demonstrates the concept. The video can be found here: https://www.youtube.com/watch?v=Jb-YNgDClKg

Tuesday, January 28, 2014

Android: location based services

Introduction

Developing applications for mobile devices gives us a lot more opportunities for context based information than a traditional web application. One of the inputs for context sensitive information is the users current location. This post describes several ways an Android application can obtain the users current location.

Location API's

In previous versions of the Android SDK you had to manually implement a location service which abstracts away the underlying location providers (GPS or cellular based). This was not ideal since as a developer of an application, you probably are not concerned about the implementation details of obtaining a users location.

Fortunately Google's Location API's provide a much better way for working with location data. The Location API's provide the following functionality:
  • Fused location provider which abstracts away the underlying location providers.
  • Geofencing. Lets your application setup geographic boundaries around specific locations and then receive notifications when the user enters or leaves those areas.
  • Activity recognition. Is the user walking or in a car.

Check for Google play services

Working with the Location API's require the presence of the Google Play Services application on the device. It is good practice to test for the presence of Google play services before using the API. This can be done with the following code:

protected boolean testPlayServices() {
        int checkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
            // google play services is missing!!!!
            /*
             * Returns status code indicating whether there was an error.
             * Can be one of following in ConnectionResult: SUCCESS, SERVICE_MISSING,
             * SERVICE_VERSION_UPDATE_REQUIRED, SERVICE_DISABLED, SERVICE_INVALID.
             */
            GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices, getActivity(), 1122).show();
            return false;
        }
        return true;
    }
Code listing 1

Code listing 1 shows how to check for the presence of Google play services. If the Google play services are not present a dialog is displayed giving the user the opportunity to download and install the Google play services application. This method returns false if the services are not found and can be placed around any code requiring Play services.

Obtaining the users location

The primary class for using the Location API's is the LocationClient. The first thing to do is instantiating the LocationClient and passing the required listeners. See the following code which is usually called from the onCreate from within an activity or onActivityCreated if the LocationClient is instantiated within a fragment.

locationClient = new LocationClient(getActivity(), this, this);

The parameters are:

  1. The Context
  2. ConnectionCallbacks. Defines the onConnected() and onDisconnected() methods.
  3. OnConnectionFailedListener. Defines the onConnectionFailed() method.
When the LocationClient is instantiated, the next thing to do is calling the connect() method of the LocationClient. This is typically done in the onResume method. In the inPause method the disconnect() method is called of the LocationClient. This ensures the LocationClient is only active when the activity is running. Should you need constant tracking of the users location when the app is in the background, it is better to create a background service for this.

When the connect() method is successful, the onConnected() callback is called. In this method you can obtain the users last known location using the following method:

locationClient.getLasLocation();

Periodic location updates

Registering for periodic location updates involves slightly more work. The first thing to do is creating a new LocationRequest object. This object specifies the quality of service for receiving location updates. The following code demonstrates this:

private static LocationRequest createLocationRequest() {
        final LocationRequest locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // The rate at which the application actively requests location updates.
        locationRequest.setInterval(60 * MILLISECONDS_IN_SECOND);
        // The fastest rate at which the application receives location updates, for example when another
        // application has requested a location update, this application also receives that event.
        locationRequest.setFastestInterval(10 * MILLISECONDS_IN_SECOND);
        return locationRequest;
    }

After the LocationRequest is created and the connect() method of the LocationClient is successful, the onConnected method is called. In this method the LocationClient is instructed to send periodic location updates to the application using the following code:

locationClient.requestLocationUpdates(locationRequest, this);

The parameters are:

  • locationRequest. Specifies the quality of services of the location updates.
  • LocationListener. Defines several callback methods including the onLocationChanged which is called when a new location is available.
Required dependencies

To use the Google play services in your application you have to define the correct dependencies in the build.gradle. There are two versions of the API: one for Android 2.3. and higher and one for Android 2.2.

Use the SDK manager to install the required packages. For Android 2.3 these are:

  • Google play services
  • Google repository
For Android 2.2 these are:
  • Google play services for Froyo
  • Google repository

So if your applications targets Android 2.2 you must use the Google play services for Froyo library. In your build.gradle specify the following dependency:

For Android 2.3:

dependencies {
    compile 'com.google.android.gms:play-services:4.0.30'
}

For Android 2.2:

dependencies {
    compile 'com.google.android.gms:play-services:3.2.65'
}

Testing with mock locations

To test with mock locations you have to do the following:


  1. Enable mock locations in the developer options.
  2. Download the sample LocationProvider example app: http://developer.android.com/training/location/location-testing.html
  3. Modify the LocationUtils class with an array of locations you want to test with.
  4. Install the LocationProvider sample app on your device.
  5. Start the LocationProvider sample app.
  6. Start the application you want to test the location functionality for.

A handy website to get the latitude and longitude of an address for testing purposes is: http://www.itouchmap.com/latlong.html

Conclusion

Working with location data in your mobile application can add a new dimension to the user experience. This article explains the steps needed to use the Google Location API's for obtaining the users current location.

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.