09 February 2011

Working with Android Layouts and ListViews

I've been the owner of an Android phone for about 5 months now. The thought of creating an application for the Android platform has appealed to me ever since. That's why I recently started with Android development as a learning project for the next couple of weeks. In this post I will start sharing my experience with developing Android applications.

Getting started

The basic thing, while starting out with a new technology, is getting to know the fundamentals. There are some great introduction and advanced videos by Google on how to develop applications for the Android platform. The use of proper tooling can also help out a lot on this part. Both Eclipse and IntelliJ has great support for developing Android application since IntelliJ 10 (and it's free to use).

For this project I'm trying to create a native Android client based on the Hippo GoGreen mobile website. If you take a look at the mobile site, there are two main entry points for browsing the site: Products and Events. I started out with Events, where I wanted to create a list of event items and show the event with a nice calendar item on the left next to the title of the event. I wanted the end result to look something like:


In Android you can create a screen/page by creating an Activity. Adding a ListView to an Activity is a matter of configuration. With Android you can define the layout of your View either by defining a piece of XML, or by writing the code in Java. For this example I use the XML notation.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/empty_events"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</FrameLayout>

As you can see the layout contains a ListView and a TextView. You can probably guess what the ListView is for, but I've added the TextView to show a message with 'No events' to the end user if no events are found.
Adding some text to a list item in a ListView is quite simple and there are some good examples available in the Android tutorials. When I got to the point where I needed to add the dynamic calendar, I really had to start digging into layout options. Android has several kinds of default layouts available.

Hovering the text over an image might not be that hard for an experienced Android developer (and there might be other ways than how I solved it), but when you're first introduced to the Android layout system it might be a bit confusing sometimes. My main goal was to show the day of the month and an abbreviation of the month dynamically on top of the calendar image and this is how I did it.

Customizing the list item view


To be able to show a customized list item View we first need to create a snippet of XML that represents the layout of our list item.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_item_event"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    style="@style/ListItem">

    <org.onehippo.gogreen.android.ui.view.SimpleCalendarView
        android:id="@+id/calendar_today"
        android:layout_height="fill_parent"
        android:layout_width="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal|top"
        />

    <TextView
        android:gravity="left"
        android:id="@+id/event_title"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_alignWithParentIfMissing="true"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/calendar_today"
        style="@style/EventTitle" />
</RelativeLayout>

As you can see in the above snippet, I'm using a RelativeLayout for my list item. The nice thing about the RelativeLayout is that you can define the relative position of the TextView versus the SimpleCalendarView. In my case the text is to the right of the calendar item. In the above layout configuration the list item contains two elements: the calendar (which is our custom View component) and a TextView, which will contain the title.

Creating the calendar view


For the dynamic calendar I've created a custom View which will position my 'inner' views in such a way that both TextViews containing the day and month position nicely on top of the ImageView. Now let's take a look at some code.

public class SimpleCalendarView extends FrameLayout {

    private ImageView calendarImageView = null;
    private TextView calendarMonthTextView = null;
    private TextView calendarDayTextView = null;

    public SimpleCalendarView(Context context) {
        super(context);
    }

    public SimpleCalendarView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);

        setUpImageView(context);
        setUpDayView(context);
        setUpMonthView(context);

        /* Add child views to this object. */
        addView(calendarImageView);
        addView(calendarMonthTextView);
        addView(calendarDayTextView);
    }

    private void setUpImageView(final Context context) {
        calendarImageView = new ImageView(context);
        calendarImageView.setImageResource(R.drawable.bg_calendar);
        calendarImageView.setScaleType(ImageView.ScaleType.FIT_XY);
    }

    private void setUpMonthView(final Context context) {
        calendarMonthTextView = new TextView(context);
        calendarMonthTextView.setTextSize(7);
        calendarMonthTextView.setTypeface(Typeface.DEFAULT_BOLD);
        calendarMonthTextView.setPadding(0, 4, 0, 0);
        calendarMonthTextView.setTextColor(Color.WHITE);
        calendarMonthTextView.setGravity(Gravity.CENTER_HORIZONTAL);
    }

    private void setUpDayView(final Context context) {
        calendarDayTextView = new TextView(context);
        calendarDayTextView.setTextSize(10);
        calendarDayTextView.setTypeface(Typeface.DEFAULT_BOLD);
        calendarDayTextView.setPadding(0, 13, 0, 0);
        calendarDayTextView.setTextColor(Color.WHITE);
        calendarDayTextView.setGravity(Gravity.CENTER_HORIZONTAL);
    }
 
    public void setDayOfMonth(final int day) {
        this.calendarDayTextView.setText(Integer.toString(day));
    }

    public void setMonth(final String month) {
        this.calendarMonthTextView.setText(month);
    }
}

If you look at the above code you can see that adding the ImageView and TextViews is quite straight-forward. Because the SimpleCalendarView extends a FrameLayout, all inner views are positioned to the top left of the View by default. By setting the gravity of both TextViews to CENTER_HORIZONTAL the text is positioned in the middle of the image. Now by setting some top padding, the day and month are put into place.
So after all it wasn't that hard to do. You just have to get to know the possibilities of the different Layouts. For my own convenience I added two extra methods to the SimpleCalendarView, so that I can easily set the month and day for each event without having to call the individual TextViews.

What's next?

This has been an interesting lesson in working with layouts, views and lists. My next post will probably be about how to retrieve data from a remote server and use that data to feed the list.

Resources used

The following resources were used while trying to create this view:

10 January 2011

Tip of the day: sharing information between HST components

If you're working as a web developer with Hippo CMS, I guess you have written quite a few HST components. I presume that by now you will have a basic understanding of what HST components can and can't do.
I've had the situation myself where I wanted to share some information between components on a single page. I first thought I could simply achieve this by adding an attribute to the request, but that didn't work. To show you what you can do, let's first start of with a bit of background information about what's actually going on inside the HST, when an incoming request is being processed.

HST request processing


Let's first have a look at a page definition. In a traditional HST page definition you have a tree of components. The figure below describes a normal page layout defintion.


As you can see the page definition in the above figure has a root component (the page definition itself) with three child components: component 1, component 2 and component 3. Now the follow flow chart shows what the HST will do when it's handling a request.

This flow chart of couse does not show all the steps taken by the HST,
but it should give you a good impression of what's going on.

At first the HST will lookup the correct page definition based on the HST sitemap. Once the correct page definition has been found the HST will start processing.

The entire component tree for the current page definition is fetched and once the tree is there, the HST will use the AggregationValve to run down the component tree and invoke the doBeforeRender() methods of all of the available components.

Once the entire component three has been processed in the 'before render phase', it will start processing the doRender() methods of all the components, so that the output of every single component will be generated and aggregated to end up in the end result.

Now the important part to know here is that each invoked component will have it's own individual HStRequest object. Now if you want to share any kind of information you cannot simply use the HstRequest, because all the information is gone while processing the next component.
However there is an object attached to these individual HstRequest objects and that is the HstRequestContext. The HstRequestContext hold some quite useful information, which you help support your components, but you can also add your own information by setting some attribute.


Enough theory for now. If you would like to have a deeper knowledge of the HST request processing, the proces is described in much more detail on the HST2 wiki.


Now for some code


As an example let's take the usage of banners on a page. Let's say we have a boolean flag configured somewhere, which will define if banners should be shown on our page.

Let's presume that a banner can be shown by multiple components on a page. If we take figure 1, we could say that a banner could appear above component 2 and underneath component 3.

Now we could let both component 2 and component 3 figure out if the banners should be shown, but we could also share the information if component 2 or 3 is executed first, so that the other component does not have to read the configuration over again. The resulting code is quite simple. Let's have a look.

@Override
public void doBeforeRender(HstRequest request, HstResponse response) {
  boolean isBannerEnabled;
  HstRequestContext requestContext = request.getRequestContext();
  //let's see if the flag has been set on the request context
  if(requestContext.getAttribute(IS_BANNER_ENABLED_ATTRIBUTE)!=null){
    isBannerEnabled = (Boolean)requestContext.getAttribute(IS_BANNER_ENABLED_ATTRIBUTE);
  } else {
    //nothing on the request context, so lets figure it out
    isBannerEnabled = isBannerEnabled(request);
    //put the result on the request context so all other components can benefit
    requestContext.setAttribute(IS_BANNER_ENABLED_ATTRIBUTE, isBannerEnabled);
  }
  //put on the request for the current component
  request.setAttribute(IS_BANNER_ENABLED_ATTRIBUTE, isBannerEnabled);
}

/**
 * Simply return true for this example.
 */
boolean isBannerEnabled(HstRequest request) {
  return true;
}

As you will see the actual code is really simple. All you will have to do is store information on the HstRequestContext. That's it. Well these were my 2 cents for today. Go and have fun and try to leverage the power of the HST2.

22 October 2010

Getting started with Vaadin

A couple of weeks ago I made myself a promise that I would look into a new technology every month and write something about it here. I've been looking around for technologies unknown to me and perhaps to some of you, so I will start out with a RIA framework called Vaadin.


About Vaadin


Before I started my journey with Vaadin, I have to say that I had never heard of it before. I was quite surprised that they were at version 6.4.6 already. That must mean something right? Let's find out.
My first impression is that for an open source framework their documentation is excellent. It's something you don't see everyday with open source frameworks and I've seen quite a few over the past years.
Vaadin really impressed with that and there even is a free (e-)book called 'The book of Vaadin', which will get you started and gives you a lot of information about the history of Vaadin, the architecture, the different components bundled with Vaadin and much more.

The architecture


I don't want to go into to much detail here, since you can find all this information on the Vaadin website, but from an architectural point of view I think these are the key concepts you need to know about Vaadin:

  • Everything is written in plain Java (no need for HTML templates, like with for instance Wicket)
  • All request processing happens on the server-side
  • GWT is used for the client-side rendering
  • Vaadin is more application than page oriented
  • Vaadin applications are state-full applications. Everything is stored in the user session.
  • You can program with Vaadin, like you would program with Swing or AWT.
Now let's try to actually start with a small application.

Getting started


There are several ways to get started with Vaadin. Vaadin has it's own plugin for Eclipse, NetBeans and a nice DZone refcard, but since I don't use either of those IDE's, I went for the Maven2 way. There are several Maven 2 archetypes available, which you can use from the command line or use from your favorite IDE (IntelliJ in my case).

Now let's create a clean Vaadin application by calling the archetype:

mvn archetype:generate \
-DarchetypeGroupId=com.vaadin \
-DarchetypeArtifactId=vaadin-archetype-clean \
-DarchetypeVersion=LATEST \
-DgroupId=com.jeroenreijn \
-DartifactId=vaadin-demo \
-Dversion=1.0-SNAPSHOT \
-Dpackaging=war

This will result in a new folder called 'vaadin-demo' and all this folder contains is a pom.xml, a web.xml and a simple HelloWorld Vaadin application. There is nothing more to it than that.

The application class is really small and simple. It just contains some components to get you going. This is what it looks like:

package com.jeroenreijn;

import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Window;

public class MyVaadinApplication extends Application
{
    private Window window;

    @Override
    public void init()
    {
        window = new Window("My Vaadin Application");
        setMainWindow(window);
        window.addComponent(new Button("Click Me"));
    }
}

Now that is nice and small right? The only thing this application does for now is that it creates a Window to put elements on with a default layout. Next to that a button with the label "Click me" is added to this window. It does not do much, but it's enough to get you going.

What's next?

I don't want to go into a full application in this post, but even after playing around with some more complex things, I have the feeling that I only scratched the surface. I think Vaadin is really interesting if you have to write rich web applications. The framework itself also has an addon directory filled with interesting and mature add-ons. I have some ideas I want to work out so I will keep you posted with my progress.

21 October 2010

Unit testing your HST2 components with EasyMock

Quality is an important aspect of every software development project. Writing unit tests is just one part of keeping an eye on quality. In this post I will try to explain how you can unit test your Hippo Site Toolkit (HST2) components, so you can be sure that the component still behaves as expected even after multiple maintenance cycles.

A mocking framework

Unit testing is the testing of software units (for instance HST2 components) in isolation. However, most units do not work alone, but they collaborate with other units, like the HST2 does for instance with a running JCR repository and a live HttpServletRequest (wrapped inside an HstRequest). To test a unit in isolation, we have to simulate these collaborations in our tests.
One way of working around such collaborations is by using Mock objects. A Mock Object is a test-oriented replacement for such a collaborator. It is configured to simulate the object that it replaces in a simple way. For this post I use EasyMock, but there are other mocking frameworks out there.

Setting up your environment

If you are regular reader, you might have noticed that I've been using Maven2 in most of my posts, so this time will not be different. To be able to test your HST components, you will need to add the following dependencies to your project/module pom.xml.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.5</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>2.5.2</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymockclassextension</artifactId>
  <version>2.5.2</version>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.onehippo.cms7.hst</groupId>
  <artifactId>hst-mock</artifactId>
  <scope>test</scope>
</dependency>


Now that we have setup all the needed dependencies let's create an HST component to get started.

Basic HST2 Component


So let's start of with a simple/basic HST2 component. Here we have a simple component that tries to get a HippoBean wrapping a JCR node for the current request and puts the bean as an attribute on the request.

import org.hippoecm.hst.component.support.bean.BaseHstComponent;
import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.core.component.HstComponentException;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.component.HstResponse;

public class AbstractBaseHstComponent extends BaseHstComponent{

    @Override
    public void doBeforeRender(HstRequest request, HstResponse response) 
        throws HstComponentException {

        HippoBean bean = getContentBean(request);
        if(bean!=null) {
            request.setAttribute("document",bean);
        }
    }
}

Looks quite simple right? Now let's move on to the test.

The actual test

Now that we've seen what our component looks like, let's take a look at how we can test this class. The component doesn't do a lot, but there are a couple of things that we want to test:

  • that the getContentBean method is called
  • when the bean is not null the bean is set as an attribute on the request
  • there is an attribute on the request with the name document
  • the document from the request attribute is the same as the one put on the request

So now let's translate that into some code.

Before we can actually test our doBeforeRender method we need to do some setup before we can continue.

MockHstRequest fakeRequest;
MockHstResponse fakeResponse;
AbstractBaseHstComponent component;

@Before
public void setUp() throws Exception {
    fakeRequest = new MockHstRequest();
    fakeResponse = new MockHstResponse();
    component = createMockBuilder(AbstractBaseHstComponent.class).
                addMockedMethod("getContentBean", HstRequest.class).
                createMock();
}

Now looking at this setUp() method, you will notice that at first we create mocked versions of a request and response. These objects are necessary because they are parameters for our method under test. In a normal environment these objects will be created by the servlet container, but since we're unit testing we have to create these ourselves.

Next to that we create a mocked version of our AbstractBaseHstComponent. We do this because we need to mock the getContentBean method, which in a normal live environment performs interaction to a live JCR repository. The logic for getting the bean based on repository configuration is not useful for our test, so we mock the method and create a partial mock of the class.

Now let's have a look at the total test case and the actual test method.

import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.content.beans.standard.HippoDocument;
import org.hippoecm.hst.core.component.HstRequest;
import org.junit.Before;
import org.junit.Test;
import org.hippoecm.hst.mock.core.component.MockHstRequest;
import org.hippoecm.hst.mock.core.component.MockHstResponse;
import static org.easymock.classextension.EasyMock.*;
import static org.junit.Assert.*;

/**
 * Test for {@link com.jeroenreijn.site.components.AbstractBaseHstComponent}
 */
public class AbstractBaseHstComponentTest {

    MockHstRequest fakeRequest;
    MockHstResponse fakeResponse;
    AbstractBaseHstComponent component;

    @Before
    public void setUp() throws Exception {
        fakeRequest = new MockHstRequest();
        fakeResponse = new MockHstResponse();
        component = createMockBuilder(AbstractBaseHstComponent.class).
                addMockedMethod("getContentBean", HstRequest.class).
                createMock();
    }

    @Test
    public void testDocumentOnRequestAfterDoBeforeRender() throws Exception {

        HippoBean bean = new HippoDocument();

        //record the expected behavior
        expect(component.getContentBean(fakeRequest)).andReturn(bean);

        //stop recording and switch the mocked Object to replay state.
        replay(component);

        component.doBeforeRender(fakeRequest,fakeResponse);

        //verify the specified behavior has been used
        verify(component);

        assertSame(fakeRequest.getAttribute("document"),bean);
    }
}


As you might notice, the testDocumentOnRequestAfterDoBeforeRender() method tests the doBeforeRender method and checks all of the above requirements.

The next step


Even though you can create a mock of most objects quite easily, it's much better to have some native support/provided mock objects for most HST2 classes. Therefore I've added a patch to JIRA, which adds more mocked classes that can be used for testing, so you do not have to mock explicit methods. Next to that it will create test maven artifact, which you can use when testing your HST component without having to mock explicit methods or objects yourself.
Let me know if you run into any issues or have some ideas on improvement. It can make all our lives better.

Note/Update: This post was written at a time when the mock classes were not part of Hippo core (version 7.4). In the meantime this has changed and the classes can now be found in hst-mock artifact.


ps. I've just noticed that Shane Smith of iProfs created a similar post with using Mockito.

06 October 2010

Large heap dump analysis with Eclipse Memory Analyzer

Most developers working with Java hardly have to think about the memory footprint of their application that they wrote. The garbage collector inside the JVM will remove most waste, but what happens when not all waste can be removed or something is wrong inside the application? This may result in an exception that probably a lot of developers and system administrators have seen before: java.lang.OutOfMemoryError (OOME).
There are several causes for such an exception, but the most obvious is that there is memory leak somewhere in the application.

The situation

At one of my recent projects we were having some memory related issues on one of the production machines. The web application was running in Tomcat 6 and it appeared that at a certain point in time, the JVM tried to allocate twice the average memory it was using. Let's say from 2 Gb the memory footprint went up to 4GB. You might have guessed it, because only a couple of minutes later we were represented with the OOME message in the server log. It turned out that this was related to the amount and type of requests being handled by the application server. I was glad to find out it was not a memory leak, but more a warning that the total size of requests could allocate a lot of memory. If your application is running, it's hard to see what objects allocate memory. To get an insight on what the application was doing at the moment the OOME occurred, we configured the JVM to create a memory(heap) dump/snapshot at the moment that the OOME was thrown.

Generating a heap dump

Most of my clients run on the Sun(Oracle) JVM, so I will try to keep this post focussed on the instructions for the Sun JVM. In case your application server runs out of memory you can instruct the JVM to generate a heap dump when an OOME occurs. This heap dump will be generated in the HPROF binary format.

You can do this in by:

  1. Manually: by using 'jmap', which is available since JDK 1.5.
  2. Automatically by providing the following JVM command line parameter:
    -XX:+HeapDumpOnOutOfMemoryError

The size of the heap dump is around the same size as the configured max heap size JVM parameter.
So if you have set your max heap size to -Xmx512m , your heap dump will be around that size.

Analyzing the heap dump

Now you have the heap dump and want to figure out what was inside the heap at the moment the OOME occurred. There are several Java heap dump analyzers out there, where most of them can do more then just heap analysis. The products range from commercial to open source and these are the ones that I tried with my 4Gb .hprof file:


I was surprised to see that most of the above applications were unable to handle a file of this size. Eclipse Memory Analyzer was actually the only heap dump analyzer that was able to handle a heap dump of this size on my MacBookPro. All the other analyzers were unable to handle a file of this size. Apparently some of these tools tried to load the entire file into memory. On a laptop with only 4 Gb this will not fit.  Eclipse MAT was able to analyze this file within 5-10 minutes.

About Eclipse Memory Analyzer


One of the great things about Eclipse Memory Analyzer is that it starts indexing the heapdumps on first load. This makes the processing of the heapdump very fast and once you've parsed the entire heapdump, reopening it is a piece of cake, because it does not have to process it all over again.

Once you have the heapdump on your screen the dominator tree view is the most useful view and can give you a very good insight on what was loaded when the server ran out of memory.

Next to the statistical views there is also an automatic leak hunter available to help you figure out the problem as fast as possible.

Summary


If you ever have to analyze a heap dump I would recommend to use Eclipse Memory Analyzer. It's fast, easy to use and free.