Quick post: How to use Groovy multi-line GStrings for single-line messages

Need to put a long string into your source code but don’t want to violate the 80 character line limit (yes, I prefer it)? You can do it by adding a new method to java.lang.String as the following listing shows.

def toSingleLinePattern = ~/\s{2,}/
String.metaClass.toSingleLine = {
    (delegate =~ toSingleLinePattern).replaceAll(' ')
}

println """This could be an error message which is very long
    and which would need to span several lines if you have a line
    length limitation of 80 characters or similar.""".toSingleLine()

How to do logging in Groovy

For some reason I couldn’t find any information about how to do logging in the two Groovy books that are available at work. I have been using Groovy for a few days now and I’m surprised about all the little tweaks and improvements the developers made to reduce code duplication and boilerplate code. For this reason, I figured that there must be a rather straightforward way to do logging in Groovy. And of course, there is one!

Please note that the following was introduced with Groovy version 1.8 and therefore won’t work in earlier versions. I don’t know about any best practices for earlier Groovy versions, but I fear that you may need to do it the way that you are used to, i.e., the Java way.

I’m going to show this using SLF4J as I always try to decouple my program from specific logging frameworks. First of, let’s start with our build.gradle file (gradle project descriptor). Continue reading

Parameterized JUnit tests in Groovy

Need to test a class or method with various values? You can make use of parameterized JUnit tests to accomplish this. And since I’m currently learning Groovy, I’m taking this chance to do it in this neat language (and to keep it as a reminder for some language constructs).

You can make use of parameterized tests using the appropriate JUnit test runner. In case of the following code listing, I’m verifying that my regular expression for Java package names is correct (or at least that it detects a certain amount of invalid ones…). Test input data is obtained from the data() method and passed to the test’s constructor. In the testInvalidPackages() method I’m simply making use of the instance variable pckg, i.e., changing the value.

package de.codecentric.janus.scaffold

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * @author Ben Ripkens <bripkens.dev@gmail.com>
 */
@RunWith(Parameterized.class)
class ScaffoldExecutorValidationTest {
    String pckg
    Scaffold scaffold

    ScaffoldExecutorValidationTest(String pckg) {
        this.pckg = pckg
        scaffold = new Scaffold([filename: 'quickstart.zip'])
    }

    @Parameters static Collection<Object[]> data() {
        def data = ['.', 'com.', '.com', 'com.example.', 'com..example']
        return data.collect { [it] as Object[] }
    }

    @Test(expected=ScaffoldingException.class) void testInvalidPackages() {
        new ScaffoldExecutor(scaffold, pckg)
    }
}

Setting up a Dell 2335dn laser printer

At work, there is a Dell 2335dn laser printer for which there don’t seem to be any Linux drivers. Luckily though, I could get it to work using HP LaserJet 3 drivers. So whenever you don’t find an appropriate driver for your printer, give the aforementioned one a try. Maybe your are luckily and can save yourself some time :-) .

How-to install KeePassX on Ubuntu

Do you have to remember an ever increasing amount of passwords? If you do, then KeePassX might be of interest to you. It’s a password manager which has high security standards and which is additionally available on Microsoft Windows and Mac OS X. If you are running Ubuntu (this probably also applies to recent Debian versions), the following snippet might be of interest to you as it shows how to install version 0.4.3 of this program. After installation, you can find it in your desktop manager’s application menu (under GNOME 2 it’s located in Applications -> Accessories -> KeePassX).

NAME='keepassx-0.4.3'
FILENAME=$NAME'.tar.gz'

echo ':: Installing prerequisites...'
sudo apt-get install libxtst-dev libqt4-dev qt4-qmake

echo ':: Downloading and extracting file...'
wget 'http://downloads.sourceforge.net/keepassx/'$FILENAME
tar xvf $FILENAME

echo ':: Installing...'
cd $NAME
qmake
make
sudo make install

echo ':: Cleaning up...'
cd ..
rm -rf $NAME $FILENAME

How-to install nginx

Since there is so much buzz around nginx, I wanted to give it a try on my small home server. The server is running a desktop edition of Ubuntu 10.04 (I keep it as backup machine in case my laptop breaks), so keep this in mind. The following bash script will download nginx version 1.1.12, its dependencies and install it. Also, a user nginx will be created.

# Start by creating an appropriate user
useradd -r nginx
mkdir /home/nginx
chown nginx:nginx /home/nginx/

# Retrieve nginx dependencies
cd /home/nginx
mkdir library
cd library
wget http://zlib.net/zlib-1.2.5.tar.gz
tar xfz zlib-1.2.5.tar.gz
rm zlib-1.2.5.tar.gz
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.21.tar.gz
tar xfz pcre-8.21.tar.gz
rm pcre-8.21.tar.gz
cd ..

# Installing nginx
wget http://nginx.org/download/nginx-1.1.12.tar.gz
tar xfz nginx-1.1.12.tar.gz
rm nginx-1.1.12.tar.gz
cd nginx-1.1.12
./configure --prefix=/home/nginx \
    --user=nginx \
    --group=nginx \
    --with-pcre=../library/pcre-8.21/ \
    --with-zlib=../library/zlib-1.2.5/
make
make install
cd ..
rm -rf nginx-1.1.12/
chown -R nginx:nginx *
sed -i 's/listen\s*80;/listen 8080;/g' conf/nginx.conf
export NGINX_HOME='/home/nginx/'
export NGINX_PID_FILE=$NGINX_HOME'logs/nginx.pid'

In case you encounter any problems, please refer to the short, but sufficient, official documentation. If it worked out for you, you can now use the following commands to start and stop the server as well as to reload the config.

# Start nginx (runs on port 8080)
su nginx -c $NGINX_HOME'sbin/nginx'

# Reload nginx config
kill -HUP $(cat $NGINX_PID_FILE)

# Stop nginx
kill -QUIT $(cat $NGINX_PID_FILE)

Check out the following blog if you need an init script for nginx.

Installing Rails 3 on a fresh Ubuntu installation

Since I find myself researching the same information a second time, I put it on my blog for further reference. The following steps were everything that is needed to get started with Rails 3 on a fresh Ubuntu 10.10 installation.

# Installing rails, rubygems and its dependencies
sudo apt-get install build-essential ruby1.8-dev libsqlite3-dev
wget http://rubyforge.org/frs/download.php/75574/rubygems-1.8.12.zip
unzip rubygems-1.8.12.zip
cd rubygems-1.8.12.zip
sudo ruby setup.rb
sudo gem install rdoc-data; rdoc-data --install
sudo gem install rails

# create project
rails new .

# only necessary when no JavaScript runtime environment exists
echo "gem 'therubyracer'" >> Gemfile
sudo bundle

# starting the server
rails s

Fixing the unable to initialize TldScanner problem when deploying

With the change to Glassfish 3.3 I encountered the TldScanner problem when deploying a simple EAR file. Since the problem did not occur with Glassfish 3.0.1 and because some of my colleagues were also having problems I investigated the problem today.

The problem is reported by many people in various mailing lists and issue trackers but in all cases the solution wasn’t fixing the problem. After replacing several dependencies (the server log stated sometimes that the problem occurred in a third party library..) and trying various solutions which I had found on the internet, I changed the directory structure and removed all whitespaces from the directory and file names. Even though you might figure that an application server, as mature as Glassfish, might be able to cope with whitespaces in directory names, it is not.

Long story short, I created a symlink in my home directory (/home/ben/odr) which points to the existing checkout at /home/ben/fontys/some semester identifier with whitespace/odr. This solved the TldScanner problem and everything was running fine again. Sometimes the simple solutions are the right ones, even in the Java EE world :-) .

Define JNDI data source for Apache Tomcat

Defining data sources via JNDI has various benefits, e.g. pooling and completely external configuration. The latter is especially important as this avoids putting database credentials into your application. Since I’m currently studying the Spring framework, I also wanted to use another application server. In fact, I wanted to try Apache Tomcat 7, a servlet container.

I have to say that I found the JNDI how-to for Apache Tomcat insufficient and therefore want to share some information that I collected in addition to the how-to.

At first, they show what a context.xml file should look like but they don’t tell you where to put it (ok they lead you to another documentation page). I found the simplest place to be the $CATALINA_BASE/conf/context.xml as this is probably sufficient for most use cases. Please note though that all deployed applications will have access to this data source. The next thing you shouldn’t forget is to put the driver into $CATALINA_BASE/lib/. In combination with the aforementioned how-to this should be all you need to use JNDI data sources with Apache Tomcat.