Java

Warning: Bootstrap classpath not set in conjunction…


Java or JDKs in particular provide a way of writing your applications to work with older JVMs.

For example you can be using JDK8 for development but you also want to make sure that your code runs in an older Java 7 based JVM. This is done using the “-target” and “-source” switches sent to the Java compiler javac.

So if you want to compile your app using JDK8  but also want to ensure that it works in Java7 you would do something like this.

javac -target 1.7 -source 1.7

Now this will make sure that your application source is not using any Java8 specific language features. For example if your code had used Lambda Expressions the compilation will fail now since they were introduced in Java 8 and are not available in Java 7.

But the problem is although the compiler can check for language features it does not (and most likely cannot) check for the usage of newer API classes introduced in the new Java platform.

So in our example here, if the application code tries to use the new JDK8 specific Date Time API classes, compilation will not fail even though you sent in “target 1.7” and “source 1.7” to the compiler!

And this is why the Java compiler warns you and suggests to set the “bootstrap classpath” to the older JDK specified in your “target” and “source” switches. This ensures that you will not use classes introduced in the the newer JDK.

javac -Xbootclasspath:/path/to/jdk7/rt.jar -target 1.7 -source 1.7

Now if your application code tries to use classes that were introduced in the newer JDK compilation will fail!

Advertisements
Design Patterns, Java, Maven, Uncategorized

Missing ServiceProviders after Shading


Shading is a technique used in Maven to create a single”Uber” jar by merging the contents of  your app jar and all of it’s dependent jars. This makes it easier when distributing your application since there is only one big jar to deal with.

The Java Service Provider pattern is a cool way of building loosely coupled extensible applications.

When building a jar containing such implementations a text file per interface should be created listing all of it’s implementations and placed in META-INF/services. This is used by the JVM when the application needs to load (using ServiceLoader class) implementations of a particular interface without explicitly knowing about them.

The problem is when shading multiple jars containing service providers Maven does not merge the contents of META-INF/services by default.

The solution is to use the transformer ServicesResourceTransformer to tell the Shading plugin to merge the contents of META-INF/services in every jar it shades.

This can be specified in the pom.xml as shown below.

<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers> 
...
Java, Programming

Groovy Console: Python like REPL for Java


UPDATE2: JShell to be introduced in Java9, so hopefully we will have a “native” Java REPL!

UPDATE1: Checkout a discussion about this post on Reddit!

One of the strong features of Python (and many other interpreted languages) is the availability of a REPL(Read, Evaluate, Print & Loop) interactive shell to execute code without having write a complete program and compile it to see the result. This substantially increases developer productivity especially when working with a large code base. Using a REPL shell (a.k.a. console) you can easily run and test small code snippets in isolation from your main program.

Now if Python can have a REPL why can’t Java? Well the answer is simple, Java is a “compiled” language. Undeterred, I still Googled for a “Java REPL”. Stackoverflow pointed me to Groovy Console. But before going onto Groovy Console, What is Groovy?

From Wikipedia:

Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform, is dynamically compiled to Java Virtual Machine (JVM) bytecode, and interoperates with other Java code and libraries. Groovy uses a Java-like curly-bracket syntax. Most Java code is also syntactically valid Groovy.

The Groovy installation includes a REPL which is (obviously :)) called “Groovy Console”. Since “Most Java code is also syntactically valid Groovy” I can now use the Groovy Console to execute Java code snippets (see screenshot below).

groovy_console_java

This is great because now I don’t have to write a complete class and the dreaded “public static void main()” to test a small snippet of code before I merge it into my “big” program.

So there you go…if you want a “Java REPL” install Groovy!

ANT, Java

Debugging ANT tasks when executing from the command line


Sometimes you may need to debug your custom Java ANT task (or even occasionally debug ANT source itself) when running from the command line. This can be achieved by setting ANT_OPTS as given below before running the “ant” command.

set ANT_OPTS=-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y

ant_debug

It might be a good idea to specify “suspend=y” as shown above since this will make the Java Virtual Machine (JVM) in which ANT executes to wait until you attach your debugger (from NetBeans of any IDE) along with the sources containing breakpoints.

This method can be used to debug ANT tasks running on a remote (build) server too without having to install an IDE and mounting source code in that particular server. This is made possible because the JVM opens a port for remote debugging which comes in handy not only for debugging ANT tasks but basically any java program that executes remotely.

Java, Java Enterprise Edition (JEE)

Java Colombo Meetup #4: REST and Web APIs


Java Colombo is a java user group formed quite recently which brings together Java developers from all around Colombo (and perhaps even developers outside Colombo too)

The group has been picking up steam lately and meetups are coming up thick and fast now.

The 4th meetup of Java Colombo was hosted by WSO2 on Thursday (20th), this was  my second meetup and like the previous one I found it to be very interesting, useful and really worth attending.

Paul Fremantle presenting REST at Java Colombo (courtesy Imesh Gunaratne)

The topic was REST and Web APIs for Java coders and the presenter was Paul Fremantle (CTO & Co Founder WSO2)

The main topics of REST were covered brilliantly by the speaker, explaining stuff in a very simple but effective manner.

I’ll try (didn’t take down notes :)) to list down the main points that were discussed…

  • Introduction to the REST architectural style and why it fits so well with the design of HTTP (using the four main HTTP verbs GET,POST, PUT, DELETE as operations and using URIs to point to resources or ‘nouns’  on the server  Customer, Account etc.)
  • The fact that REST is kinda like design pattern (architectural style?) and leaves out the ‘hardcore’ implementation details to the developer.
  • The concept of Hypermedia as the Engine of Application State (HATEOAS)
  • The importance of designing your RESTful application in a simple yet robust way.
  • REST vs SOAP (it was mentioned that when it comes to mobile apps REST is almost always the winner)
  • JSON as a compact (non-verbose, lightweight) media type to send data between client and server, especially in mobile/cloud apps
  • Content Negotiation in HTTP (basically how the client and server negotiates the types of content i.e. json, xml, html etc. exchanged between each other)
  • JAX-RS: the REST specification for Java and one of it’s implementations Apache CXF.

Overall it was one of the best sessions I had attended, Paul did ‘live’ coding using Eclipse and relied very little on the slides which was really cool.  The Q&A session after the presentation was very active and informative too.
Great Work Java Colombo! and kudos to WSO2 for hosting the event for the 4th time! Looking forward to the The 5th meetup which is already planned!!!

Java

Repeat after me: Java is pass-by-value


Although I have blogged previously about “Java Pass by value” the JavaRanch Campfire story here is probably the best explanation of it I have seen so far. The ‘remote control’ analogy for object references makes it much easier to understand for any newbie.

The reinforcement at the end of the story is pretty cool and sums everything up nicely… 🙂

So repeat after me:
Java is pass-by-value.
(OK, once again… with feeling.)
Java is pass-by-value.
For primitives, you pass a copy of the actual value.
For references to objects, you pass a copy of the reference (the remote control).

Java

Java varargs and arrays


Although I had known about varargs (variable number of arguments) since Java 5, strangely I didn’t know that arrays can be given in place of varargs until yesterday (criminal I know :))

 package javaapplication2;
 public class JavaApplication2 {

    public void printAll(String... strs){
        for (String str: strs){
            System.out.println(str);
        }
    }
    
    public static void main(String[] args) {
        String[] strs = {"hello","world"};
        new JavaApplication2().printAll(strs); //String array param
        new JavaApplication2().printAll("hello","sri lanka"); //multiple string params
    }
}

And I also tried changing the parameter format of a class’s main method using varargs instead of the usual String[]. That seemed to work too..

public static void main(String... args) {
        System.out.println("args.length = " + args.length);
}

Varargs are convenient when programming. The official document gives a nice short introduction to them. The key points that I took from it was;

  1. The three periods after the final parameter’s type indicate that the final argument may be passed as an array or as a sequence of arguments.
  2. Varargs can be used only in the final argument position.
  3. As an API designer, you should use them sparingly, only when the benefit is truly compelling.
  4. Generally speaking, you should not overload a varargs method