JSP: how to read unicode from forms

April 6th, 2008
Are you having encoding problems while trying to read multilingual data from a JSP form? That is because JSP by default is trying to interpret your input as ISO-8859-1. That's fine unless you have a form that sendsUTF-8.

The problem can be eliminated by simply adding the following line of before you do any calls to getParameter():

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
...
request.setCharacterEncoding("utf-8");
...
}


The Bic and Bac song (video + lyrics)

March 19th, 2008
This is the video of Bic & Bac from Les Mondes Engloutis, the best cartoon ever, together with the lyrics of the song (in french!) for you to sing aloud! I wish I knew what they mean, it's all french to me :)





C'est la gigue de Bic et Bac
Bac et Bic, c'est logebic
La petite gigue du flashbic
Tralala-lala-la !

Dans la peine ou le grand bourdon
Le Flashbic, nous dansons
Dans la grande gigue d'Arkadia
Venez avec moi !

Nous sommes deux Pangolins
Qui se carapatent
Nous sommes deux gros malins
Donnons-nous la main…

Vers Arkadia, marchons sous le vent la pluie
Tout là-bas, nous sortirons de la nuit
Et le Shagma, pour nous tous il revivra
Tourneboule et tourneboule la gigue de la vie

Pour Arkadia, nous danserons tous unis
Tout là-bas, quand brillera le Shagma
Et c'est ainsi que giguent tous nos amis
Dansez, chantez, chantez, dansez la gigue de la vie

C'est la guigne pour Bic et Bac
Bac et Bic c'est tragique
Dansons la gigue du Flashbic
Tralala-lala-la !

Nostalgique ou bien grognon
Le Flashbic, nous dansons
Dans la petite ronde du Shagma
Entrez avec moi !

Nous sommes deux Pangolins
Qui se décarcassent
N'ayons plus peur de rien
Donnons-nous la main…

Vers Arkadia, marchons sous le vent la pluie
Tout là-bas, nous sortirons de la nuit
Et le Shagma, pour nous tous il revivra
Tourneboule et tourneboule la gigue de la vie

Vers Arkadia, marchons dans les pains d'épis
Tout là-bas, on sauvera le Shagma
Et que la vie nous garde bien tous unis
Tourneboule et tourneboule la gigue de la vie

Pour Arkadia, nous danserons tous unis
Tout là-bas, quand brillera le Shagma
Et c'est ainsi que giguent tous nos amis
Dansez, chantez, chantez, dansez la gigue de la vie

scanf (and why you should avoid using it)

February 7th, 2008
I believe scanf() is one of the most common pitfalls that most novice C programmers encounter. In our first steps with the C programming language we usually try to write some simple interactive programs, like a program that asks for our name ("What is your name?") and then sends some greetings in a more personalized fashion ("Hello, Giannis!"), or even some simple game.

In most books, students are encouraged to use the scanf() function as the standard method to read the user's input. And it really does a good job, as long as the input given by the user is what was expected by the author of the program. Or else, things may get a little tricky especially for the newcomer. Here is an example, a simple program that prompts the user to enter a number, and then it print out whether it was a even or an odd number. Here, our hypothetical programmer intended to apply some sort of defensive programming, and check whether the user's input was recognized as a number. The program will keep on asking until a valid number is entered:


#include <stdio.h>

int main()
{
int number, result;

do
{
printf("Give me a number: ");
result = scanf("%d", &number );
if (result < 1)
printf("You didn't type a number!\n");
}
while (result < 1);

if (number % 2 == 1)
printf("%d is odd.\n", number);
else
printf("%d is even.\n", number);
}



At first sight it looks fine. If we try to run it we'll get what we expected:


giannis@giannis-desktop:~$ ./a.out
Give me a number: 133
133 is odd.
giannis@giannis-desktop:~$ ./a.out
Give me a number: 44
44 is even.



It looks okay! But what happens if the user enters some invalid input? Let's find out:


Give me a number: abc
You didn't type a number!
Give me a number: You didn't type a number!
Give me a number: You didn't type a number!
Give me a number: You didn't type a number!
...



And it goes like this until we terminate the program with Ctrl-C. Not quite what expected, eh?

What did go wrong here? Well, let's take a step-by-step course. At first, the user is prompted to enter a number. Then scanf is called to read an integer number from standard input. The program blocks and waits for the user to type something and press Enter. After that, scanf reads the first character from standard input, which is 'a', which is not a digit. As a result, scanf puts back the character and bails out. The error message is displayed and we start all over again to ask the user for new input. However, when scanf is called on second time, it doesn't block at all, because the input buffer already contains the previously entered data. It tries once more to parse the user's input, and it fails once again, and the loop infinitely continues for ever.

It turns out that the problem here is that if some invalid input is entered, it never leaves the input buffer. What we need here is to find a solution, so that the user input is always taken off from the input buffer, either when it is valid or not. The "proper" way to achieve this, is to first read a whole line of input into a temporary buffer using fgets(), and then parse the buffer using sscanf(), a close-cousin of scanf(). This is how it will look like:


...
do
{
printf("Give me a number: ");
char st[1024];
fgets( st, sizeof(st), stdin );
result = sscanf(st, "%d", &number );
if (result < 1)
printf("You didn't type a number!\n");
}
while (result < 1);
...



And now let's try to test the new improved version of the program:


giannis@giannis-desktop:~$ ./a.out
Give me a number: rfdasf
You didn't type a number!
Give me a number: fasfdsfgsd
You didn't type a number!
Give me a number: 25
25 is odd.



Now we got somewhere, didn't we? Another, less elegant, way to solve the same problem would be to still use scanf() but also meticulously take care to remove the invalid line of data from the buffer. In C-terms, that would be:


...
do
{
printf("Give me a number: ");
result = scanf("%d", &number );
if (result < 1)
{
printf("You didn't type a number!\n");
char st[1024];
fgets( st, sizeof(st), stdin );
}
}
while (result < 1);
...



But as I said before, I personally find this version kind of ugly, because, we are using fgets() only to read and ignore a whole line from the input buffer, which is something we can avoid if we use sscanf().

I believe most C programmers have been puzzled at their first steps, and I hope that these little headaches will not discourage new programmers from continueing their efforts. For these efforts will be greatly rewarded!

X11 development files in Ubuntu

February 6th, 2008
If you tried to compile a X11 application in Ubuntu you may get error messages that several X11 related header files were missing (such as Xlib.h). The files you need are contained in the libx11-dev package. Type this command to install it:

sudo apt-get install libx11-dev

and then try again to build the application.

How to get rid of the "Share-to-Web Upload Folder"

January 30th, 2008
If you have a Hewlett Packard ScanJet you probably have been annoyed by this stupid HP Share-to-Web Upload Folder that has been settled in your Desktop. There seems to be no obvious way to remove it or delete it, and if you try to right-click on it the Windows Explorer hangs and you have to restart it.

Here is what you have to do to send it from where it came:

Go to Start → Settings → Control Panel → Add or Remove Programs. After the list is populated find and highlight the program named HP Photo and Imaging. Then push the Change button. The InstallShield Wizard will show up. Click Next and then select Repair. Click Next again. In the next step make sure that you DON'T check the Add a Shortcut to the Desktop checkbox. Finally click Install. By the end of the procedure you should see the evil icon missing from your Desktop.

install developer's man pages on ubuntu

January 28th, 2008
To install the valuable man pages for development in your Ubuntu box, simply do:

sudo apt-get install manpages-dev

This will install the man pages that "describe the Linux programming interface". They include the Linux system calls (section 2) and library functions (section 3).

Ubuntu: mouse pointer is randomly disappearing

December 20th, 2007
Problem:
Lately you have noticed that your mouse pointer disappears occasionally, or flickers while you move it along the screen, in a fairly random fashion. You may have also noticed that this is mostly happening while Firefox is in the process of loading a page. Sometimes you may also get stuck with an animated mouse pointer, which is fixed only by restarting the X windows system.

Cause:
A bug in the Enhanced Zoom Desktop plugin of CompizFusion.

Solution:
Go to System → Preferences → Advanced Desktop Effects Settings. Click on Enhanced Zoom Desktop and then select the Mouse Behavior tab. Make sure that you have not checked the options Scale the mouse pointer and Hide original mouse pointer. (Yes, you will have to live without those two cool features if you want to get rid of the missing mouse pointer problem). Close the settings manager and restart X.

How to retrieve INSERT-generated IDs with JDBC.

December 17th, 2007
The answer is very simple. You just have to call the getGeneratedKeys() method of your statement object, right after its execution.

The getGeneratedKeys() method will return a ResultSet object that contains any keys that was generated by the execution of your statement.

Let's see a simple example. Assume the following MySQL table:

mysql> show fields from Person;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100)     | NO   |     |         |                |
+-------+------------------+------+-----+---------+----------------+


This is the code that will insert a row into this table. We do not provide a value for id, because it is an AUTO_INCREMENT field; MySQL will automatically assign a unique value for this field.

String sql = "INSERT INTO Person (name) VALUES ( ? )";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,"Giannis");
statement.execute();

ResultSet rs = statement.getGeneratedKeys();
rs.next();
int personId = rs.getInt(1);
rs.close();

statement.close();


After the execution of the statement, we call getGeneratedKeys() to get the ResultSet to get the value that automatically was generated for the id field. We call next() to read the first line of the result set, and then we read the first column, which we expect to be an integer.

How to get the files of a package on Ubuntu

December 8th, 2007
To get the list of the contents of an installed package on Ubuntu, try this command:

dpkg -L package-name

or alternatively:

dpkg --listfiles package-name

For the reverse action, that is, to find which package a file belongs to, try this command:

dpkg -S file-pattern

or alternatively:

dpkg --search file-pattern

Replace file-pattern with part of the filename you're searching for, or even the full path.

For example, we will find out which package contains the file /usr/share/java/servlet-api-2.4.jar:

giannis@giannis-desktop:~$ dpkg -S /usr/share/java/servlet-api-2.4.jar
libservlet2.4-java: /usr/share/java/servlet-api-2.4.jar


The package we're looking for, is: libservlet2.4-java

Get stack trace information in Java programs.

December 7th, 2007
Sometimes it could be useful to get the current stack trace while a Java program is being executed.

As of my limited knowledge, I don't know a direct way to get the stack trace, but sometimes the solution is right in front of your eyes.

This code will print the stack trace at any point of your proram:

StackTraceElement[] elements = new Throwable().getStackTrace();
for (int i = 0; i < elements.length; i++)
System.out.println(elements[i]);


Or using for-each:

for (StackTraceElement element : new Throwable().getStackTrace())
System.out.println(element);


Or even simpler you can just call printStackTrace() if you only want to print the stack trace in standard error:

new Throwable().printStackTrace();

Note that we are not actualy throw a Throwable. We only create a Throwable object which contains the information we want.