My first open source project: Selenium on Steroids

The projects targets QA automation engineers that want a clean and simple way to create Selenium tests allowing them to focus more on designing the tests rather than dealing with technical difficulties. Using a simple property file and Maven profiles the instantiation of a WebDriver objects with different kind of settings reduces to just setting some predefined properties. The project enhances the functionality of the WebDriver API by offering additional methods for common tasks, having as a long run target to implement most of the Selenium IDE functions. SoS also offers different utility methods to interact with simple files, properties files, Excel documents, XML documents, Databases, post XML calls over HTTP, etc. Basically everything you need for your data driven testing scenarios.

Features

Using Google Guice in Web Applications

Introduction

As promised in the previous article I’ll continue presenting Google Guice also for web applications. In order to do this you’ll need to get the servlet extension – part of the standard distribution, along with other extensions like JMX, JNDI, Persist, Struts or Spring. Using Guice, the web.xml will be reduced at minimum – just make the Guice container start. The rest of the configurations will be easily done in Java in the same type-safe manner presented in the previous article.

The servlets will benefit from:

Having JAXB1 and JAXB2 in the same classpath

If you just add JAXB1 and JAXB2 jars into the same classpath you may end up with the following exception:

You are trying to run JAXB 2.0 runtime but you have old JAXB 1.0 
runtime earlier in the classpath.
Please remove the JAXB 1.0 runtime for 2.0 runtime to work correctly.

The ideal solution would be to migrate everything to JAXB2 and remove the JAXB1 dependencies, but if you have certain constrains around this (and there usually are a lot) like: time, legacy systems, too much effort to retest everythig, etc there is an easy solution to have the old code run smooth and in the same time write the new code using the latest version of JAXB.

Here are the steps you need to follow:

  • Download jax1-impl-XXX.jar, where XXX is something like 2.x.x (this can be found in the JAXB2 distribution)
  • Remove your old jaxb-impl.jar (version 1) from the classpath
  • Add the new jaxb1-impl-XXX.jar into the classpath

All done!

Guice – a lightweight DI framework alternative to Spring

What is Guice?

To quote from the Guice official page

“Guice alleviates the need for factories and the use of new in your Java code. Think of Guice’s @Inject as the new new. Guice embraces Java’s type safe nature, especially when it comes to features introduced in Java 5 such as generics and annotations. You might think of Guice as filling in missing features for core Java. Ideally, the language itself would provide most of the same features, but until such a language comes along, we have Guice”

If you’ve used Spring or other DI frameworks you’re probably familiar to the above ideas. I’ll present in this article how to get started with Guice in a non-web application. I’ll detail the web side in a future article.

Is it better than Spring?

Well, this is one of those talks that could last forever. Like EJB vs Spring, Struts vs JSF and so on. It’s a matter of choice. I can say one thing though: if you need just  DI in your application go for Guice. It’s very lightweight, it’s type safe and it’s faster than Spring.

Using Guice for a non-web application

Suppose you have an application and the class that contains the main method its called Application. When using Guice the approach is a little changed. Besides starting the application you’ll also want a way to trigger the dependency injection. In order to to this you must have an “entry-point” that “manually” triggers the creation of the graph of objects that will get injected and only after that starts the actual application logic. We’ll call the class responsible for these 2 things the Bootstrap class. We also need to create a Module by extending the AbstractModule class. Quoting from the Java Doc of the Module interface:

A module contributes configuration information, typically interface bindings, which will be used to create an Injector. A Guice-based application is ultimately composed of little more than a set of Modules and some bootstrapping code.

Let’s see the code:

The Bootstrap class:

package com.insidecoding.guice;
import com.google.inject.Guice;

Continue reading

How to display images from the database in your jsp pages – the easy way

The easiest and elegant way to read images from the database and display them in the UI is through a servlet that handles the image processing for you. I’ll present below a sample that displays a user avatar in the jsp page. This sample uses Spring 3 and the tip from this article to inject a spring bean into this servlet. This example can easily be adapted to many kinds of situations. Here is the code:

The servlet

package insidecoding.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import insidecoding.service.UserService;

@Component("imageServlet")
public class ImageServlet implements HttpRequestHandler {

    @Autowired
    private UserService UserService;

    @Override
    public void handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // get the thumb from the user entity
        byte[] thumb = userService.getCurrentUserAvatar();

        String name = "userAvatar";
        response.setContentType("image/jpeg");
        response.setContentLength(thumb.length);

        response.setHeader("Content-Disposition", "inline; filename=\"" + name
                + "\"");

        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            input = new BufferedInputStream(new ByteArrayInputStream(thumb));
            output = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[8192];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (IOException e) {
            System.out.println("There are errors in reading/writing image stream "
                    + e.getMessage());
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException ignore) {
                }
            if (input != null)
                try {
                    input.close();
                } catch (IOException ignore) {
                }
        }

    }
}

Map this servlet to the /image path in web.xml

     <servlet>
        <servlet-name>imageServlet</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>imageServlet</servlet-name>
        <url-pattern>/image/*</url-pattern>
    </servlet-mapping>

Usage in JSP Continue reading

How to increase Tomcat heap size in Eclipse

If you get a lot of java.lang.OutOfMemoryErrors while running your web application on Tomcat from Eclipse, it means that you should increase the heap size of your tomcat instance. To do this, follow these steps:

1. Open the Server view and double-click on the Tomcat instance. The server configuration screen will open.

2. Click on the “Open launch configuration” link from the General Information section.

3. Click on the Arguments tab and add the following at the end of the VM arguments: -Xms128m -Xmx512m.

The values for this 2 arguments may vary, depending on your needs or available memory :)

Algorithm: Get all possible letter combinations from a dialed number

Problem

Implement a smart dialer. When typing digits into a dialer, get all contacts that match any letters combination corresponding to the typed digits. If you type 564, for example, the dialer should suggest John.

Solution

The core of this dialer is an algorithm that returns all possible letter combinations for a dialed number. After this, just find any contact that starts with any of this combinations.

How to do it:

- we need a mapping between digits and letters.

- if the dialed number starts with 0 or 1, ignore it as they don’t match any letter on the keyboard

- otherwise, for each digit in the dialed number, iterate through each array of letters and put each possible combination into a list.

This can be implemented using recursion. The code in Java (for Android):

package insidecoding.android;

import java.util.ArrayList;
import java.util.List;

public class DialSuggestHelper {
    private static final String[][] MAPPINGS = { { "0" }, { "1" },
            { "A", "B", "C" }, { "D", "E", "F" }, { "G", "H", "I" },
            { "J", "K", "L" }, { "M", "N", "O" }, { "P", "Q", "R", "S" },
            { "T", "U", "V" }, { "X", "Y", "Z", "W" } };

    private DialSuggestHelper() {

    }

    public static List getConditions(String number) {
        if (number.startsWith("0") || number.startsWith("1")) {
            return new ArrayList();
        }

        List list = new ArrayList();

        int[] arr = new int[number.length()];
        for (int j = 0; j < arr.length; j++) {
            arr[j] = Integer.parseInt(String.valueOf(number.charAt(j)));
        }
        combine("", arr, 0, list);
        return list;
    }

    public static void combine(String root, int[] number, int current,
            List list) {
        for (int k = 0; k < MAPPINGS[number[current]].length; k++) {

            if (current == number.length - 1) {
                list.add(root + MAPPINGS[number[current]][k]);
            } else {
                combine(root + MAPPINGS[number[current]][k], number, current + 1,
                        list);
            }

        }
    }
}
Usage: getConditions("564") will return [JMG, JMH, JMI, JNG, JNH, JNI, JOG, JOH, JOI,
 KMG, KMH, KMI, KNG, KNH, KNI, KOG, KOH, KOI, LMG, 
LMH, LMI, LNG, LNH, LNI, LOG, LOH, LOI].

Creating a URL JLabel in Swing

So, you need a simple clickable URL JLabel in your Swing application? You can, of course, use third party libraries to do this, but why add another dependency for a single component when can easily write one in 5 minutes.

So what do we want for this JLabel:

  • to click on it and go to an URL
  • to have a hand cursor on mouse over
  • the text to be underlined just like a real link

We’ll write a class that extends JLabel and a mouse adapter that will take care of opening the link. As the mouse adapter will be used only for this label, we’ll add it as a private member class. Here is the code:

package insidecoding.swing

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URI;
import javax.swing.JLabel;

/**
 *
 * @author ludovicianul
 */
public class URLLabel extends JLabel {

    private String url;

    public URLLabel() {
        this("","");
    }

    public URLLabel(String label, String url) {
        super(label);

        this.url = url;
        setForeground(Color.BLUE.darker());
        setCursor(
                new Cursor(Cursor.HAND_CURSOR));
        addMouseListener(
                new URLOpenAdapter());
    }

    public void setURL(String url) {
        this.url = url;
    }

    //this is used to underline the text
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.blue);

        Insets insets = getInsets();

        int left = insets.left;
        if (getIcon() != null) {
            left += getIcon().getIconWidth() + getIconTextGap();
        }

        g.drawLine(left, getHeight() - 1 - insets.bottom, (int) getPreferredSize().getWidth()
                - insets.right, getHeight() - 1 - insets.bottom);
    }

    private class URLOpenAdapter extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(new URI(url));
                } catch (Throwable t) {
                    //
                }
            }
        }
    }
}

I think the code is pretty self-explanatory:

  • in the constructor we set the label color to a darker blue, we set the mouse over cursor to Hand Cursor and we register the mouse click listener
  • we use the paint() method to underline the label’s text
  • the mouse adapter uses the Continue reading