15 January 2011

[ANN] Moving my blog - Take 2

Some of my feed subscribers notified me that the new rss feed of my blog does not work. Sorry about that. Finally I have managed to get it up and running. Please try to subscribe again. It will work now.

27 December 2010

[Newbie] NullPointerException when calling findViewById

Well this one really took me quiet some time to solve it. When ever I called findViewById whitin my Activity I got a bloody NullPointerException :(

Here is the code that causes the NullPointerException.

public class DisplayActivity extends Activity {

    private final String TAG = "DisplayActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView target = (TextView) findViewById(R.id.targetDisplay);
        target.setText(text); // <-- That causes the NullPointerException

        setContentView(R.layout.display);        
    }
} 
 
The solution of course is very easy and was mainly caused by the lack of my Android knowledge. Android of course only can access elements within a layout after it the layout is explicitly set. Therefore I had to set the layout using setContentView(..) and after that the Activity can access the TextView targetDisplay. So the fix was unbelievably easy as you can see in the listing below.

public class DisplayActivity extends Activity {

    private final String TAG = "DisplayActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display); // do this first

        TextView target = (TextView) findViewById(R.id.targetDisplay);
        target.setText(text); // <--No NullPointerException anymore                
    }
}

13 October 2010

Counting lines of code using Groovy

The following Groovy scripts easily counts the lines of files. In this example comparing the lines of code between an multi module Maven 2 project and the Gradle oposite.

def root = new File('/home/username/dirOne')
def pomCount = 0
def gradleCount = 0

private int getLOC(File f) {
    int i = 0  
    f.eachLine { i++ }
    return i
}

root.eachFileRecurse {

    if (it.isFile()) {
        if (it.name == 'pom.xml') {
             println "Reading ${it.absolutePath}"
             pomCount += getLOC(it)
        }
        else if (it.name.matches('.*\\.gradle')) {
             println "Reading ${it.absolutePath}"
             gradleCount += getLOC(it)
        }
        else {
          //println "Ignoring ${it.name} (${it.absolutePath})"
        }
    }
}
println "LOC of all pom.xml ${pomCount}"
println "LOC of all gradle.build ${gradleCount}"

29 September 2010

Apply changes in .bashrc immediately

I have just learned that if you change something in your .bashrc file (e.g. add a new environment variable) and you want to apply it immediately to your shell environment just type.

source ~/.bashrc

Et voilà. Your current bash terminal has implemented your changes done in .bashrc

3 March 2010

Java Calendar API - A misleading piece of software


Today I found a bug in a software module which was caused by the misleading Calendar API of Java regarding the method called before. Of course if the author of the code would have considered the API documentation where the behavior is well described this bug could have been prevented. But the method seems absolutely simple that I would not have read the API documentation neither.


Here comes the code in which the bug was located

public boolean isPasswordExpired(Date lastPwdChange,
  boolean isPwdChangeNeeded) {
 boolean pwdExpired = false;
 if (getMaxValidityTime() > 0 && lastPwdChange != null) {
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(lastPwdChange);
  calendar.add(Calendar.DAY_OF_YEAR, getMaxValidityTime());
  log.debug("Password must not be older than " + getMaxValidityTime() + " days");
  pwdExpired = calendar.before(new Date()); // <-- here comes the BUG!
 }
 return pwdExpired || isPwdChangeNeeded;
}

isPasswordExpired checks if a password has expired. The bug is located at calendar.before(new Date()) where the before method of a java.util.Calendar gets called. Since the parameter of before is a java.lang.Object actually everything can be used to call before. In this example the parameter is a java.util.Date. This looks quiet straight forward, does it? But its oh so wrong!


The API documentation describes it as follows:
if and only if when is a Calendar instance. Otherwise, the method returns false.
Since this feature 'A password can expire' has not been used until now and the code has not been covered by unit tests :( this malfunction has not been detected yet.



22 February 2010

My Android must have apps selection

Recently I have bought the new Google Nexus One (US Version). Here is a small must have collection of Android apps which I find quiet useful so far.
  • ASTRO File Manager - A very nice tool to manage your file on your SD card.
  • NetSentry - NetSentry keeps track of how much data is transferred over each network interface available to your Android system.
  • Daily Dilbert - Well there is nothing more to say :)
  • Google Maps - Nice new edition for Nexus One introducing a navigation system
  • TweetCast - A nice Twitter client
All apps can be found at the Android Market.

30 December 2009

Top 5 Java tools I need to work

The year 2009 is ending. Time to reflect about my set of tools for Java development at COR&FJA.


IntelliJ IDEA
IntelliJ IDEA 9 Ultimate is a very good commercial IDE for Java professionals. It has outstanding support for Groovy and Grails development. Since version 9.0 IDEA comes in two different editions. The community edition is open source and free to use. The ultimate edition is the commercial release of IDEA.

dbUnit
dbUnit helps you writing integration tests which require a database. It lets you define specific dataset which can be added to the database before your tests start and removed after your tests have been completed.
A few months ago I started to use dbUnit as a database migration tool. I had the task to migrate a MySQL database to an Oracle database. After some research I decided to export the MySQL schema and importing it to Oracle using dbUnit. Well it perfectly worked out.

JIRA
After using JTrac and Mantis my employer finally decided to use JIRA as standard issue tracker. In my opinion JIRA is in a professional environment the Rolls Royce of issue trackers. Well at least in comparison with JTrac and Mantis :)

Hudson
After using Cruise Control I am really happy to have met Hudson. Setting up Hudson really is quick and easy. A simple setup wont take you more than five minutes. Comparing to Cruise Control this is a BIG plus and finally there is no bloody XML configration anymore.

Grails
It's the end of 2009. I am still a big Grails fan (as you probably have noticed). Grails is a wonderful web framework based on Groovy, Spring, Hibernate and Sitemesh which helps you to build web applications as fast as possible. Few days ago Grails 1.2 has been released.


Well these are the tools I personally like most. What tools do you like? Happy new year everyone!

8 December 2009

Unexpected behaviour of ArrayLists size method

Today I just learned something more about Javas ArrayList and my Debugger after an half an hour of trying to find out what is wrong with my code.
I had the strange situtation that the debugger told me that my list contained 6 elements but the size method of that list returned a value of 7 (see figure below). Apparently the ArrayList accepts null values without complaining about it and these null values are going to modify the size of the list but the debugger - in the case the debugger of IntelliJ IDEA 9 RC1 - filters null values and does not display them.




With the following listing you can reproduce this behaviour using IntelliJ IDEA (or your prefered IDE).

import java.util.ArrayList;
import java.util.List;

public class FunnyLists
{
   public static void main(String[] args)
   {
      List<String>
 list = new ArrayList<String>();
      list.add("Hello");
      list.add(null);
      list.add("World");        

      System.out.println("Size: " + list.size());

      for(String element : list) {
         System.out.println("Element: " + element);
      }
   }
}



This listing generates the following output:
Size: 3


Element: Hello
Element: null
Element: World

6 July 2009

Passed the SCJP - A reflection about the exam

It's finally done! I passed the SCJP last June and therefore I would like to reflect things I have learned and share my thoughts with you.

Study material
For the SCJP exam preparation I used the web learning lessons provied by SUN and SCJP Java 6 Study Guide. The web learning lessons and espessially the example exams where really valuable to me . They give you the feeling how hard the exam can be and what kind of questions could be asked.

To all future students: Repeat the test exams as much as you can. This will get you through the SCJP exam.

The 'SCJP Java 6 Study Guide' introduces all SCJP topics very well and contains a CD-ROM with additional test exams. These test exams are definitely harder than those of SUN but I really recommend to take these test exams. If you pass these test exams you will definitely pass the real SCJP exam!

Exam day
I took the exam at test-site in Zurich downtown. First of all I had to identify myself with two different identifcation documents (e.g. passport, creditcard or drivers licence). After that I had to hand out my watch, wallet and my bag to the supervisor. All the thing were looked in a safe. Done! After that my supervisor introduced me to my exam workstation and told me that several cameras are observing me during the exam. Well therefore try NOT to cheat during the whole exam. It not worth it.

Next steps
Currently I am thinking about further steps within the SUN Certification Programm. One step could be the 'SUN Certified Java Developer', a very generell continuation of the SCJP based on developing a client/server desktop application using Swing. Another step could be the 'SUN Certified Web Component Developer'.

I have not yet decided what certification is going to be next but I am tending to the SCJD because may knowledge about SWING is quiet poor :(

3 June 2009

iCalendar 0.2 Grails Plugin is out

Just minutes ago the iCalendar Grails Plugin version 0.2 has been released. More details about the release can be found here.

29 May 2009

iCalendar 0.1 Grails Plugin just released

Just seconds ago I got it all ready to release the first version of the iCalender Grails plugin. Version 0.1 is absolutely simple and easy to use. It covers - in my point of view - the main topics of the iCal format.

So when should I use the iCalendar Plugin in my Grails application?
Well if you want to provide a simple iCalendar export service within your Grails controllers to first convert your event data to iCal and the send it to the client. One big advantage is that you can use a builder to describe your event data. This could look for example like this.

iCalendar.calendar {
events {
event(start: new Date(), end: new Date(),
description: 'Events description', summary: 'Short info') {
organizer(name: 'your name', email: 'your@email.com')
}
}

If you'd like to know more about this plugin please feel free to visit the plugins homepage.

Synology DS207+ - Troubles with Volume - Disk 2 crashes

From time to time my Synology DS207+ suffers from a invalid RAID1 volume and telling me "volume 1 was degrade, please repair it". Well if I do so and start the repairing process my DS207+ works for the next 24h (up 3 days). After that period it tells me that disk 2 in volume 1 has crashed and that I should replace the disk.

Well the first time I really did replace the harddisk but after 3 months the same thing happend to this brand new harddisk. So I decided to take the harddisk out and put it into my PC. Starting my OS and deleting all partions on that disc. And well - oh wonder - this worked. To me this behaviour seems like a strange bug in the Synology firmware. Anyway to me this is the fastest work around to get my NAS up and running again.

27 May 2009

SCJP - Now it gets strange

Which two about using the java.io.Serializable class are true? (Choose two.)

A) If Dog extends Animal, then Animal must implement java.io.Serializable in order to serialize an instance of Dog.
B) If Dog has-a Collar, then Collar must implement java.io.Serializable in order to serialize an instance of Dog.
C) If Dog extends Animal and Animal implements java.io.Serializable but Dog does NOT implement java.io.Serializable, you can serialize an instance of Dog.
D) When an instance of a subclass is deserialized, none of the constructors in it's constructor chain will ever be invoked.
E) If you mark a class's instance variable volatile, and then serialize an instance of that class, the state of the volatile variable will be lost during serialization.

Sun's says: Options B and C are correct. A class's superclasses don't have to implement Serializable in order to be serialized, and if a superclass doesn't implement Serializable then it's constructor will run during deserialization. A transient variable's state is lost during serialization, but a volatile variable's state is not lost.
I really do agree with option C but cannot understand why option B should be absolutely right. I still can serialize the Dog instance even if the included Collar does not implement Serializable. I could mark the Collar instance variable transient and everyone would be happy at runtime.

SCJP - This one could knock me out

Can anyone solve this? I've chosen wrong :( And probably learned something.



1. class Test4 {
2. public static void main(String [] args) {
3. boolean x = true;
4. boolean y = false;
5. short z = 42;
6.
7. if((z++ == 42) && (y = true)) z++;
8. if((x = false) || (++z == 45)) z++;
9.
10. System.out.println("z = " + z);
11. }
12. }


What is the result?

A) z = 42
B) z = 44
C) z = 45
D) z = 46
E) Compilation fails.
F) An exception is thrown at runtime.

Becoming a Sun certified Java programmer or how to become a compiler

The next two weeks I am trying to prepare myself to Sun's certified Java programmer (SCJP) exam. Up to now it really does not kick ass. Well my main troubles with the studies are currently some topics in the exam objective 3.5 (Tokenizing).

Objective 3.5 - Tokenizing with Pattern and Matcher
Let's say there's the pattern 'a?' and we would like to tokenize the following string 'aba' using the following Java class.

public static void main(String[] args) {
Pattern p = Pattern.compile("a?"); // compile the pattern
Matcher m = p.matcher("aba");

while (m.find()) {
System.out.println(m.start() + " >" + m.group() + "<");
}
}

What I expected out of this listing was something like this.
0 >a< 
2 >a< 
But what it actually returns was this.
0 >a< 
1 >< 
2 >a< 
3 >< 
Mhm. According to my study book (from which I took this example) they talking about some zero-length matches when using the greedy quantifiers '*' or '?'. They say that zero-length matches can appear under the following circumstances.
  • After the last character of source data
  • In between characters after a match has been found
  • At the beginning of source data (if the first character is not a match. Try tokenizing this string '2aba')
  • At the beginning of zero-length source data
Well this rules seems to be regular expression specific and does not have anything to do with the Java implementation. The only funny thing is - I use RegEx Buddy to develop my regexes - that I cannot reproduce it in my favourite regex editor. Yet another topic to learn by rote (means not really understanding it but memorize it for the exams purpose only)

23 December 2008

Grails 1.1 Beta 2 steht zum Download bereit

Heute Nachmittag gab Graeme Rocher (SpringSource) den Grails Release 1.1 (Beta 2) für die Entwicklergemeinde frei. Dieser Beta Release ist wie gewohnt nicht für ein produktives Umfeld gedacht, sondern dient den Entwicklern zum Ausprobieren der neuen Grails 1.1 Features.

Zu den neuen Features gehören unter anderem diese Punkte.
Die Release Notes findet man hier. Die neue Beta Version kann unter http://grails.org/Download heruntergeladen werden. Viel Spass beim ausprobieren.

16 December 2008

Groovy-JDK erhält eine Versionierung

Unter Groovy-JDK versteht man eine API Dokumentation (im Javadoc Format) über die Methoden, um welche Groovy  Java Klassen (z.B. java.lang.String) erweitert. Gerade letztens wollte ich diese API Dokumentation verwenden, um herauszufinden, in welcher Groovy Version eine Methode eingeführt wurde. In der API Dokumentation war die Methode aufgeführt, jedoch konnte ich diese in Grails 1.0.4 (verwendet Groovy 1.5.6) nicht verwenden. 

Aus der Grails Newsgroup habe ich dann erfahren, dass die Methode erst mit Groovy 1.5.7 einführt wurde und dass der DocGenerator, welcher die Groovy-JDK Dokumentation generiert, den @since Javadoc Tag nicht interpretiert. 

Nach dem mir Guillaume Laforge (Groovy Projektleiter bei SpringSource) ein paar Koordinaten über die involvierten Klassen im Groovy Projekt gegeben hat, habe ich mich entschlossen ein erstes Mal für das Groovy Projekt einen Patch zu erstellen und diese fehlende Funktionalität nachzulieferen. Daraus entstanden einerseits ein Patch, welcher den DocGenerator um den @since Tag erweitert und andererseits ein weiterer Patch, welcher die fehlenden @since Tags in den Groovy-JDK Klassen nachführt.

Gemäss Guillaume werden die Patches voraussichtlich mit Groovy 1.6-RC1 in die Codebasis übernommen (siehe Zitat G. Laforge).
Yup, the patch looks fine, although I haven't tested it. I'll most probably add the patch before we release 1.6-RC-1, perhaps even today if I'm not too busy with other things.
Ich bin wirklich positiv überrascht, wie schnell und unkompliziert solche Contributions es in die Groovy Codebasis schaffen. Das motiviert mich für allfällige weitere Contributions für Groovy bzw. Grails :)

10 November 2008

Grails 1.0.4 - Bald schon da

Wenn man der Grails User Mailing List und dem Projektleiter von G2One glauben darf, wird Grails 1.0.4 noch diese Woche ausgeliefert. Aktuell wird nämlich heftig über den Inhalt von 1.0.4 in der User Mailing Listdiskutiert.

Unter den Erneuerungen finden sich unter anderem folgende Themen:
  • Upgrade auf Spring 2.5.5
  • Das Setzen eine Hibernate SQL Types in GORM
  • Und eine nervige Fehlermeldung, welche in Zusammenhang mit Firefox (> 2.x) auftritt, es sich dabei aber um einen Fehler in Grails 1.0.3 handelt.
Bei Grails 1.0.4 handelt es sich um einen Stabilisierungsrelease, d.h. dass bekannte Fehler behoben werden, es aber kaum neue Features hinzukommen. Gegen Ende dieses Jahres plant G2One dann noch die Veröffentlichung des Minor Releases Grails 1.1, welcher zusammen mit Groovy 1.6 veröffentlicht werden soll. Dieser Release bringt wiederum neue Features mit, auf welche es sich freuen lässt.

4 November 2008

Neues von der Squeezebox Front


Logitech hat ein neues Produkt, namens "Squeezebox Boom" auf den Markt geworfen, welchem ich nicht widerstehen konnte.

Die "Squeezebox Boom" entzückt durch die von Squeezebox gewohnte Einfachheit in der Installation und der Bedienung. Einstecken, WLAN Einstellungen konfigurieren und dann bereits schon Musik hören.

Nachdem ich schon lange meinen ursprünglichen Radiowecker entsorgen wollte, habe ich mit der "Squeezebox Boom" nun endlich einen würdigen Nachfolger gefunden.

Tolle "Schnickschnack-Features" sind beispielsweise, das automatische abdunkeln der Anzeige, wenn die Raumbeleuchtung ausgeschaltet wird. Somit kann ich schlafen, ohne dass mir ein Leuchtturm im Zimmer steht.

Nach der ersten Nacht :) kann ich die neue Squeezebox nur weiterempfehlen. Geweckt hat sie mich übrigens auch pünktlich.