Category Archives: Java

Adding custom Intellij Idea launcher on unity (Ubuntu 12.04)

As you know Intellij Idea comes in tar.gz distribution for linux OS, so it is only possible to launch it from terminal after unpacking.

But there is a possibility to add quick launcher button for unity.
First of all, create idea.desktop file with the following contents:

[Desktop Entry]
Name=Idea Community Edition
Comment=Launch Idea Community Edition

Paste your location to the Idea distribution in the italicized text given above.
After that, open this file in nautilus and just drag it to your launcher bar.

Tuning Intellij Idea

First of all consider changing idea.vmoptions.
idea.vmoptions is a text file with a list of JVM settings, it’s usually found in the bin folder in the Idea installation folder. This file can be open in any text editor.

The following settings increase performance drastically on Sun JVM 1.6:


Notice, that I enabled concurrent mark-sweep GC (in theory it’d be faster than others on 1.6) and aggressive optimizations as well as server JVM and I don’t use assertions (no `-ea’ switch).

I tested these on x86 linux with Idea Community edition of build 111.69

As for appearance I’d suggest using Nimbus theme (Settings -> Appearance -> Look and Feel).

That’s how idea looks on my Ubuntu:

Idea 11 Community Edition on Ubuntu

Full screenshot is available here.

P.S.: For Mac OS X users:
There is no idea.vmoptions file on Mac OS X.
In order to modify the mentioned JVM settings, you’d go to the application’s package contents, then open the inner “Contents” folder and then open Info.plist (just click on it and the standard plist editor will be opened). In the opened plist editor consider changing Java > VMOptions key as given above.
You may copy-and-paste the following value I use on my Mac laptop:

-Xverify:none -XX:+UseConcMarkSweepGC -XX:+AggressiveOpts -XX:+CMSClassUnloadingEnabled -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing -XX:CMSIncrementalDutyCycleMin=0 -XX:-TraceClassUnloading -Xbootclasspath/a:../lib/boot.jar

Note, that you may want to make Idea start in 32-bit mode to reduce the memory consumption and increase the overall IDE performance. Just ctrl-click on the application icon in the “Applications” folder and click on the checkbox “Open in 32-bit mode”.

After doing so Idea starts in 1 (ONE) second or so on my Mac Book Pro!

You have to edit idea64.vmoptions if you’re running idea in 64-bit mode (thanks to Rudy for noticing this).

Create self-sufficient JAR with maven

After getting stuck several times with maven assembly plugin I decided to make a note on how to create self-sufficient jar with maven. Self-sufficiency implies jar to include all the required dependencies so it can be started with java without specifying extra classpaths.

        <!-- Packaging configuration -->

Then you’ll be able to create self-sufficient jar:

mvn clean package assembly:assembly

context:annotation-config for StaticApplicationContext

For some reason I’m unable to use XML configuration for spring in the current project (and thus ClassPathXmlApplicationContext) – don’t ask me why :)
So I’ve to specify the entire configuration in code (by using StaticApplicationContext.registerSingleton).

The question is – how to make StaticApplicationContext work as if “annotation-config” is specified to make application context process annotated fields, methods (e.g. @Resource, @PostConstruct, etc.)?

After digging in spring javadocs it turns out to be very simple:

final StaticApplicationContext context = new StaticApplicationContext();

context.registerSingleton("beanPostProcessor", CommonAnnotationBeanPostProcessor.class);
context.registerSingleton("superior", SuperiorImpl.class);
context.registerSingleton("inferior", InferiorImpl.class);

context.refresh(); // Refresh is mandatory before any getBean invocation, otherwise bean processors won't work

final Superior superior = context.getBean(Superior.class);

The most important line is where CommonAnnotationBeanPostProcessor is registered in the DI context.

The spring documentation states regarding this class:

NOTE: A default CommonAnnotationBeanPostProcessor will be registered by the “context:annotation-config” and “context:component-scan” XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom CommonAnnotationBeanPostProcessor bean definition!

NOTE: Annotation injection will be performed before XML injection; thus the latter configuration will override the former for properties wired through both approaches.

How to write and debug your own annotations processor.

This is a short but comprehensive guide on how to write and debug your own annotations processor (assuming you are using Java 6, should work on Java 7 as well).

  • Create jar where your annotations processor will reside, say ann-proc.jar (Just define annotation processor class).You may want to add dependency to the JDK’s tools.jar in case you wanna use sun-specific code model entities:


  • Create (or proceed to) another jar (say my.jar) you want to process with annotations processor, add annotations you want to process.
  • Add the following file (which in fact is a SPI configuration file) to my.jar resources folder

    + /META-INF/services
    + javax.annotation.processing.Processor

    The contents of this file would look as follows:


  • That’s it, do mvn clean install on the my.jar package having installed ann-proc.jar and see the effect.If you want to debug your annotations processor, you may use mvnDebug, say do mvnDebug clean compile in the my.jar root folder and attach your IDE to the 8000 debug port.

Ugly Netbeans font rendering on Ubuntu Linux

Netbeans fonts rendering may look ugly on the latest Ubuntu.
The following configuration does the trick for me (file $netbeans/etc/netbeans.conf, see part in bold):

# Options used by NetBeans launcher by default, can be overridden by explicit
# command line switches:
netbeans_default_options=”-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-Dapple.laf.useScreenMenuBar=true -J-Dsun.java2d.noddraw=true -J-Dswing.aatext=true -J-Dawt.useSystemAAFontSettings=lcd_hrgb

Checked with openjdk, it probably won’t work for “older” sun JDK.

Spring and AspectJ

For those who uses Spring 3.0.5:

Spring 3.0.5 doesn’t work with aspectjweaver 1.6.10+ due to AssertionError at org.aspectj.weaver.UnresolvedType.nameToSignature!

E.g. if you use aspects in your spring config with, say, jdbc:initalize-database configuration clause, most likely you’ll get assertion error in your JUnit test what uses such a config.

The possible workaround would be to switch to aspectjweaver of version 1.6.9.

Restlet’s JAX RS lacks custom converters

I published earlier how to use Restlet framework with Spring over its JAX RS frontend.

Unfortunately, there is no simple way to specify custom JSON converter for certain types, say java.util.Date (e.g. if you want to serialize it to ISO 8601-compatible string representation).
In order to support that you need either to write a custom MessageBodyConverter or serialize objects directly to string in your JAX RS resource.

I’m gonna try Apache CXF as it looks promising and flexible in such an aspect.

REST API how to: JAX RS + Restlet + Spring + Maven

Several days ago I needed to add REST API support to my app. I decided to pick Restlet framework for its simplicity and broad community.
Besides the obvious simplicity and power of the restlet engine, restlet guys provided a bulk of libraries to help to integrate with Spring, JAX RS (a.k.a. JSR 311) and many other things – such as integration with J2SE, J2EE, GWT, SSL, Jackson, JAAS…

I’ve found, hovewer, that there is obvious lack of the complete illustration of the integration JAX RS based on Restlet with Spring in the J2EE application.
It is not completely clear how to create JaxRsApplication, restlet Component and JAX RS REST providers and wire them together in the Spring fashion.

Here is the quick practical reference on how to do that:

In short:

  1. Add restlet dependencies to your pom.xml
  2. Pick restlet component name, say “restletComponent”. You need this to reference this component in your web.xml, in the spring config and in your Jax RS application
  3. Add restlet servlet to web.xml
  4. Write JAX RS resources and application
  5. Instantiate them in your spring configuration file with the “restletComponent”

Here is step-by-step howto:

  1. Create new maven J2EE project, add the following dependencies to your pom:


    Take restlet.version based on the latest stable release of the Restlet library, I’ve taken 2.0.1 for my project.

  2. Add the following to your web.xml:

  3. Note: This step is optional one and you may pick completely different approach to create REST resources and application.

    Write your JAX RS application and services

    Again, you may pick another approach, and this is how I did that:
    All the REST-related beans are placed into the* package and all the applications and resources are marked with the spring @Component stereotype annotation.

    These are the resources:

    @Path("/") // this is the root resource
    public class HelloResource {
        private HelloService helloService;
        public HelloMessage createHelloMessage(@QueryParam("recipient") String recipient) {
            return helloService.createHelloMessage(recipient);
        public HelloMessageList queryGreetings(@QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit) {
            return helloService.queryGreetings(offset, limit);
    public class AnotherResource { ... }

    The resources are pretty common to JAX RS, the only thing to mention would be that we marked it with @Component annotation and used autowiring.

    The application that does that may look as follows:

    import org.restlet.Component;
    // all the other import statements are omitted for clarity
    public final class SpringJaxRsApplication extends JaxRsApplication implements InitializingBean, BeanFactoryAware {
        // NOTE: restletComponent instantiation point will be given below (we do it in the spring config)
        private Component component;
         * {@inheritDoc}
        public void afterPropertiesSet() throws Exception {
            final Set> classes = new HashSet>();
            // NOTE: Here we must list all the provider JAX RS classes
            add(new Application() {
                public Set> getClasses() { return classes; }
         * {@inheritDoc}
        public void setBeanFactory(final BeanFactory beanFactory) throws BeansException {
            setObjectFactory(new ObjectFactory() {
                public  T getInstance(Class jaxRsClass) throws InstantiateException {
                // NOTE: We delegated bean instantiation to spring
                    return beanFactory.getBean(jaxRsClass);

    And one final step, instantiate the REST-related entities of that in your spring config:


One of the obvious drawback of this solution is that SpringJaxRsApplication is not reusable and you must specify all the resource classes by hand. However, this could easily be approached by autowiring array of class names that is defined in the spring config to the jax rs application or even scanning the package contents and querying the resource beans.

If you are new to REST you might wanna look to the following JAX RS implementations besides Restlet:

Javascript snippet: “asUtfCodes” function

Sometimes I need to include escaped string sequence to my code (mostly for unit tests), because clearcase (VCS I forced to use by my current employer) chokes when it encounters UTF-8 -encoded source code.

In order to make my life easier, I wrote a small function that transforms a given input string to it’s escaped UTF-16 equivalent.

Here is the function:

function asUtfCodes (charStr) {
var result = "";
for (var pos = 0; pos < charStr.length; ++pos) {
var codeStr = charStr.charCodeAt(pos).toString(16);
var padding = 4 - codeStr.length;
for (var i = 0; i < padding; ++i) {
codeStr = "0" + codeStr;
result = result + "\\u" + codeStr;

return result;

Sample usage (press Ctrl+Shift+J in Chrome and proceed to script console to check it IRL):

asUtfCodes("Привет!")    // results in