Some SQL injection in Android – how to use GROUP BY and CASE when you are not allowed to do so

I suppose you’re all familiar with the “academic” examples of SQL injection when you put a AND 1=1 at the end of the SQL query and magically you get access to all kind of nasty things. I’ll show you how to use the same trick to do a SQL injection in Android, but for a good thing ūüôā

I had the following situation: I’ve wanted to select group all the calls from the call log either by the caller name if the number was in the agenda or by number if the number was not in the agenda. To do this you need a content resolver, a URI and a projection to tell Android which columns you want to select. A typical call will look as follows:

getContentResolver().query(CallLog.Calls.CONTENT_URI, 
new String[] { projection}, selection, new String[] 
{selectionArgs}, sortOrder)

As you notice there is no way of telling android how to group the rows. But we Continue reading “Some SQL injection in Android – how to use GROUP BY and CASE when you are not allowed to do so”

Advertisements

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 “Guice – a lightweight DI framework alternative to Spring”

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 display images from the database in your jsp pages – the easy way”

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].