Saturday, July 30, 2011

Using Java 7 in Eclipse

1. Download Eclipse 3.7 Maintenance Build:
Eclipse 3.7 does not have support for Java 7, but the good news is that you can download a a 3.7 "maintenance build" (>= M20110729-1400) which does. I downloaded mine from here. The download was really slow, because it was coming from Canada and there were no other mirrors!

2. Add a Java 7 JRE:
Start Eclipse and go to Window > Preferences. Navigate to Java > Installed JREs and add your Java 7 JRE to the list, as the default JRE.

3. Upgrade Compiler Compliance Level:
Once again, in your preferences go to Java > Compiler and select 1.7 as the "Compiler compliance level".

4. Check Project JRE:
If you are working on an existing project, you need to make sure that the project is using JDK7 system library. Go into your project properties and into Java Build Path. Select the Libraries tab and check the version of your JRE System Library. If necessary, press Edit... to change it to JDK7.

5. Test it out:
Create a test class and use a Java 7 feature e.g. List<String> list = new ArrayList<>();. This should compile successfully. Eclipse should even be able to auto-complete the diamond.

The latest news on Eclipse Java 7 support can be found on the Eclipse wiki: http://wiki.eclipse.org/JDT/Eclipse_Java_7_Support_(BETA).

Friday, July 29, 2011

Java 7 is here!

I've been looking forward to Java 7 for a long time and it is finally here! This release is jam-packed with new features and I am really excited about trying it out!

There are great additions to the concurrency package such as a fork/join framework, phasers, transfer queues and threadlocal pseudo-random number generators.

Also, as part of Project Coin (JSR 334), JDK7 includes a set of small language changes intended to simplify common, day-to-day programming tasks and reduce boilerplate such as:

  • Strings in switch
  • Binary integral literals and underscores in numeric literals
  • Multi-catch and more precise rethrow
  • Improved Type Inference for Generic Instance Creation (diamond)
  • try-with-resources statement
  • Simplified Varargs Method Invocation
For a full list of changes take a look at the release notes.

I'm going to be writing about the new features in Java 7 as I learn about them, so stay tuned!

Sunday, July 24, 2011

Viewing CSV Files

I find CSV (or, to be more general, DSV) files difficult to read on Unix because you can't tell which column a value is in. So I always end up importing them into a spreadsheet which is a pain. Here is an example of a small pipe-delimited file containing book data:
Title|Author|CoAuthor|Year|ISBN
Carrie|Stephen King||1974|978-0385086950
The Human Web|William McNeill|Robert McNeill|2003|978-0393051797
It would be a lot easier to read, if I could convert the file into dictionaries of key:value pairs in order to see which columns the values were referring to, like this:
Title:Carrie
Author:Stephen King
CoAuthor:
Year:1974
ISBN:978-0385086950

Title:The Human Web
Author:William McNeill
CoAuthor:Robert McNeill
Year:2003
ISBN:978-0393051797
So, I wrote the following Bash script to convert a delimiter separated file into a collection of dictionaries. It uses awk to read the first row, which contains the column names, split it and store it in an array. It then prints out the remaining rows along with their column names which are looked up from the array.
#! /bin/bash
# CSV Viewer
# Usage: csv [-d delim] filename
# default delimiter is pipe.
#
# Input file:
# h1|h2|h3
# v1|v2|v3
# w1|w2|w3
#
# Output:
# h1: v1
# h2: v2
# h3: v3
#
# h1: w1
# h2: w2
# h3: w3

delim=|
while getopts "d:" OPTION
do
   case $OPTION in
     d) delim=$OPTARG; shift $((OPTIND-1)) ;;
   esac
done

if [ $# -eq 0 ]
then
    echo "Usage: csv [-d delim] filename" >&2
    exit 1
fi
awk -F "$delim" '{if(NR==1)split($0,arr);else for(i=1;i<=NF;i++)print arr[i]":"$i;print "";}' "$1"
Running the script:
sharfah@starship:~> csv.sh -d '|' file
Title:Carrie
Author:Stephen King
CoAuthor:
Year:1974
ISBN:978-0385086950

Title:The Human Web
Author:William McNeill
CoAuthor:Robert McNeill
Year:2003
ISBN:978-0393051797

Saturday, July 23, 2011

Copying Eclipse Preferences

If you want to transfer your preferences from one Eclipse installation to another, you can try the following approaches:

Option 1: Export/Import
Export your current preferences to a file and then import them into your new installation.
Go to File > Export and then choose to export General > Preferences to the local filesystem. Then start your second version of Eclipse, go to File > Import and choose to import General > Preferences.

Option 2: Copy runtime setting directory
Copy ${ECLIPSE_WORKSPACE}/.metadata/.plugins/org.eclipse.core.runtime/.settings from the existing installation to the new one.

Sunday, July 17, 2011

Tracing Java Applications with BTrace

BTrace is a dynamic tracing tool for Java. It allows you to insert tracing actions into the classes of a running Java program. This is especially useful, if you are using a third-party library. So, if you want to know whenever a certain method is called in your program, you can tell BTrace to print out a message whenever that method is hit. See the User Guide for more information.

Quick Start:

  • Download BTrace from here
  • Extract the release to a directory e.g. ~/btrace
  • Write a BTrace program. There are many samples present in the samples directory. Here is one of mine: the program below prints a message whenever the target program calls the ArrayList.add() method.
  • import com.sun.btrace.annotations.*;
    import static com.sun.btrace.BTraceUtils.*;
    import java.util.*;
    @BTrace
    public class ArrayListTrace {
    
        // @OnMethod annotation tells where to probe.
        // In this example, we are interested in entry
        // into the ArrayList.add() method.
        @OnMethod(
            clazz="java.util.ArrayList",
            method="add";
        )
        // print out what was added
        public static void alert(@Self ArrayList self, Object o) {
            print("ADDED ");
            println(o);
        }
    }
    
  • Compile your script:
  • javac -cp "~/btrace/build/*" ArrayListTrace.java
    
  • Start the java program you want to probe and get its pid.
  • Run BTrace and watch the messages appear:
  • ~/btrace/bin/btrace -cp ".:~/btrace/build/*" <PID> ArrayListTrace.class
    
Useful BTrace Programs:

Here are a few useful BTrace programs I have used in the past:
  • OnThrow: Prints out the stack trace of an exception whenever a Throwable is created. This way you can capture all exceptions, even those that have been swallowed.
  • LogTracer: Prints out log messages.
  • AllMethods: Prints out the name of every method entered.