• Making Eclipse in Ubuntu 10.4 to use Sun Java as default JRE
    May 14, 2010

    Even after completing procedures in my previous post for setting up Sun JRE, Eclipse still had OpenJDK as java runtime. Therefore we need to make Eclipse find Sun JRE and set it up as default JRE.

    Go go Window -> Preferences and click on Java-> Installed JREs. By default you will only see OpenJDK installed. Click Search and select /usr folder to be searched for JREs, since Sun JRE is installed in that folder. Searching will take some time, and after that it found 7 new JREs for me.

    This is because /usr/lib64 in symbolic link to /usr/lib, so 4 of JREs it found were duplicates of 3 new JREs and one old OpenJDK. We can immediately remove duplicates, they will usually be marked with "(1)" in the end of their names.

    Out of remaining four JREs, one is Sun JRE (the one we have been desperately looking for), 32 bit Sun JRE and two of them are OpenJDKs. Again browsing file structure we see that /usr/lib/jvm/java-1.6.0-openjdk is a symbolic link to /usr/lib/jvm/java-6-openjdk, thus we can get rid of that one too.

    Now we click on checkbox of Sun JRE making it default JRE and we are done.

  • Complete guide to organizing a Google Web Toolkit project with Eclipse plug-in.
    May 12, 2010

    GWT projects can get very complex by the time and therefore it gets very important to organize them properly from the beginning so that working with them would be as painless as possible.

    Both Google Web Toolkit and Google Plugin for Eclipse provide rich features and capabilities for creating applications. But here I came up with few practices for getting the most out of them. In this tutorial, I will be creating a sample project step by step on my work PC, which has Ubuntu 10.4, Eclipse 3.5, Google Web Toolkit SDK 2.0.3 and Google AppEngine SDK 1.3.3 as of this writing. Similar steps can be achieved in other operating systems without any significant effort.

    1. Installing and configuring necessary tools First of all install Eclipse and Google Plugin for Eclipse (google plugin from here on) if you have not yet done so by instructions provided here. After this you need to install GWT and optionally AppEngine SDKs. You could download and install them separately, but since google plugin installs those SDKs with itself, there is no need to do that.

      Instead of that we will be creating a symbolic link to the installation folder of GWT SDK coming with google plugin. Its name and path is usually long, and changes from version to version when there is an update. In my case I have a manual install of Eclipse (well, just downloading it from the official website, unpacking and running) which is under /home/elchin/programs/eclipse, so I will try to see which plugins are installed under google name. Plugins go to plugins/ folder inside eclipse, and their naming convention is similar to Sun's java packaging name convention - reverse domain based. Thus, names of google plugins start with com.google. After looking inside plugins/ folder, I found that GWT plugins have names starting with com.google.gwt.eclipse.sdkbundle. After that I do ls eclipse/plugins/com.google.gwt.eclipse.sdkbundle.* and find out that I have 3 GWT installations, which is indeed true, and in each of them there is gwt-[version] folder, which is GWT SDK that I am looking for. I create a symbolic link from /home/elchin/programs/gwt pointing to there.

    2. Creating GWT Project

      Now that we are done with setting up the GWT SDK, we will create a GWT project. It is possible to create GWT project from Eclipse, which has a very convenient wizard for it. But the biggest drawback I found about it was that it did not create ant buildfile, which makes it harder to compile projects from console. You don't need it on daily basis, but it did happen to me that I needed to remotely access my machine from home and then compile GWT project, so it would be very useful for me to have a buildfile already being there so that I could just invoke ant. (You can find more on compiling GWT project in here

      Therefore we are going to take advantage of both of these approaches and combine them in one. First we are going to create GWT project from Eclipse with AppEngine optionally enabled, and then we are going to separately create GWT project with the same name and package structure from command line in temporary folder, and then copy build.xml file to our main project.

      Creating project from Eclipse is pretty straightforward. To create project from command line go to GWT SDK folder and invoke webAppCreator:

      ~/programs/gwt/webAppCreator -out TestGWT net.asgarli.testgwt.TestGWT

      If webAppCreator is not executable, chmod it:

      chmod +x webAppCreator

      Note that I skipped junit parameter, you can optionally add it for JUnit support. Yuo can find more about webAppCreator and its arguments in here: http://code.google.com/webtoolkit/doc/latest/tutorial/create.html

      Now we need to copy build.xml file generated in this project into our main project in Eclipse. Thus I am going to do

      cp TestGWT/build.xml ../../workspace/TestGWT/

      and then refresh project in Eclipse (by pressing F5) to see build.xml included in project. If everything done correctly there should be no problem with paths, since both of projects will be referencing same SDK. However it is very important to get package and project names correct.

    3. Running and deploying

      We are ready to deploy! There are two ways now to run your GWT Project, one would be from google plugin, and other way would be calling ant devmode from console. While google plugin is quite convenient for running, I still prefer the old way of launching webapp where hosted mode would open separate window to keep development screen in Eclispe cleaner. Another reason was that I had a bug in the plugin that 'stop' button was disappearing from time to time and I could not terminate the launch.

      But I also do not like the fact that I will have to always to go console to type ant devmode. Luckily for us Eclispe allows launch of ant buildfiles, so we are going to make use of this feature.

      Find build.xml file in project, and right click on it and select 'Run As' and click on 'Ant Buildfile...'. This will open you a configuration screen that will allow you to select targets to run. I created two of such configurations, one having 'build', and the other having 'devmode' targets selected. I named them 'COMPILE TestGWTProject' and 'DEVMODE TestGWTProject' respectively. Now I have launches for compilation and running in development mode which I can painlessly use.

    4. CVS/SVN integration

      Almost all of projects that you are going to be working with in a collaborative environment will require you to share your project in some kind of versioning system. I am going to do it on CVS server which I have installed on my machine, but similar steps can be done with any other versioning systems including SVN.

      First you need to share the project in Eclipse, so right click on the project, Team -> Share Project. I already have my cvs parameters configured, so I am going to make use of them. After configuring everything (how to do that is out of scope of this tutorial), proceed to sharing the project, but be sure NOT TO COMMIT ANYTHING yet!

      We are skipping this step in here, because we will need to add output files of GWT compilation to .cvsignore (or .svnignore). Compilation results go to war/[project-name-with-small-letters] folder, so in my case it was war/testgwt. Right click on it, Team -> Add to .cvsignore. Other things we could to add to .cvsignore are gwt-servlet.jar file in war/lib and all other library files from AppEngine if they are there, because Google Plugin adds them automatically, so you do not need to version/update them.

    Happy coding!

  • Installing Sun Java Runtime Environment (JRE) and Sun Java Development Kit (JDK) on Ubuntu 10.4 Lucid Lynx
    May 5, 2010

    For some reason Ubuntu has decided to exclude Sun Java from their default repository in favor of OpenJDK. With version 10.4 of Ubuntu, Sun Java is only included in a partner repository, so in order to be able to install it instead of OpenJDK, we need to include that partner repository as a software source in aptitude, install sun-java packages and then select Sun Java as default java execution environment.

    Here is the procedure to follow:

    Open shell and execute command

    sudo add-apt-repository "deb http://archive.canonical.com/  lucid partner"

    This will add the partner repository we need. After that you need to update the package list :

    sudo apt-get update

    Now after this if you search for sun-java, you will see it being included in package list :

    [elchin@asgarli ~] $ sudo apt-cache search sun-java
    sun-javadb-client - Java DB client
    sun-javadb-common - Java DB common files 
    sun-javadb-core - Java DB core
    sun-javadb-demo - Java DB demo
    sun-javadb-doc - Java DB documentation
    sun-javadb-javadoc - Java DB javadoc
    sun-java6-source - Sun Java(TM) Development Kit (JDK) 6 source files
    sun-java6-jre - Sun Java(TM) Runtime Environment (JRE) 6 (architecture independent files)
    sun-java6-javadb - Java(TM) DB, Sun Microsystems' distribution of Apache Derby
    sun-java6-fonts - Lucida TrueType fonts (from the Sun JRE)
    sun-java6-plugin - The Java(TM) Plug-in, Java SE 6
    sun-java6-jdk - Sun Java(TM) Development Kit (JDK) 6
    sun-java6-demo - Sun Java(TM) Development Kit (JDK) 6 demos and examples
    sun-java6-bin - Sun Java(TM) Runtime Environment (JRE) 6 (architecture dependent files)
    ia32-sun-java6-bin - Sun Java(TM) Runtime Environment (JRE) 6 (32-bit)

    Time to finally install it! In addition to JRE, I also need JDK, sources and 32 bit runtime environment, so I did

    sudo apt-get install sun-java6-jdk sun-java6-source ia32-sun-java6-bin

    After this Sun Java will be downloaded and installed on your system. Now in order to confirm the version of Java being used, do

    java -version

    which should normally tell you that you are currently using Sun Java, but in my case it told me that I am still using OpenJDK.

    [elchin@asgarli ~] $ java -version
    java version "1.6.0_18"
    OpenJDK Runtime Environment (IcedTea6 1.8) (6b18-1.8-0ubuntu1)
    OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)

    This means I will need to explicitly tell Ubuntu to use Sun Java. We do that using update-alternatives utility:

    sudo update-alternatives --config java

    And after that choose number corresponding to Sun Java, 64 or 32 bit depending on what would you prefer to be default. I choose 64 bit:

    There are 3 choices for the alternative java (providing /usr/bin/java).
    Selection  Path                    Priority  Status
    * 0      /usr/lib/jvm/java-6-openjdk/jre/bin/java  1061   auto mode
    1      /usr/lib/jvm/ia32-java-6-sun/jre/bin/java  63    manual mode
    2      /usr/lib/jvm/java-6-openjdk/jre/bin/java  1061   manual mode
    3      /usr/lib/jvm/java-6-sun/jre/bin/java    63    manual mode
    Press enter to keep the current choice[*], or type selection number: 3
    update-alternatives: using /usr/lib/jvm/java-6-sun/jre/bin/java to provide /usr/bin/java (java) in manual mode.

    Again we test our version :

    [elchin@asgarli ~] $ java -version
    java version "1.6.0_20"
    Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
    Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)


  • GNU Screen cheatsheet
    May 4, 2010

    GNU Screen is an open-source terminal multiplexer which allows you to open multiple terminals sessions inside a single terminal. It also allows you detach and attach sessions, which means you can log out of the system and still have your programs running. There are a lot of GNU screen tutorials all around, so I did not feel like creating another one, instead I composed a cheatsheet which will summarize GNU screen commands.

    screen -ls -> list screen sessions

    screen -r SESSION -> reattach screen session, SESSION can be PID or name.

    CTRL + a c -> create new window

    CTRL + a A -> set window name

    CTRL + a w -> show all window

    CTRL + a p -> switch to previous screen

    CTRL + a n -> switch to next screen

    CTRL + a 0..9 -> switch to window 0..9

    CTRL + a " -> choose window

    CTRL + a CTRL + a -> switch between windows, like alt+tab in Windows.

    CTRL + a d -> detach session, processes running in session still run in background even if you log out

    Scrolling: CTRL + a [ -> start copy mode, similar to visual mode in vim. Move cursor to the beginning of copy location, press ENTER to start selecting, press ENTER again to copy the selected text to the buffer

    CTRL + a ] -> paste from buffer

    Split screens. When you create split screen it lets you to see many of windows that you created. There is only a single list of windows created, you don't have separate window lists for each split screens: CTRL + a S -> create split screen.

    CTRL + a X -> close current split screen

    CTRL + a Q -> close all split screens but current one

    CTRL + a TAB -> switch between split screens

  • How to remove Navbar in Blogger Template Designer
    Apr 19, 2010

    The old way of removing Blogger Navigation bar does not work anymore with new Blogger Template Designer. Here is the new way which worked for me on this blog :

    1. Go to Dashboard > Layout > Edit HTML

    2. Find the code that starts the template definition, it should be similar if not the same to this :

      Blogger Template Style
      Name:     Picture Window
      Designer: Josh Peterson
      URL:      www.noaesthetic.com
      ----------------------------------------------- */
    3. Add the following code right below the place you found the code above:

      #navbar {
         display: none !important;
         height: 0px;
      #navbar-iframe {
         display: none !important;
         height: 0px;

    I have tried adding it to the end of the template, but it did not work, so you do need to add it to the beginning. I also tried removing visibility, display or height attributes, and figured out that you need all three of them for the trick to work. For some blogs which have white or black (depending on color of Navbar) backgrounds, not putting height: 0px will also work, but for the blogs where you have picture or texture backgrounds, there will be a stripe in the color of Navbar on top of the page.

    I am not sure whether you need both navbar and navbar-iframe styles, but I added them both because I could not test it in browsers not supporting iframes.

  • UTF-8 encoding problem (and solution) with MySQL on Ubuntu Karmic Koala 9.10
    Apr 12, 2010

    Ubuntu by default is installed with utf-8 support for default locale, and it encourages usage of utf-8, but for some reason mysql in ubuntu is installed with latin1 charset. I observed it when utf-8 characters were not displaying properly in GWT application I wrote, and investigating to the issue, I figured out that it was mysql problem.

    We can see this when we invoke status command in mysql default installation :

    mysql> status
    mysql  Ver 14.14 Distrib 5.1.37, for debian-linux-gnu (x86_64) using  EditLine wrapper
    Connection id:          107
    SSL:                    Not in use
    Current pager:          stdout
    Using outfile:          ''
    Using delimiter:        ;
    Server version:         5.1.37-1ubuntu5.1-log (Ubuntu)
    Protocol version:       10
    Connection:             Localhost via UNIX socket
    Client characterset:    latin1
    Server characterset:    latin1
    UNIX socket:            /var/run/mysqld/mysqld.sock
    Uptime:                 12 days 16 hours 25 min 44 sec

    In addition to this there are also character set properties for databases, tables and connection, and connection character set is calculated from server and client character set properties.

    So in order to achieve full utf-8 support, we need to do the following :

    1. set server character set to utf-8
    2. set database character set to utf-8
    3. set character sets of tables to utf-8
    4. set character set of mysql client to utf-8

    To perform steps 2 and 3 you need to add respective commands into create statements of tables and databases.

    In order to set encoding property of mysql server to utf-8, you have to edit the configuration file residing by default in /etc/mysql/my.cnf, and the following line under both [mysqld] and [client], and then restart the server :


    Adding this will also automatically set all other server variables related to character sets to utf8. The output of status command after the restart is following:

    mysql> status
    mysql  Ver 14.14 Distrib 5.1.37, for debian-linux-gnu (x86_64) using  EditLine wrapper
    Connection id:          52
    SSL:                    Not in use
    Current pager:          stdout
    Using outfile:          ''
    Using delimiter:        ;
    Server version:         5.1.37-1ubuntu5.1-log (Ubuntu)
    Protocol version:       10
    Connection:             Localhost via UNIX socket
    Client characterset:    utf8
    Server characterset:    utf8
    UNIX socket:            /var/run/mysqld/mysqld.sock
    Uptime:                 3 min 20 sec

    We can also output some server variables:

    mysql> show variables;
    | Variable_name                           | Value                                                                                     |
     character_set_client                    | utf8                                                                                      |
    | character_set_connection                | utf8                                                                                      |
    | character_set_database                  | utf8                                                                                      |
    | character_set_filesystem                | binary                                                                                    |
    | character_set_results                   | utf8                                                                                      |
    | character_set_server                    | utf8                                                                                      |
    | character_set_system                    | utf8                                                                                      |
    | character_sets_dir                      | /usr/share/mysql/charsets/                                                                |
    | collation_connection                    | utf8_general_ci                                                                           |
    | collation_database                      | utf8_general_ci                                                                           |
    | collation_server                        | utf8_general_ci

    I removed unnecessary variables for readability.

    Here are various links on the issue, they also contain tables for collations and character encodings, which helped me to figure out that German umlaut (ü) is C3BC in utf-8 and thus becomes ü in latin1 (à - C3, ¼ - BC).

    http://www.collation-charts.org/mysql60/mysql604.latin1_general_ci.html - chart of latin1 encoding with case insensitive general collation.

    http://www.collation-charts.org/mysql60/mysql604.utf8_general_ci.european.html - chart of utf-8 encoding with case insensitive general collation.

    http://en.wikipedia.org/wiki/UTF-8 - information about utf-8 encoding

    http://java.sun.com/docs/books/tutorial/i18n/text/stream.html - java and text encoding

    http://www.itsolut.com/chrismusings/2009/06/05/gwt-utf-8/ - blog post about utf-8 in GWT

    http://issues.appfuse.org/browse/APF-708 - here I found the simple solution for setting server and client charsets to utf8

  • My preparation notes for SCJP 6
    Apr 1, 2010

    These are the notes I made while preparing for SCJP exam. Not very structured, but these were the key points I wanted to cram right before the exam. Download in MS Word or PDF. Enjoy!

    Java keywords: abstract, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while, assert, enum.

    Identifiers can start with letter, currency characters ($,€, etc.), _. Can contain number, cannot start with number.

    Getter : getPropertyName, for booleans isPropertyName.
    Listener : addMyListener, removeMyListener

    All methods are forcefully abstract and public.
    All variables are public static and final, i.e. you can only declare constants in an interface, no instance variables.
    Methods cannot be static, strictfp, final or native (because they are abstract). public modifies is required, because it can also be default package access.

    Protected members and methods have package-level access as well as parent-child access. Default members and methods have only package access.

    Argument: The things you specify between the parenthesis when you are invoking a method.
    Parameters: The things in method's signature that indicate what the method must receive when it is invoked.

    strictfp - in methods causes floating point to adhere to IEEE 754 standard, no matter the underlying platform.

    Varargs: must be last parameter and there can be only on var-arg in a method. Examples:

    void doStuff(int... x); // 0 to many ints as parameter
    void doStuff(char c, int... x):
    void doStuff(Animal... a);

    void doStuff(int x...);
    void doStuff(int... x, char... y);
    void doStuff(String... s, byte b);

    Constructors cannot be static, final or abstract.

    Data types:
    byte - 8 bits
    short - 16 bits
    int - 32 bits
    long - 64 bits
    float - 32 bits
    double - 64 bits
    char - 16 bits
    size of boolean is VM dependent.
    sign bit is leftmost bit.

    Instance variables cannot be marked static, because then they become class variables.

    Local variables can only have final as modifier. They have to be initialized before attempted to be used. Otherwise there will be a compile error because local variables are not initialized to their default values, unlike instance variables.

    public class A{
        int in;
        public A(int in) {
            in = in; // no effect
            this.in = in; // will do what we assumed

    If you mark an instance variable transient, you tell JVM to skip it when you serialize the object.

    Volatile modifier tells JVM that a thread accessing it must reconcile its own private copy of the variable with the master copy in memory.

    Static methods and variables.
    Things you can make static:
    - Methods
    - Variables
    - A class nested within another class, but not withing a method.
    - Initialization blocks.

    Things you cannot make static:
    - Constructors
    - Classes (unless they are nested)
    - Interfaces
    - Method local inner classes.
    - Inner class methods and instance variables.
    - Local variables

    You cannot declare enums in a method.

    Java history (what appeared in which version):
    enums - java 5
    generics - java 5
    var-args - java 5
    function to return subtype of return type - java 5
    using Boolean in if(Boolean) - java 5
    switch evaluate enum - java 6
    assertions - java 4

    final and volatile modifiers don't go together.

    Java objects that pass more than one IS-A test are polymorphic, so all classes except Object are polymorphic.

    On runtime only instance methods are dynamically invoked, not variables or static methods.

    Overloading method can return subtype since java 5.

    Object casting can look up multiple inheritance tree levels.

    Casting interfaces always works until class is not final

    If A knows about the way B was implemented, its tight coupling, which should be avoided. The looser coupling is, the better it is.
    Cohesion is a degree of how a class has a single well-focused purpose. The higher the cohesion, the better it is.

    Octal literals : int nine = 011; // zero in front!
    Hex : 0xDeadCaFe
    Long: long a = 55L; // L or l at the end
    Floating point literals are double by default, so if you want them to be float, add F/f to the end.
    Literal integer is always int by default.
    Calculation of int-or-small expressions is always int

    Primitive casting:
    float -> int - explicit
    int -> double - implicit
    long -> double - implicit
    double -> int - explicit, all digits after dot are lost.

    long l = 130L;
    byte b = (byte) l;
    System.out.println(b); //prints -126

    byte = 3; b+=7;
    compound assignment operations cast automatically.

    Array elements are always initialized to their default values.

    Multi-dimensional arrays = multi-objects.

    primitive arrays cannot be reassigned to different type, object arrays can:
    int a[] = new char[2]; // NO
    Object objs[] = new String[4]; // Ok

    Wrappers are IMMUTABLE.

    Except char, all wrappers have 2 constructors.
    Integer i1 = new Integer(42);
    Integer i2 = new Integer("42");
    For Boolean, "true" in all cases is true, else false.

    Methods of wrappers:
    primitive xxxValue() - convert wrapper to primitive
    primitive parseXxx(String) - convert String to primitive
    Wrapper valueOf(String) - convert String to Wrapper

    Following wrapper object pass == test:
    Character from \u0000 to \u007f (127).
    Short and Integer from -128 to 127

    Argument matching while overloading:
    Widening beats boxing
    Widening beats var-args
    Boxing beats var-args
    Wrappers don't widen!
    You can't widen and box
    You can unbox and widen.
    These are made in a way that old code would not be behaving differently (widening is older concept, so it beats boxing and var-args which are newer)

    Signature of finalize method : protected void finalize() throws Throwable {}

    instanceof operation on null is always false.

    switch can evaluate : short, int, char, byte, enum
    cannot evaluate : long, float, double, Objects
    case has to be compile-time constant, so :
    final int a = 1; // Ok for using in case
    final int b;
    b = 1; // NOT Ok for using in case
    if enum is used, you need only the name of constant, not the name of enum. So MY_ENUM_INSTANCE instead of MyEnum.MY_ENUM_INSTANCE.

    byte b = 2;
    switch (b) {
    case 23:
    case 128: // compile error, compiler knows that 128 is not a byte.

    If a directory is missing, file creation will throw exception

    You can't delete a directory if it is not empty. You can rename it though.

    renameTo takes File as an argument.

    File.list() returns array of Strings.

    Console.readLine("%s", "input:"); // just syntax memo

    Console.readPassword returns char array.

    Object o;
    o = /*cast necessary here if not Object*/ is.readObject();

    java.io.NotSerializableException is thrown at runtime if object is not serializable.

    serialization method signatures:
    private void writeObject(ObjectOutputStream os) {
    private void readObject(ObjectInputStream is) {

    regular expressions:

    • \d digit
    • \s space
    • \w letter, digit, _

    subset, submap, tailmap, etc. by default INCLUDE. And all of these methods are creating BACKED collections!

    Collections.reverserOrder(/optionally Comparator here/) returns reverse Comparator.

    wait, notify, notifyAll have to be invoked only from synchronized context, where you have lock for an object.

    Garbage collection: while counting how many objects get garbage collected, pay attention to what is inside classes.

    Array casting - exception, not a compile error.

    System.out.println() on enum gives its reference, not name.

    class A{
            index = 4; // this works, no compile error
        int index;

    equals for wrappers return true only if types are equal too.

    PriorityQueue: add() and offer() do the same. peek() returns first value pool() returns and removes.

    float calculations result in float. TreeSet - watch for objects inserted there to be Comparable!

    For anonymous inner classes, ";" must come right after }, otherwise compile error will be in the same line as }

    In order for main() method to use inner class it must be static, because main is also static! If inner class is not static, you need to make an instance of outer class. <-- watch for this in exam.

    javac has no -D option.


subscribe via RSS