Wednesday, August 13, 2008

iCal and Google Calendar

Here the how-to explaining how to interact with GoogleCalendar using iCal and the CalDAV support provided by Google.
GiCal!

Monday, August 4, 2008

Java: component to display images from a byte array

In some situation there might be the need of displaying images received through a byte array (e.g. the image is sent using a socket). The solution is pretty simple. With the following code you can easily create a Component which can display images (e.g. JPEG, GIF) from a byte array. Then you just need to add this component to your GUI.
class ImageComponent extends JPanel
{
    public ImageComponent() {}
        
    public ImageComponent (byte[] image)
    {
        ByteArrayInputStream bis = new ByteArrayInputStream (image);
        try {
            _image = ImageIO.read (bis);
        }
        catch (IOException ex){}
    }
        
    //This method replaces the image displayed by the component
    //with a new one passed in the image byte array.
    public void updateImage (byte[] image)
    {
        ByteArrayInputStream bis = new ByteArrayInputStream (image);
        try {
            _image = ImageIO.read (bis);
        }
        catch (IOException ex){}
        repaint();
    }
        
    public void paint(Graphics g)
    {
        g.drawImage(_image, 0, 0, null);
    }
        
    public Dimension getPreferredSize()
    {
        if (_image == null) {
            return new Dimension (320, 240);
        } else {
            return new Dimension (_image.getWidth (null), _image.getHeight (null));
        }
    }
        
    BufferedImage _image;
}

Wednesday, July 30, 2008

Tutorial: grab images from a network camera using Java

Requirements: a network camera with a web interface. The web interface should make available somehow a dynamically generated JPEG image. For the implementation we will use the Apache commons, available here. In particular we need the http-commons-client, the commons-logging and the commons-codec. The http-commons-client is what we really need, the other two packages are dependencies for the commons-client.

To run the program you need to have the JAR files included in the tar.gz archives in the Java classpath.

First of all we need to know the URL to get the image from the camera. In my case it was something like http://xxx.yyy.www.zzz/cgi-bin/video.jpg?size=3. Now we are ready to write the code.
//NetworkCamera class

import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class NetworkCamera
{
    public NetworkCamera (String url)
    {
        log ("Registered network camera. Image url = " + url);
        _method = new GetMethod(url);
        //Create the HTTP client and set the parameters
        _client = new HttpClient();
        _client.getParams().setParameter ("http.useragent", "CustomizedJavaClient");
        _client.getParams().setParameter ("http.connection.timeout", new Integer(5000));
        _method.setFollowRedirects (true);
    }
    
    
    public byte[] getImage ()
    {
        log ("Getting image...");
        byte[] image = null;
        try {
            int retCode = _client.executeMethod (_method);
            if ( retCode != -1){
                log ("getMethod succeed [HTTP-RESPONSE-CODE" + retCode + "]. Content lenght = " + _method.getResponseContentLength());
                //The HTTP response body contain the bytes of the image
                image = _method.getResponseBody();
                System.out.println ("Bytes read: " + image.length);
            }
        }
        catch (IOException ex) {
            //Report error
            System.out.println (ex.getMessage ());
        }  
        return image;
    }
    
    private void log (String message)
    {
        if (DEBUG) {
            System.out.println (message);
        }
    }
    

    private GetMethod _method;
    private HttpClient _client;
    
    private static final boolean DEBUG = true;
}

//Main class (for test purpose)

import java.io.FileOutputStream;

public class Main
{
    public static void main (String[] args) throws Exception
    {
        Camera cam = new NetworkCamera (CAMERA_IMAGE_URL);
        byte[] image = cam.getImage();
        
        FileOutputStream fos = new FileOutputStream (IMAGE_FILE_NAME);
        fos.write(image);
        fos.close();
    }
    
    private static final String CAMERA_IMAGE_URL = "http://xxx.yyy.www.zzz/cgi-bin/video.jpg?size=3";
    private static final String IMAGE_FILE_NAME = "test.jpg";
}

The code gets a frame from the camera as a JPEG file and saves it as test.jpg.
Of course you may use exactly the same code to grab an image from a web site. You can try, for instance, to assign
private static final String CAMERA_IMAGE_URL = "http://www.google.com/intl/en_ALL/images/logo.gif"
and see what happens.

Thursday, July 24, 2008

Object to byte array and byte array to Object in Java

Here how to convert an Object to a byte array, and vice-versa.
public byte[] toByteArray (Object obj)
{
  byte[] bytes = null;
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    ObjectOutputStream oos = new ObjectOutputStream(bos); 
    oos.writeObject(obj);
    oos.flush(); 
    oos.close(); 
    bos.close();
    bytes = bos.toByteArray ();
  }
  catch (IOException ex) {
    //TODO: Handle the exception
  }
  return bytes;
}
    
public Object toObject (byte[] bytes)
{
  Object obj = null;
  try {
    ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
    ObjectInputStream ois = new ObjectInputStream (bis);
    obj = ois.readObject();
  }
  catch (IOException ex) {
    //TODO: Handle the exception
  }
  catch (ClassNotFoundException ex) {
    //TODO: Handle the exception
  }
  return obj;
}

Tuesday, July 22, 2008

Extract EXIF Metadata from JPEG files using Java

I was looking into this problem for a project I am working on, and I found this cool library.


Here some usage examples.

Sunday, July 20, 2008

Blogger Hacks

The first thing I wanted to do as soon as I created this blog was to remove the blogger bar on top of the pages.

I googled for a while and I found the solution in here. The hack is really simple, you have just to insert a new CSS rule just before the "Variable definitions" in the HTML code of your template:
#navbar-iframe
{
display: none !important;
}
The !important keyword prevent the property from being overwritten from the rules inserted by the blogger engine.

Thursday, July 17, 2008

UDP Server Socket using Java

The following simple example shows how to open a UDP server socket using Java. The code receives strings from a UDP socket and print them in the standard output.
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.DatagramPacket;

public class SimpleUDPSSocket extends Thread
{
public SimpleUDPSSocket() throws Exception
{
_dSocket = new DatagramSocket(PORT);
_running = false;
}

public void run()
{
byte buf[] = new byte[MAX_SIZE];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
String data;
_running = true;
while (_running) {
try {
_dSocket.receive (packet);
}
catch (Exception ex) {
_running = false;
break;
}
data = new String(packet.getData(), 0, packet.getLength());
System.out.println (data);
}
}

private DatagramSocket _dSocket;
private boolean _running;
private static final int PORT = 4444;
private static final int MAX_SIZE = 64;
}


Wednesday, June 4, 2008

Office 2008 for Mac: reset the licence number

If for some reason you need to reset your Office 2008 for Mac license number, the simple script below is what you need. Just copy and paste it in your favorite text editor, save it as "reset_office_license.sh", open a terminal window, cd in the directory where you saved it, give it the execution permission (chmod +x reset_office_license.sh) and run it (./reset_office_license.sh). The script might need superuser permissions to run correctly.

#!/bin/bash
# Author: Massimiliano Marcon
# Description: this script resets the Microsoft Office 2008 for Mac licence number.

DEFAULT_OFFICE_PID_LOCATION="/Applications/Microsoft\ Office\ 2008/Office/OfficePID.plist"
DEFAULT_OFFICE_SETTING_LOCATION="~/Library/Preferences/Microsoft/Office\ 2008/"

function reset () {
mkdir /tmp/backup-office-licence
mv $DEFAULT_OFFICE_PID_LOCATION /tmp/backup-office-licence
mv $DEFAULT_OFFICE_SETTING_LOCATION/Microsoft\ Office\ 2008\ Settings.plist /tmp/backup-office-licence
mv $DEFAULT_OFFICE_SETTING_LOCATION/Office\ Registration\ Cache\ 2008 /tmp/backup-office-licence
echo "Done. Restart Microsoft Office and insert the new serial number."
}

function question () {
echo -n "Would you like to reset your Microsoft Office Licence Key now? (yes/no) "
read RESPONSE
case "$RESPONSE" in
yes)
#Reset process
reset
#End reset process
;;
no)
echo "Nothing to do, exiting."
;;
*)
echo "Please type \"yes\" or \"no\""
question
;;
esac
}

echo "[Resetting your Microsoft Office Licence Key...]"
echo "*** All the files will be moved in /tmp ***"

question

exit 0