Thursday, June 18, 2009

Dude, where are my resources?

I was struggling with a stupid problem this week and it took me some time to realize what was going on, so I will post here the solution so nobody else needs to waste time on this matter again (and for future reference for myself as well ;)).

I wanted to read a .csv (comma separated value) text file that was inside one package in my application. Consider the simplified version of my code in the tree below.

|- main
|- java
|- com
|- resources
|- file.csv

The had this (simplified) code:

public class App {

public static void main(String[] args) throws IOException {
URL url = App.class.getResource("com/resources/file.csv");

The value of the variable url was null. And there is one simple (and quite obvious once you find out) reason for this. The resource file was indeed in my src folder, but it was not in my destination folder where the classes were generated. As I am using maven, this would be the target folder.
And why is this obvious? Because the getResource method uses the ClassLoader of the calling class to find the resource you are looking for, and the realm of files the ClassLoader knows are in the classpath. As I was executing the code from my IDE, the classpath would be the compiled classes from sources. On top of that, the problem was that the text files not being copied to the destination folder.

Thanks to Maven the solution was quite simple. As it is based on convention over configuration, all I did was to move the resources folder to the root of the src/main folder like this:

|- main
|- java
|- com
|- resources
|- file.csv

The had this (simplified) new version of the code:

public class App {

public static void main(String[] args) throws IOException {
URL url = App.class.getResource("file.csv");

In summary, just make the resource available somewhere in your classpath: in the target/classes folder or in the .jar you are generating.

Find this article also on

Thursday, June 11, 2009

Java in Ubuntu

Well, I am now just trying to use Ubuntu as a development environment. First thing I noticed is that there are more than one jre already installed by default in the system, and here is the evidence:

jars@jars-desktop:~$ locate /rt.jar

I really wanted to use the Sun JDK for my development instead of OpenJDK, so I installed the Sun Java.

Just type the command below and compare the results:

sudo apt-get install sun-java6-bin sun-java6-jre sun-java6-jdk

jars@jars-desktop:/etc/alternatives$ sudo apt-get install sun-java6-bin sun-java6-jre sun-java6-jdk
Reading package lists... Done
Building dependency tree
Reading state information... Done
sun-java6-bin is already the newest version.
sun-java6-jre is already the newest version.
sun-java6-jre set to manually installed.
Suggested packages:
sun-java6-demo sun-java6-doc sun-java6-source
The following NEW packages will be installed:
0 upgraded, 1 newly installed, 0 to remove and 14 not upgraded.
Need to get 17.4MB of archives.
After this operation, 55.7MB of additional disk space will be used.
Get:1 hardy-updates/multiverse sun-java6-jdk 6-07-3ubuntu2 [17.4MB]
Fetched 17.4MB in 3min23s (85.6kB/s)
Preconfiguring packages ...
Selecting previously deselected package sun-java6-jdk.
(Reading database ... 139447 files and directories currently installed.)
Unpacking sun-java6-jdk (from .../sun-java6-jdk_6-07-3ubuntu2_i386.deb) ...
sun-dlj-v1-1 license has already been accepted
Setting up sun-java6-jdk (6-07-3ubuntu2) ...

But which of the two JVMs that now reside in my system area going to be used? Here it comes the ass-saving (and brand new to me) Ubuntu command:

sudo update-java-alternatives -s java-6-sun

This will define Sun Java-6 as the default JVM in your system. If you prefer to do it step-by-step just type this:

jars@jars-desktop:~$ sudo update-alternatives --config java

There are 2 alternatives which provide `java'.

Selection Alternative
+ 1 /usr/lib/jvm/java-6-openjdk/jre/bin/java
* 2 /usr/lib/jvm/java-6-sun/jre/bin/java

Press enter to keep the default[*], or type selection number:

The next tricky step is to set the prefered order in which your JVMs shoud be used. To set this up just edit the /etc/jvm file and include your recently installed JVM as the first one, so your file looks more or less like this:

# This file defines the default system JVM search order. Each
# JVM should list their JAVA_HOME compatible directory in this file.
# The default system JVM is the first one available from top to
# bottom.


Ok, not ready yet, but I am not willing to return to Windows without doing this until the end! :)
So, next step is setup the environment variables and if you want to set it system wide, edit the /etc/profile file and append the following lines at the end:

export JAVA_HOME=/usr/lib/jvm/java-6-sun
export PATH=$PATH:$JAVA_HOME/bin

You can also set the variables for only one user by editing /home/$user_name$/profile.

Now test it!!

jars@jars-desktop:/etc/alternatives$ java -version
java version "1.6.0_07"
Java(TM) SE Runtime Environment (build 1.6.0_07-b06)
Java HotSpot(TM) Client VM (build 10.0-b23, mixed mode, sharing)

You find this article also on

Wednesday, June 10, 2009

JavaOne 2009 Slides

You can download the slides from JavaOne 2009 conference from here. Just choose the track and find the slides.

You need to be signed at the Sun Developer Network (SDN) to view/download the pdf.


Thursday, June 4, 2009

JavaOne 2009: RESTful Transaction Systems

Mark Little (JBoss CTO) and Michael Musgrove (Red Hat Tx)
RESTful Transaction Systems

  • Atomic Transactions should have a scoping mechanism that provides "all-or-nothing" semantics, enables shared resources to be protected from concurrent use and have ACID properties (Atomic, Consistent, Isolated, Durable)

  • WS-Transactions in the past vas very hard to achieve transactional interaction among WS services; even JTS implementations didn't interoperate but WS provide the opportunity to leverage unparalleled interoparability

  • On B2B interaction, one cannot affort to lock resources on behalf of an individual indefinitely and maybe you need to undo a subset of the worh that's been done

  • Possible Transaction Models for REST

    • Atomic Transaction (XA/XTA) - status: specified and implementd

    • Forward Compensation Base (WS-BP)- status: specified

  • Implementation for REST transaction for JBoss uses an uniform interface with HTTP and the usual methods (GET, PUT and POST) return the usual HTML code and some XML in the body

  • Example URLs:

    • GET <s>://<auth>/transaction-coordinator/active

    • POST <s>://<auth>/transaction-coordinator/begin

  • Demo is using the transaction-coordinator (with a Proxy in Tomcat) and some Web Services in Python, JBoss TM and RESTeasy

JavaOne 2009: Enterprise Application Integration Patterns

Andreas Egloff (Sun) and Bruce Snyder (SpringSource)
Enterprise Integration Patterns in Practice
"A Design Pattern is a formal way to document a solution to a design problem ina particular field of expertise" - from Wikipedia

  • The presentation is based on the "enterprise integration patterns" book

  • Stencils for Visual Studio in EAI Patterns web site

  • Flexibility x Productivity: too little explicit support out-of-the-box but explicit support out-of-the-box is too rigid (does not fit your case or you are forced to go around) - the solution would be to extend those use cases

  • Frameworks: Apache Camel and Project Fuji (from OpenESB v3)

  • Camel supports routing of messages in a simple manner like, for instance, from("A").to("B") and much more complex stuff like taking decisions in the route and where to route the message to; it also suppors a pipeline routing much like from("file://myfile.txt").choice().when().method("MyBean","matches").to("Q").end().pipeline("B","C","D")

  • Some Camel components: Atom, Bean, SEDA, SFTP, HTTP, FTP, Mock, XQuery, XSLT and much more (70+)

  • Project Fuji is the basis for OpenESB v3 and is a service platform to realize SOA based on Convention - Configuration - Code in that order; Light weight and OSGi based and not centred on JMS but on Services

  • The Project Fuji has a Web UI that allows the user to visually declare and configure services and program the connections and routing of services; it also offers a DSL (Integration Flow Language)

  • Bruce and Andreas went on some slides with examples of the patterns from EAI book and showed how those are implemented in Camel calls using Fuji interface to build them - it seems easy, but as they said in the beginning of the presentation, using out-of-the-box solutions might be too rigid; on the good side, you can write code using DSL and even pure Java, so it really might be an interesting solution for integration

  • After the slides, a quick live demo using Eclipse with some tools for Spring and Maven with archetypes for Apache Camel

Wednesday, June 3, 2009

JavaOne 2009: Coding REST and SOAP together

Martin Grebac and Jakub Podlesak from Sun Microsystems on Coding REST and SOAP together

  • Using METRO = JAXB + JAX-WS + WSIT and Jersey

  • No deployment descriptors needed (use annotations) but still available if required; part of Java EE 5 and 6

  • Why REST? Simplicity, Takes advantage of the existing caches and proxies, Serendipity, Scalability (HTTP load balancers)

  • Common JAX-WS/RS concepts should be supported

  • Heavy using of annotations: @Path, @WebService, @GET, @Produces, @WebMethod, @XmlRootElement, @XmlAttribute etc.

  • Take care: do not fall into RPC over HTTP (REST-RPC hybrid), use compatible security (Securing SOA does not automatically secure the REST), annotation hell

  • Think about the consumers of your services and ask yourself if you really need SOAP and REST; consider using REST only in some parts of your application

  • Use @WebMethod annotations to enable control over exposed SOAP methods

JavaOne 2009: Effective Java

Joshua Bloch in "Effective Java: still effective after all these years"
First Edition of the famous book Effective Java was in 2001 and is now on its second edition from 2008 and it has new chapters on generics, enums, annotations, varargs, concurrency and Serialization

  • About Generics

    • Unlike arrays, generics types are invariant: List <String> is not a subtype of List <Object>; Wildcard provide additional API flexibility

    • PECS - Producer extends, Consumer super (Mnemonic for Wildcard usage)

    • How to write a container with an arbitrary number of type parameters: typesafe heterogenous container pattern - parameterize selector instead of container; present selector to container to get data; data is strongly typed at compile time; allows for unlimited type parameters

  • Enum Types

    • double temp = thermometer.getTemp(true)

    • double temp = thermometer.getTemp(Temperature.FAHRENHEIT)

    • double temp = thermometer.getTemp(FAHRENHEIT)

    • which of the above would you prefer? :)

  • Synchronized collections are largely obsolete; use ConcurrentHashMap and friends and Never sinchronize on a concurrent Collection

  • The Serialization Proxy Pattern - don't serialize instances of your class; instead, serialize instances of a small, struct-like class that concisely represents it, then reconstitue instances of your class at read time using a constructor that uses only its public methods - Sun uses this pattern on its EnumSet there is a private static final SerializationProxy

The presentation is based on lots and lots examples of code, so it's kind of hard to resume them here! ;) In essence, it is probably a good idea to buy the new edition of the book! ;)

JavaOne 2009: Enterprise Build and Test in the Cloud

Carlos Sanchez from G2iX on Enterprise Build and Test in the Cloud

  • Tools:

    • Build: Apache Maven (build and more, start/stop AS, automatic deployment, execution of tests - note: most people in the room use maven and not ant)

    • Test Cases: TestNG (they don't use JUnit) - unit/integration tests, parameterized tests, parallel testing - note: not many people in the room uses TestNG

    • Integration tests: Selenium - UI and integration testing, tests run in the browser, tests can be recorded, firefox plugin

  • Continuus Integration: Apache Continuum - tight integration with Maven, dependency handling, trigger builds on defined conditions - note: not many people in the room use continuum

  • Cloud Computing: Amazon Web Services - storage, queue service, manpower, computation

  • Joke of the day: The #1 Programmer Excuse for legitimately slacking off: "my code's compiling" - credits XKCD

  • Different setup for selenium grid: using a selenium hub brings no complexity to the developers or to the already written tests; setting up differente remote controls for differente environments (IE on Windows, Firefox on Linux, Safari on Mac) only depends on having the Selenium hub

  • TestNG will allow to run the same tests in the different environments that were setup by Selenium Grid

  • Test Servers cost money: using the cloud allows to use on-demand servers, pay-per-hour, unlimited number of machines and start in a couple of minutes - no OS X offered by amazon

  • Create Amazon Machine Images for each different environment you need to test your application - The machines are killed after the tests are run and you only pay for the time you use those machines

  • Use Maven EC2 plugin to start amazon AMIs, stop at the end of test and pass user data

Found a different (but up to date) version of this presentation from Carlos Sanches at slideshare.

JavaOne 2009: Lessons Learned in ESB

Andreas Egloff and Frank Kleviet: ESB Lessons Learned
Both speakers work now at Sun in the OpenESB project and come from a big vendor that sold EE products.

  • ESB as a product comes with risks like, for instance, architecture concerns (good or bad for SOA?), more middleware, over-reliance on one provider

  • Light weight non functional requirements: enterprise scale integration, change happens (decouple configuration), long term commitments (today's hot stuff is tomorrow's legacy)

  • Accomodate large teams: enterprises like to scale by adding people and this makes things harder: easy-to-learn is critical, provide tooling (automated testing & integration) and keep the solution simple

  • Tooling is great, but don't let it get in the way!

  • In their words: "Consultants tend to think that copying and pasting code make them more productive. And this is not true.!: Prefer convetion and configuration over coding! Support Patterns as first class citizens!

  • Frameworks are poweful to reduce code duplication, but sometimes constrain flexibility: Interceptors are a powerful way to add flexibility

  • Developers spend a lot of time waiting. It is necessary to shorten the change-build-deploy-test cycle, by reducing build time, deploy time with smapper deployables or in-place editing; increase testability and debuggability with built-in tests and support automation

  • Modulartiy improves startuptime and performance by only loading what's necessary when it's needed. Modularity can help control complexity.

  • Reduce the artifacts per solution or make managing large numbers of artifats possible.

  • Connectivity Configuration: configuration belongs to run-time and not design or development time; deployables are used in different environments

  • Message-based services more robust in face of change so avoid rebuilding the world for small business logic changes: use scripting languages, externalize business logic (e.g. CBR), consider evolution, versions in handling messages, externalize cross-cutting concerns (e.g. Aspects)

  • Patch Management! OSBi allows to declare a dependency on a specific version of a component, and this way it is not necessary to test the whole enterprise application because you need to upgrade one library

  • JMS if often a bottleneck - component-component message-passing can also be done without JMS; in-memory message exchange allows performance improvement. Just use JMS if it is really necessary

  • JMS has a proprietary wire protocol, requires yet more infrastructure; HTTP provides proven scalability and interoperability;

  • Avoid depending on one vendor only so stick with open standards, open-source: portability of skills of developers

JavaOne 2009: "Bug-free" code on Java 7?

Preventing Bugs with pluggable type checking by Michael Ernst

  • New Feature in Java 7

  • The motivation of the presentation is to help people to design a type system to solve a specific problem

  • Java 7 has a new annotation syntax: e.g. List <@NonNull String> strings; or myGraph = (@Immutable Graph) tmpGraph;

  • Type Qualifiers improves documentation, find bugs in programs, guarantee the absence of errors and reduces the need for assertions and run-time checks

  • Checkers are designed as compiler plug-ins (i.e. annotation processors) and use familiar messages; many checkers are being implementd in Java 7

  • Michael said: "If you want to find some bugs in your code, Findbugs is ok. If you are a developer who cares, you'll want to find ALL your bugs, and this is the tool for that"

  • It is possible to create your own type checking annotations, and he showed us how to write a quick one to avoid SQL injection in our code that access the database

  • Michael showed some statistics comparing FindBugs and the new Java 7 type checking; type checking found 8 bugs (20000 LOC) and findBugs none; on the other hand, type chacking demanded 35 annotations to be written throughout the code

  • It is said that annotations like these would clutter your code, but in my opinion it is a good trade-off for having a "bug-free" code

  • Another interesting option that Type Checking offers, is that one can start doing the annotation of the code on a per-module or per-class basis, i.e. start with the most important parts of the code

The new release of Java 7 will be out this Friday June, 3rd.

Tuesday, June 2, 2009

JavaOne 2009: Clojures for the JVM by Rich Hickey

  • Fundamentals: it is a dynamic language and a new LISP, Functional, Supporting Concurrency, Compiles to JVM bytecode, not OO

  • Why not OO? Because OO encourages mutable state and Mutable stateful objects are the new "spaghetti code". His words, not mine! :)

  • Supports a REPL (read-eval-print-loop)

  • Load/change code in running program

  • On Data Types it has, for example, Arbitrary Precision Integers, Ratios (no precision loss?), doubles, BigDecimals...

  • On Composite Data Structures it has, for example, Lists, Vectors, Maps, Sets and everything nests

  • Data structures are the code, not text-based syntax and everything is an expression

  • All data structures are immutable; performance problems are avoided by two rules: new versions are not full copies and make use of a structural sharing of data (this last one is kind of hard to put in a few words here)

  • Abstraction-based library built on concrete classes for structures with a Java Interface

  • Clojure supports prallel computation, mostly because it focuses on concurrency, which is made easy by using immutable data; no locks needed

  • The only thing that mutate are references themselves, in a controlled way

  • Clojure uses MVCC - Multiversion Concurrency Control through the command dosync which is the transactional control done by databases

  • Clojure integration with Java is natural beacause the data types are the same as Java; it has debugging support and all the Java bytecode infrastructure works with Closure

Why is it that everytime I see a brand new language or programming paradigm it reminds me of everything I learned 15 years ago at College? My words, not his! :)

JavaOne 2009: EJB 3.1Overview

EJB 3.1 Technology Overview by Kenneth Saks
He spoke about the EJB 3.1 Spec which should be ready by end of the year.

  • Session Bean with Local Business Interface; "No-interface" view client - it calls directly the business method from the EJB and it is not generated by the API

  • Java EE Platform packaging will change to a simplified version; same behavior withoud need for ejb-jar

  • EJB 3.1 "lite" API; a small subset of EJB 3.1 API required by JavaEE pPlatform 6 Web Profile, which is made possible by the simplified .war packaging mentioned earlier (local session beans, transactions, declarative security and interceptors)

  • Portable global JNDI Names for Remote and Local session beans; portable naming syntax with unique names defined globally, within application and per module

  • EJB Component Testing tries to solve the problem that it is hard to test Local session beans and client-side EJB component; it is possible to run the EJB in an embeddable container in regular JSE

  • New features: Singletons (new Session Bean component type, Container and Bean Managed Concurrency), Startup/shutdown callbacks, Caledar-based timers (created progammatically or automatically), Asynchronous session bean invocations (available for Stateful, Stateless and Singleton beans), JAX-RS Integration

Glassfish v3 has the implementation for all these new features.

JavaOne 2009 General Session

The Opening General Session for Java One 2009 has just begun. We had presentations from Verizon, Intel, Sun itself with JavaFx. The first two were a little bit commercial, but the JavaFX quick presentation and introduction was interesting in the way that it showed what this technology is able to do!!