Showing posts with label base64. Show all posts
Showing posts with label base64. Show all posts

Saturday, February 12, 2011

Taking a picture - Base64 encoding in JavaMe

It's been a while since my last post, January was a busy month, but here I am again.

In this post, we are going to do something really interesting: taking a snapshot with the phone's camera and send it to the server in Base64 format.

You should read the post about Base64 in JavaMe (J2ME) if you haven't:


Taking the snapshot is quite easy, you just have to be careful about blocking calls. The real problem happens when uploading the image to the server. I tried several scenarios using Glassfish 3.0.1 and Tomcat 6.0.32 and none of the scenarios worked on both servers... It was very frustrating becasue the code seems to be OK, but works for Glassfish or for Tomcat but not both.

Let's start with the general code, assume the following is inside the MIDlet class:

  
     //inside MIDlet class...

     /** Commands to control the application flow*/
     private Command commandShoot = null;
     private Command commandExit = null;
     private Command commandSend = null;
     private Command commandBack = null;
     private Display display = null;

     /** flags to indicate whether the phone 
      *  supports png or jpeg encoding for snapshots
      */
     private boolean png = false;
     private boolean jpeg = false;

     /** Canvas where the video is going to be played*/
     private VideoCanvas videoCanvas = null;

     /** Canvas where the snapshot is going to be shown*/
     private ImageCanvas imgCanvas = null;


     public void startApp() {
        display = Display.getDisplay(this);

        commandExit = new Command("Exit", Command.EXIT, 0);
        commandShoot = new Command("Shoot", Command.SCREEN, 0);
        commandSend = new Command("Send", Command.SCREEN, 0);
        commandBack = new Command("Back", Command.BACK, 0);

        //Verifies if the application can use the camera
        //and encoding
        if (checkCameraSupport() && 
            checkSnapShotEncodingSupport()) {

            //this is the canvas where the video will render
            videoCanvas = new VideoCanvas(this);
            videoCanvas.addCommand(commandExit);
            videoCanvas.addCommand(commandShoot);
            videoCanvas.setCommandListener(this);

            display.setCurrent(videoCanvas);
        } else {
            System.out.println("NO camera support");
        }
    }

    /**
     * Checks whether the phone has camera support
     * @return true if and only if the phone has camera
     * support
     */
    private boolean checkCameraSupport() {
        String propValue = System.getProperty
                           ("supports.video.capture");
        return (propValue != null) && propValue.equals("true");
    }
    
    /**
     * Checks if the phone has png or jpeg support.
     * @return true if and only if the phone supports
     * png or jpeg encoding
     */
    private boolean checkSnapShotEncodingSupport() {
        String encodings = System.getProperty
                           ("video.snapshot.encodings");
        png = (encodings != null) 
              && (encodings.indexOf("png") != -1);

        jpeg = (encodings != null) 
               && (encodings.indexOf("jpeg") != -1);

        return png || jpeg;
    }

The previous methods tell you if the phone has camera support and if it can encode snapshots in either png or jpeg format. The +startApp():void method, starts the application, checks for the camera support and starts the canvas where the video will render.

Next is the method that actually encodes an array of bytes. Later we will show how to pass the Image as a byte array to this method in order to get the Image in Base64 format:

  
     //inside MIDlet class...

    /**
     * Encodes an array of bytes
     * @param imgBytes Array of bytes to encode
     * @return String representing the Base64 format of
     * the array parameter
     */
    public String encodeImage(byte[] imgBytes) {
        byte[] coded = Base64.encode(imgBytes);
        return new String(coded);
    }

As we saw in the Base64 encode-decode in JavaMe (J2ME) Post, the previous method encodes using the bouncy castle library.

The following methods goes inside the MIDlet class as well, they are responsible of starting the canvas that takes the snapshot and passing the snapshot to another canvas in order to show it to the user:

  
    //inside MIDlet...

    /**
     * Starts the Video Canvas to take the snapshot
     */
    public void snapShot() {

        if (png) {
            videoCanvas.startSnapShot("png");
        } else if (jpeg) {
            videoCanvas.startSnapShot("jpeg");
        } else {
            videoCanvas.startSnapShot(null);
        }
    }

    /**
     * Shows the snapshot in a Canvas
     * @param bytes Array of bytes representing the
     * snapshot
     */
    public void showSnapShot(byte[] bytes) {
        if (bytes != null) {

            imgCanvas = new ImageCanvas(bytes);
            imgCanvas.addCommand(commandSend);
            imgCanvas.addCommand(commandBack);
            imgCanvas.setCommandListener(this);

            display.setCurrent(imgCanvas);
        }
    }

OK, that's pretty much the general code for the MIDlet, let's see what happens within the VideoCanvas class. The next code should be inside the constructor, it starts the video player:

        
    //inside VideoCanvas class...

    /* Application MIDlet**/
    ImageCaptureMidlet midlet = null;

    /** Control for the video*/
    VideoControl videoControl = null;

    public VideoCanvas(ImageCaptureMidlet mid) {
        midlet = mid;
        Player player = null;

        try {
            player = Manager.createPlayer("capture://video");
            player.realize();
            videoControl = (VideoControl) player.getControl
                           ("VideoControl");
            videoControl.initDisplayMode
                       (VideoControl.USE_DIRECT_VIDEO, this);
            videoControl.setDisplayFullScreen(true);
            videoControl.setVisible(true);

            player.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

So, when the canvas is created it starts the player and the video starts playing inside the canvas. When the MIDlet invokes the +snapShot():void method, the following piece of code is executed inside the VideoCanvas class:

    //inside VideoCanvas class...

    /**
     * Starts a thread to take the snapshot. 
     * Some devices will take the snapshot without 
     * the need of a thread, but some others 
     * doesn't (including my emulator). 
     * So start a new Thread...
     * @param encoding String representing the encoding
     * to use when taking the snapshot
     */
    public void startSnapShot(final String encoding) {
        new Thread(new Runnable() {

            public void run() {
                try {
                    byte[] rawBytes = null;
                    if (encoding != null) {
                        //take the snapshot using the encoding
                        rawBytes = videoControl.getSnapshot
                                   ("encoding=" + encoding);

                    } else {
                        //take the snapshot using the best
                        //possible encoding. 
                        //Implementation dependent
                        rawBytes = videoControl.getSnapshot
                                   (null);
                    }
                    //ask the midlet to show the snapshot
                    midlet.showSnapShot(rawBytes);
                } catch (MediaException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }

You may notice that the method starts a new Thread. That's because not all devices will take the snapshot right away, some times it takes a little bit to start the camera and take the sanpshot. That's why, we have started a new Thread. Also, check that +VideoControl.getSnapshot(String):byte[] method can receive a null parameter, indicating that let the implementation decide which is the best encoding possible to take the snapshot. Finally, when the snapshot is taken, the method asks the application MIDlet to show it.

We have previously seen the +showSnapShot(byte[]):void method in the MIDlet class, so let's take care about the ImageCanvas class where the snapshot is shown:

    //inside ImageCanvas class...

    /** Snapshot to render*/
    private Image image = null;

    /** bytes of the snapshot*/
    private byte[] imageBytes = null;

    public ImageCanvas(byte[] bytes) {
        imageBytes = bytes;

        //creates an Image using the byte array 
        image = Image.createImage(imageBytes, 0, 
                                  imageBytes.length);
    }

    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        g.setColor(0x000000);
        g.fillRect(0, 0, width, height);

        //render the snapshot
        g.drawImage(image, getWidth() / 2, getHeight() / 2, 
                    Graphics.HCENTER | Graphics.VCENTER);
    }

    //Getters and Setters...


OK, up until now we have seen how to take a snapshot and render it on a Canvas. That's the general code we were talking about at the beginning of this post. Now let's see how to send the snapshot to the server. Here we are going to present two scenarios, one for Glassfish server and another for the Tomcat server.

Glassfish Server:
The following method is the method inside the MIDlet that sends the snapshot to a servlet deployed on Glassfish server 3.0.1:

    //inside MIDlet class

    /**
     * Sends the snapshot to the server
     */
    public void send() {
        new Thread(new Runnable() {

            public void run() {

                String imageEncoded = 
                   encodeImage(imgCanvas.
                               getImageBytes());                

                String format = png ? "png" : jpeg?"jpeg":"";
                
                //This is my servlet’s URL
                String URL = 
                           "http://localhost:8080/" + 
                           "Base64ExampleServlet_v2/" +
                           "ImageServlet";

                HttpConnection http = null;
                OutputStream os = null;
                DataOutputStream dout = null;
                try {
                    //Open HttpConnection using POST
                    http = (HttpConnection) Connector.open(URL);
                    http.setRequestMethod(HttpConnection.POST);
                    //Content-Type is must to pass parameters 
                    //in POST Request
                    http.setRequestProperty(
                         "Content-Type", 
                         "application/x-www-form-urlencoded");
                   
                    os = http.openOutputStream();

                    ByteArrayOutputStream bout = new 
                                       ByteArrayOutputStream();
                    dout = new DataOutputStream(bout);
                    dout.writeUTF(imageEncoded);
                    dout.writeUTF(format);
                    os.write(bout.toByteArray());
                    
                    os.flush();  
                } catch (IOException ex) {
                    ex.printStackTrace();
                } 
                //whatever happens, close the streams 
                //and connections
                finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    if (dout != null) {
                        try {
                            dout.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    if (http != null) {
                        try {
                            http.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

As you can see, the method calls the encoding method passing the snapshot as a byte array, then it starts a HttpConnection to the servlet deployed on Glassfish server. It opens the OutputStream and writes the image as Base64 format and it also writes the encoding (format) used. On the server side, you should read the stream the same way you wrote it, taht is, first read the image in Base64 format and then the encoding used (format).

Tomcat Server:
The following method is the method inside the MIDlet that sends the snapshot to a servlet deployed on Tomcat server 6.0.32:

    //inside MIDlet class

    /**
     * Sends the snapshot to the server
     */
    public void send() {
        new Thread(new Runnable() {

            public void run() {

                String imageEncoded = 
                   encodeImage(imgCanvas.
                               getImageBytes());                

                String format = png ? "png" : jpeg?"jpeg":"";
                
                //This is my servlet’s URL
                String URL = 
                           "http://localhost:8080/" + 
                           "Base64ExampleServlet_v2/" +
                           "ImageServlet";

                HttpConnection http = null;
                OutputStream os = null;
                try {
                    //Open HttpConnection using POST
                    http = (HttpConnection) Connector.open(URL);
                    http.setRequestMethod(HttpConnection.POST);
                    //Content-Type is must to pass parameters 
                    //in POST Request
                    http.setRequestProperty(
                         "Content-Type", 
                         "application/x-www-form-urlencoded");
                   
                    os = http.openOutputStream();

                    //IMPORTANT, when writing Base64 format
                    //there are chars like '+' that  
                    //must be replaced when sending.
                    imageEncoded = 
                        imageEncoded.replace('+', '-');
                    StringBuffer params = new StringBuffer();
                    params.append("image" + "=" + imageEncoded);
                    params.append("&" + 
                                  "format" + "=" + format);
                    System.out.println(params.toString());
                    os = http.openOutputStream();
                    os.write(params.toString().getBytes());
                    
                    os.flush();  
                } catch (IOException ex) {
                    ex.printStackTrace();
                } 
                //whatever happens, close the streams 
                //and connections
                finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    if (http != null) {
                        try {
                            http.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

This method differs from the Glassfish method in the way it writes the parameters. Tomcat's method writes the parameters as a key/value pair. Notice one important point, the Base64 format uses chars like '+', chars that may be confused in the HTTP protocol, because they can be translated as a space char. So before sending the image in Base64, replace the '+' chars with '-' chars, but when receiving in the servlet (server side), convert the chars back before writing the image to the disk. This is only needed in the Tomcat's method.

Wow, loooooong post... Again, my advise is be careful when deciding which method to use in which server. Sometimes the code you wrote may be well written but for some reasons it won't work on the server... so you have to try another way to write your code until it works.

That's it for now, hope this helps you to write applications that use the device's camera.

see ya soon!


References:

Taking Pictures with MMAPI. 2011. Oracle [online].
Available on Internet: http://developers.sun.com/mobility/midp/articles/picture/
[accessed on February 01 2011].

Java Tips - Capturing Video on J2ME devices. 2011. Java Tips [online].
Available on Internet: http://www.java-tips.org/java-me-tips/midp/capturing-video-on-j2me-devices.html
[accessed on February 01 2011].

J2ME Sample Codes: Image Capturing in J2ME. 2011. J2ME Sample Codes [online].
Available on Internet: http://j2mesamples.blogspot.com/2009/06/image-capturing-in-j2me.html
[accessed on February 01 2011].

Embedded Interaction - Working with J2ME - Picture transmission over HTTP. 2011. Embedded Interaction [online].
Available on Internet: http://www.hcilab.org/documents/tutorials/PictureTransmissionOverHTTP/index.html
[accessed on February 01 2011].

Base64. 2010. Wikipedia [online].
Available on Internet: http://en.wikipedia.org/wiki/Base64
[accessed on December 28 2010].

The Legion of the Bouncy Castle. bouncycastle.org [online].
Available on Internet: http://www.bouncycastle.org/
[accessed on December 28 2010].

Sunday, January 9, 2011

Servlet-GSON vs JSONME-JavaME III

This is the third post about JSON and JavaME. In previous releases: first we introduced JSON for JavaMe (J2ME), then we improved the example by adding compression/decompression support. Now, we are going to introduce Base64 format support for sending images in our JSON example.
Although this is not a best practice, because you should send the image's URL  instead of sending the image itself in the JSON String, sometimes you just need to do exactly that.

Requirements:

Servlet-GSON vs JSONME-JavaME: Contains the original classes. More info:
http://www.java-n-me.com/2010/11/servlet-gson-vs-jsonme-javame.html

Servlet-GSON vs JSONME-JavaME II: Second part of the saga. Adds compression/decompression support. More info:
http://www.java-n-me.com/2010/12/servlet-gson-vs-jsonme-javame-ii.html

Base64 encode-decode in JavaMe: Explains how to use Base64 format in JavaMe (J2ME). More info:
http://www.java-n-me.com/2010/12/base64-encode-decode-in-javame.html


You should check the previous requirements if you haven't, because in this post we use some of the classes defined there.

The image we are going to send is in PNG format:



OK, let's begin, first we are going to show you the changes in some of the original classes. As usual, let's start with the server side:

import java.awt.Image;
public class Client {

   /** Name of the client*/
    private String name;

    /** Last name of the client*/
    private String lastName;

    /** Identification of the client*/
    private String id;

    /** Photo of the client*/
    private transient Image photo;


    /** Photo of the client in Base 64 format*/
    private  String photoBase64;


    //Getters and Setters...
}

Our Client class has now two new attributes for the photograph of the client. The java.awt.Image attribute binds to the photograph of the client directly. The String attribute photoBase64 contains the Base64 format of the photograph that is going to be sent in the JSON String. Notice that the attribute photo is marked as transient, meaning that GSON won't use this attribute in the JSON String.

Following is the servlet class which will create a client with a photograph, will get the JSON String representation of the client and his photograph and will compress the data before sending the response to the mobile client. The servlet uses the GSON API, the java.util.zip.GZIPOutputStream and the JSE sun.misc.BASE64Encoder class:


import com.google.gson.Gson;
import java.io.*;
import java.net.URL;
import java.util.Vector;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;
import javax.swing.ImageIcon;
import model.Client;
import sun.misc.BASE64Encoder;

public class ClientsServlet extends HttpServlet {
   ...

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //sets the type of response and the charset used
        //Be careful, in your mobile client, read the response using the same charset
        //if sending the response as text. If you sent it as binary data,
        //there is no problem
        response.setContentType("application/json; charset=UTF-8");

        //create some clients and add them to the vector
        Vector vClients = new Vector();

        //used to convert Image to Base64 format
        BASE64Encoder encoder = new BASE64Encoder();

        Client clientOne = new Client();
        clientOne.setName("Alexis");
        clientOne.setLastName("López Ñ");
        clientOne.setId("123456");
        clientOne.setPhoto(new ImageIcon("images/duke.png").getImage());
        //get the image bytes. Read it as an URL
        byte[] imgBytes =
          getImageBytes("http://localhost:8080/GSON_Servlet/images/duke.png");
        String imageCoded = encoder.encode(imgBytes);
        clientOne.setPhotoBase64(imageCoded);

        //... add more clients...
      
        vClients
           .add(clientOne);

        //convert the clients vector to JSON using GSON, very Easy
        Gson gson = new Gson();
        String jsonOutput = gson.toJson(vClients);

        System.out.println("*****JSON STRING TO RESPONSE*****");
        System.out.println(jsonOutput);
        System.out.println("*********************************");

        System.out.println("Length of String in bytes = "
                                    + jsonOutput.getBytes().length);
        //compress de data
        byte[] compressed = compress(jsonOutput);
        System.out.println("Length of compressed bytes = "
                                    + compressed.length);

        //send the binary response
        ServletOutputStream out = response.getOutputStream();
        out.write(compressed, 0, compressed.length);
        out.flush();
        out.close();
    }
    ...
}

The servlet uses two important methods. One is the +compress(String):byte[] that we have analized in the previous post of this saga. The other one is the +getImageBytes(String):byte[] which is shown next:

/** * Returns the binary representation of the image passed as an URL * @param imgURL URL String of the image * @return array of binary data representing the image * @throws IOException */ public static byte[] getImageBytes(String imgURL) throws IOException { URL imgUrl = new URL(imgURL); ByteArrayOutputStream bout = new ByteArrayOutputStream(); InputStream in = imgUrl.openStream(); int i = 0; while ((i = in.read()) != -1) { bout.write(i); } in.close(); bout.close(); byte[] bytes = bout.toByteArray(); return bytes; }

The last method reads the image from the URL and gets its binary representation. One important thing to keep in mind, is that you should use PNG Images as it is the default format for JavaMe (J2ME) MIDP applications, not doing so may arise exceptions on the mobile client when parsing the Image data. When the servlet is run and it receives a POST request, the following message is shown on the console output:

INFO: *****JSON STRING TO RESPONSE***** 9/01/2011 06:11:23 PM INFO: [{"name":"Alexis","lastName":"López Ñ","id":"123456","photoBase64":"iVBORw0KGgoAAAANSUhEUgAAAP8AAADICAMAAAAQqcftAAAAAXNSR0IArs4c6QAAAwBQTFRFDAAA\r\nCgQKGAAAEAgMGAAIGAAQGAgIGAgQEBAIABAQCBAQEBAQEBAYEBgQEBgYECEYGAgYGBAIGBAQGBAY\r\nGBgIGBgQGBgYGBghGCEYIQAAIQAIIQAQIQgQIQgYIRAQIRAYKQAMKQgQKQAYIRAhIRgQIRgYIRgh\r\nISEYMQAILgUVNwQSQgAYKRAUKRgYKSEYPA0YISEhKRAhKRghKRgpMRQhMRgpPQghPRQhKSEhKSkh\r\nISEpKSYrMSUlNi4pOScvOzU1SBwpRkI9WgYgbBk1RkJKTkdHVkhNVFJMUlJaWlRUXlhaZVtdb2Fk\r\ncWxne2lwf3h5yBUsqDBU1Bcx0SRJ3BU53xs53yJK4TJjin5"
... not all data shown ... "}] INFO: *********************************



INFO: Length of String in bytes = 17425
INFO: Length of compressed bytes = 12890

As you can see, the JSON representation of the client now has the photograph in Base64 format in order to send the image data to the mobile client as part of the JSON String. Also notice that there is some compression in the response to the client.

On the mobile client side, there are also changes in the Client class:

import java.util.Vector;
import javax.microedition.lcdui.Image;
import org.bouncycastle.util.encoders.Base64;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

public class Client {


    /** Name of the client*/
    private String name;

    /** Constant name of the attribute name*/
    private static final String ATT_NAME = "name";

    /** Last name of the client*/
    private String lastName;

    /** Constant name of the attribute last name*/
    private static final String ATT_LAST_NAME = "lastName";

    /** Identification of the client*/
    private String id;

    /** Constant name of the attribute id*/
    private static final String ATT_ID = "id";

    /** Photo of the client*/
    private  Image photo;

    /** Photo of the client in Base 64 format*/
    private  String photoBase64;


     /** Constant name of the attribute photoBase64*/
    private static final String ATT_PHOTO_BASE_64 = "photoBase64";

    //Getters and Setters...

    /**
     * This method should be used by this class only, that's why it is private.
     * Allows to get a JSONObject from the Client passed as parameter
     * @param client Client Object to convert to JSONObject
     * @return JSONObject representation of the Client passed as parameter
     */
    private static JSONObject toJSONObject(Client client) {
        JSONObject json = new JSONObject();
        try {
            json.put(ATT_NAME, client.getName());
            json.put(ATT_LAST_NAME, client.getLastName());
            json.put(ATT_ID, client.getId());
            //only if the client has a photo associated send it as JSON
            if(client.getPhotoBase64() != null)
            {
                json.put(ATT_PHOTO_BASE_64, client.getPhotoBase64());
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
        return json;
    }

    /**
     * Allows to get a Client Object from a JSON String
     * @param jsonText JSON String to convert to a Client Object
     * @return Client Object created from the String passed as parameter
     */
    public static Client fromJSON(String jsonText) {
        Client client = new Client();
        try {
            JSONObject json = new JSONObject(jsonText);

            //check if the JSON text comes with the attribue Name
            if (json.has(ATT_NAME)) {
                //asign the String value of the attribute name to the client
                client.setName(json.getString(ATT_NAME));
            }

            //check if the JSON text comes with the attribue last name
            if (json.has(ATT_LAST_NAME)) {
                client.setLastName(json.getString(ATT_LAST_NAME));
            }

            //check if the JSON text comes with the attribue id
            if (json.has(ATT_ID)) {
                client.setId(json.getString(ATT_ID));
            }

             //check if the JSON text comes with the attribue photo
            if (json.has(ATT_PHOTO_BASE_64)) {
                client.setPhotoBase64(json.getString(ATT_PHOTO_BASE_64));


                //once the photo in base 64 format has been read,
                //convert it to an Image. IMPORTANT: PNG image format or
                //you may get an Exception
                byte[] decoded = Base64.decode(client.getPhotoBase64());
                Image img = Image.createImage(decoded, 0, decoded.length);
                client.setPhoto(img);
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
        return client;
    }
}

You can find the changes in bold. The important changes are the adition of the attributes for managing the photograph and the modification of the methods for parsing the JSON String to and from an Object. Notice the use of the org.bouncycastle.util.encoders.Base64 class to decode the Base64 format data of the photograph. You can find the original source code of the Client class (mobile client side) in the first post of this saga.

Next is the MIDlet that runs the code:

import com.tinyline.util.GZIPInputStream;
import java.io.*;
import java.util.Vector;
import javax.microedition.io.*;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;


public class JSONMIDlet extends MIDlet {


    private Form f = null;


    public JSONMIDlet() {
        //form for the photos
        f = new Form("Photo testing");
    }


    public void pauseApp() {
    }


    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }


    public void startApp() {
        try {
            //ask for the clients
            Vector clients = getClients();


            //show information of the clients
            System.out.println("*****CLIENT INFORMATION*****");
            for (int i = 0; i < clients.size(); i++) {
                Client cl = (Client) clients.elementAt(i);


                System.out.println("Client " + (i + 1) 
                                                + " name = " + cl.getName());
                System.out.println("Client " + (i + 1) 
                                                + " last name = " + cl.getLastName());
                System.out.println("Client " + (i + 1) 
                                                + " ID = " + cl.getId());
                System.out.println("Client " + (i + 1) 
                                                + " Photo Base64 = " + cl.getPhotoBase64());
                System.out.println("");


                //if the client has a photo, append it to the form
                if (cl.getPhoto() != null) {
                    f.append(cl.getPhoto());
                }
            }




            Display dsp = Display.getDisplay(this);
            dsp.setCurrent(f);




        } catch (IOException ex) {
            //manage the exception
            ex.printStackTrace();
        }
    }


...//other methods


}

The method +getClients():Vector has not changed and can be found in the last post of this saga (as there is compression/decompression support). Finally the emulator shows the following:


Well, that's it for today. Quite a large post, I hope I was clear enaugh, but if you have any questions do not hesitate to contact me.

see ya soon!


References:

TinyLine Utils. 2010. TinyLine [online].
Available on Internet: http://www.tinyline.com/utils/index.html
[accessed on December 11 2010].

Using JavaScript Object Notation (JSON) in Java ME for Data Interchange. Agosto 2008. Oracle [online].
Available on Internet: http://java.sun.com/developer/technicalArticles/javame/json-me/
[accessed on October the 26th 2010].

meapplicationdevelopers: Subversion. 2007. Oracle [online].
Available on Internet: https://meapplicationdevelopers.dev.java.net/source/browse/meapplicationdevelopers/demobox/mobileajax/lib/json/
[accessed on October the 27th 2010].

The Legion of the Bouncy Castle. bouncycastle.org [online].
Available on Internet: http://www.bouncycastle.org/
[accessed on December 28 2010].

Tuesday, December 28, 2010

Base64 encode-decode in JavaMe

I want to start this post asking: why do you think you need to encode data? At first, I didn't have a specific answer, so I googled and found some interesting answers and now I can tell you: You want to encode, because you need to transfer binary data through a channel that is designed to deal with textual data. A common example is when you need to transfer an Image inside a JSON String or in a XML message.

We will use the Bouncy Castle library to Encode/Decode binary data in Base64 format. Although this library has a lot more and can be used for Encryption/Decryption using different methods, today we will focus on the Encoding/Decoding part. You can download the library using the following link:


Make sure you download the J2ME version. When you download this version, you'll get the full source code and when you build it, you get a 1.7MB library... which may be too much for a mobile application. Anyway, with the source code you can make a build of some classes and not of all of them. That's how I made a build with only the encoders packages and classes and is just about 14KB. If you need it, just ask for it you can download it using this link.

To work with Base64 in JavaMe (J2ME) the bouncy castle library comes with the org.bouncycastle.util.encoders.Base64 class. Next is how you can use it in your MIDlet:


import org.bouncycastle.util.encoders.Base64;

...
    /**
     * As an example, encodes a String and then it decodes it.
     * Prints to console the result of the encode/decode.
     */
    public void encodeDecodeExample() {
      
        String word = "New word to encode using Base64 also special "
                + "chars like Ñ and ó";
      
        System.out.println("Encoding: ");
        System.out.println(word);
      
        byte[] coded = Base64.encode(word.getBytes());
        String strCoded = new String(coded);
      
        //prints the encoded word
        System.out.println("Result: ");
        System.out.println(strCoded);

        System.out.println("Decoding: ");
        System.out.println(strCoded);
      
        byte[] decoded = Base64.decode(strCoded);
        String strDecoded = new String(decoded);

        //prints the decoded word
        System.out.println("Result: ");
        System.out.println(strDecoded);
    }
...

When the previous code is run, the console output shows the following:




Encoding: 
New word to encode using Base64 also special chars like Ñ and ó

Result: 
TmV3IHdvcmQgdG8gZW5jb2RlIHVzaW5nIEJhc2U2NCBhbHNvIHNwZWNpYWwgY2hhcnMgbGlrZSDRIGFuZCDz

Decoding: 
TmV3IHdvcmQgdG8gZW5jb2RlIHVzaW5nIEJhc2U2NCBhbHNvIHNwZWNpYWwgY2hhcnMgbGlrZSDRIGFuZCDz

Result: 
New word to encode using Base64 also special chars like Ñ and ó


You can see that first it prints the String varible called 'word' encoded, after that it decodes the encoded word and prints the decoded word. You only need to have the byte array of data and invoke the proper methods.

This library is pretty simple to use and it gives you the power of transmit binary data as text. As we mentioned before, if you need to send, for example, an Image as text (JSON String? XML?).

This is a small part of the bouncy castle library. It has many encryption/decryption method to be used in your mobile applications. In future posts we will explore some of these methods to add security to our mobile applications.

This concludes our introduction to Base64 in JavaMe (J2ME), wait for the next post where we will use it to send images from the server to the mobile client using, once again, JSON Strings.

see ya soon!


References:

Base64. 2010. Wikipedia [online].
Available on Internet: http://en.wikipedia.org/wiki/Base64
[accessed on December 28 2010].

The Legion of the Bouncy Castle. bouncycastle.org [online].
Available on Internet: http://www.bouncycastle.org/
[accessed on December 28 2010].