A template to create log4j Logger objects in Eclipse

In my (server) Java apps, I usually use log4j to keep logs. These days, I actually use SLF4J as a proxy for log4j, mostly because the framework I’m using (Vert.x) uses it.

Over the years I’ve tuned my log format to only store the information I care about, and nothing more than that:

<PatternLayout pattern="[%d{HH:mm:ss.SSS}] %p %c{3} - %m%n" />

so I have a timestamp, the log level (%p), the class name with up to 3 levels of package hierarchy (%c{3}), and the new-line-terminated message (%m%n).

A sample line:

[11:39:36.667] TRACE redis.redis_client.RedisDecoder - received new MultiBulkReply

This format requires a Logger object in all classes that need logging, which requires quite a bit of boilerplate code, e.g.:

private static final Logger LOGGER = LoggerFactory
    .getLogger(SlackRouter.class);

You quickly grow tired of typing all of that. But worry not! Eclipse comes to the rescue!

Setup an Eclipse Template

I created a template that does the work for me: now, all I have to do to add a new Logger object is type log, hit Ctrl + space, and select “Insert logger”.

Just like this:

Adding a Logger

Note that typing “log4” instead of “log” only gives you one option, saving 2 precious key strokes! 😛

Here’s how to set it up for your Eclipse.

  1. Open your Eclipse Preferences menu
  2. Type “java editor templates” in the search bar
    uno
  3. Hit the “New” button
  4. Set “log4j” as name (or whatever you want the shortcut to be), add a description, paste this in the “Pattern” field:
    ${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
    private static final Logger LOGGER = LoggerFactory.getLogger(${enclosing_type}.class);
    

    and hit “OK”
    tre

  5. That’s it!

    If you’re not using SLF4J, all you need to do is change the import code to include the actual class you use.

Could not open the requested socket: Address already in use. Restart Jetty from Eclipse on Mac OSX

I am used to hit on the Play button in Eclipse like hell when developing server apps, so I ran into this issue pretty quickly.

When you’re working with Google App Engine on Mac OSX, pressing that familiar green button after having deployed the app once makes Eclipse complain as in the title. The stop button is grayed out (as it’s controlling the latest instance of Jetty, which didn’t start) and you can’t launch your app without restarting Eclipse.

So, to kill the old Jetty instance you just open a terminal and type:

lsof -i TCP:8888 | grep java | grep LISTEN

Where 8888 is the port on which Jetty is listening (it could be 8080 or something else depending on your configuration), and the first grep is just to stay on the safe side (you don’t want to kill something else). If you’re sure that there’s nothing else listening on that port, just omit it.

The output will be something like

java    33873 myusername   68u  IPv6 0xffffff801a2c1510      0t0  TCP localhost:ddi-tcp-1 (LISTEN)

Then, just type

kill -15 33873

where 33873 is the number in the second column in the output of the previous command.

You can then run the project from Eclipse.

My routine is to keep a terminal window open and just run this one-liner when I run into the error:

kill -15 $(lsof -i TCP:8888 | grep java | grep LISTEN | awk '{ print $2 }')

which does exactly the same thing, but in an automated fashion… it’s just an arrow_up away! 🙂

Ant stopped working after Eclipse update on Mac OSX (<terminated> is shown with no explanation)

After updating Eclipse on my laptop, all of a sudden the built-in version of Ant that ships with Eclipse stopped working.

I right-click on a build.xml files, run it as Ant build but… nothing happens! I don’t get any message in the Eclipse Console (you know, the usual red ones telling you that you screwed up somewhere in the XML file). The only thing I get is a mysterious <terminated> message in the view’s title, followed by the path to the Java executable on my machine.

I kept just using Ant from a shell until I decided it was time for some googling. After searching through bugs I found this comment on a bug, so here’s what you need to do:

  1. go to your Eclipse preferences
  2. go to Ant/Runtime
  3. in the “Classpath” tab, expand the “Ant Home Entries (Default)” list
  4. you should see a bunch of entries like Applications/eclipse/plugins/org.apache.ant_x.y.z.v.../lib/ant*.jar: if you go check, that folder doesn’t exist!
  5. press “Add External JARs” and go to /Applications/eclipse/plugins/, where you should find an org.apache.ant_ folder with a different version than that of the listed entries (in my case I have an org.apache.ant_1.8.3.v20120321-1730 folder)
  6. select and add all jars in the lib folder inside the org.apache.ant_x.y.z folder (the one from the previous step)
  7. select and remove all old jars (those from the non-existing folder), hit apply

now Ant should work again!

By the way, this should be the open bug that tracks this issue if you want to follow it.

Fixing the “An internal error occurred during: “SVN Update” . 68″ error

This should not happen anymore from Eclipse Indigo or newer and Subclipse version whatever, but it happened to me today using Helios.

Long story short: this message means that you have a conflict somewhere in your project, just check which file(s) is/are marked with the conflict icon, and solve the conflict (right click/team/mark resolved… and pick the action you want to perform). That’s it!

Minimal Lambda functions / closures in Java (5 and up!) with generics

This is a thing that I’m sure a lot of Java programmers have come with an implementation for, but no minimal examples were easy to be found when I looked for it. And it was fun to code, too, so I’ll share it!

Many many times I find myself wanting to declare a simple function to be executed on all items in a list, much like I do in Python with lambdas. What I usually do is just write a separate method if I find myself doing this same thing several times, and call that method all over. This is boring, though!

With lambda functions I find this task a little less boring and, most of all, I can use the same scheme wherever I need it and it speeds up my work since my brain seems to enjoy this process much better..

This is the LambdaFunction interface:

/**
 * A function to be executed on all items in a list.
 * 
 * <p>
 * This is a verbose Java equivalent of lambda functions; it's verbose
 * because you must declare a (private anonymous) class to define the lamba
 * function.
 * 
 * <p>
 * This is how you would use it:
 * 
 * <blockquote>
 * 
 * <pre>
 * List<MyClass> myList = Arrays.asList(new MyClass("one"), new MyClass("two"));
 * Utils.executeAll(myList, new LambdaFunction<MyClass>() {
 *     public void execute(MyClass item) {
 *         // call one of MyClass methods
 *         item.foo();
 *     }
 * }
 * </pre>;
 * 
 * </blockquote>; Where of course the {@link LambdaFunction} can be stored to
 * be reused several times.
 * 
 * @author mb
 * 
 * @param <T>
 *            the type of elements in the list on which the lambda function
 *            must be executed
 * @see Utils#callOnAll(List, LambdaFunction)
 * @see Utils#callOnAll(Object[], LambdaFunction)
 */
public static interface LambdaFunction<T> {

    /**
     * The function called on all items in the list.
     * 
     * @param item
     *            the item onto which the function must be called
     */
    public void execute(T item);
}

(The interface is static just because in my code it’s in the same file as the Utils class, but you can put it in a separate file if you want).

As the javadoc explains, you use it in combination with the Utils.callOnAll() method. Here are the two flavors:

public final class Utils {
    /**
     * Calls the argument lambda <tt>function</tt> on all items in the argument
     * <tt>list</tt>.
     * 
     * @param <T>
     *            the type of elements in the list
     * @param list
     *            the list onto which the lambda function must be executed
     * @param function
     *            the function to be executed on all items in the list
     * @see LambdaFunction
     */
    public static <T> void callOnAll(List<T> list, LambdaFunction<T> function) {
        for (T item : list) {
            function.execute(item);
        }
    }

    /**
     * Calls the argument lambda <tt>function</tt> on all items in the argument
     * array.
     * 
     * @param <T>
     *            the type of elements in the list
     * @param items
     *            the items onto which the lambda function must be executed
     * @param function
     *            the function to be executed on all items in the list
     * @see LambdaFunction
     */
    public static <T> void callOnAll(T[] items, LambdaFunction<T> function) {
        for (T item : items) {
            function.execute(item);
        }
    }
}

And this is an example of how I use it:

private static final LambdaFunction<TouchHandler> HANDLER_ENABLER = new LambdaFunction<TouchHandler>() {

        @Override
        public void execute(TouchHandler item) {
            item.setEnabled(true);
        }
    };
Utils.callOnAll(handlers, HANDLER_ENABLER);

Yes, I could have just added a private void enableHandlers(boolean areEnabled) method in this case, but I prefer to pollute my classes with as few private utility methods as possible; private fields are hidden by Eclipse, so I never even pay attention to them. Plus, if I didn’t need to call HANDLER_ENABLER several times I could have had a true(r) lambda function:

Utils.callOnAll(handlers, new LambdaFunction<TouchHandler>() {

        @Override
        public void execute(TouchHandler item) {
            item.setEnabled(true);
        }
    });

Was it simple to implement? Yup. Is it less readable? Not really. Do I love using it? Definitely! 😀

Have JavaHL remember SVN credentials (user/password)

I was forced to move from SVNkit to JavaHL, so I immediately crashed into the poor integration that JavaHL has by default with Eclipse.

I added a new repository, one in which my username is different from the one I use for my laptop, and even though Eclipse prompted me for the password I had no way to change the username. I tried to remove the conf folder from the .subversion one I have in my user’s home, but to no avail. I also wiped the .subversion directory altogether, but still it wanted me to use my local machine’s username.

Googled around, found no solution.

So, what I ended up doing is putting the full repository URL (complete with my username on the remote machine, as in svn+ssh://username@repository/path/to/repo) and exporting my SSH public key to the server. Yes, JavaHL asks you to type your password every. damn. time.

If you never generated your public key, just type ssh-keygen -t rsa in a shell and choose all the default options, they’re fine.

Then, export your key to the repository (one of the most frequent sequence of commands I’m using these days):

cat ~/.ssh/id_rsa.pub | ssh myUser@repository 'mkdir -p .ssh/; cat >> .ssh/authorized_keys'

Of course, replace myUser@repository with your username on the remote repository in the previous command, and you’re good to go 🙂