Archive for the 'code snippets' Category

Custom Authentication Provider in Spring

The Spring Security module supports by default some standard ways to retrieve user information for authentication from databases, LDAP or other commonly used storages. But unfortunately the Spring documentation does not say much about creating connections to custom data sources. There are actually several different ways to do it.

But let’s say we have a Spring MVC application with a login form which contains a user name and password field, but the application does not use any of the supported methods to store the user data. How can we authenticate the user anyway?

The easiest way in my opinion is to create a new authentication provider. So we simply need to implement the AuthenticationProvider interface.

The authenticate() function of the class must return an UsernamePasswordAuthenticationToken instance if the authentication is successful or null otherwise. You can choose another token, simple check the classes implementing AbstractAuthenticationToken. But for our scenario this should be enough.

It is important to populate the list of authorities we grant the user. I used the standard user role (“ROLE_USER”).

In the real-world you might want to add a member variable to the authentication provider pointing to a bean which contains the code for authenticating an user, here I just hard-coded it (name must be “admin”, password “system”).

public class CustomAuthenticationProvider implements AuthenticationProvider {

	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String name = authentication.getName();
		String password = authentication.getCredentials().toString();
		if (name.equals("admin") && password.equals("system")) {
			List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
			Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
			return auth;
		} else {
			return null;

	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);

Now we need to declare the new authentication provider in our configuration:

	<authentication-provider ref="customAuthenticationProvider"/>

And that’s it!

Simple Multi-Threaded Application in Haskell

Haskell has a powerful concurrency library which is surprisingly easy to use. The Control.Concurrent library is shipped with the standard installation of ghc and provides everything needed to get started.

As a small test I want to write a programme which reads numbers from stdin, spawns a new process to calculate the Fibonacci number for each input on a different CPU and prints the result to stdout.

First we need a function which is called when spawning a new process, which should calculate the result and print it to the console. In my case this is a simple IO Monad, which gets a MVar as it’s first argument. The function will wait for input from the MVar and then call the Fibonacci function.

This MVar can be thought of as a synchronised box where a thread can store a value and another thread can read from it. So MVars are just the poor men’s message channel which can hold one value at the time only. Of course there are also real channels in Haskell which act like the message queues in Scala or Erlang, see Control.Concurrent.Chan for more informations.

printResult mvar =  do
	value <- takeMVar mvar
	print $ "fib(" ++ show value ++ ")=" ++ show (fib value)

fib 0 = 0
fib 1 = 1
fib n =  fib (n - 1) + fib (n - 2)

Now we need to read the input from stdin, create a MVar object and invoke the printResult function. The cool thing about Haskell is the forkIO function which is really convenient. It takes an arbitrary IO expr and invokes it in a new thread:

import Control.Monad -- needed for "forever"
import System.Exit     -- needed for exitSuccess

main = forever $ do
	line <- getLine
	when (line == "quit") exitSuccess
	mvar <- newEmptyMVar
	forkIO $ printResult mvar
	putMVar mvar (read line :: Integer)

Now we have to compile our programme with the “-threaded” flag:

ghc -threaded fib.hs -o fib

The RTS allows us now to define the number of processors the application runs on with the -Nnum flag. If I want to use three processors for parallelisation I can run the programme simply with:

./fib +RTS -N4

Java: Casting to Array

OK, here’s the problem:

I want to convert a List to an Integer[]:

List<Integer> intList = ...
Integer[] intArray = (Integer[]) intList.toArray();

throws: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

This code doesn’t work, because of type incompatibility. The method toArray() returns an Object[] array but I want to have an Integer[] array instead. The solution is a little bit ugly:

List<Integer> intList = ...
Integer[] intArray =  intList.toArray(new Integer[0]);

It’s interesting, I never stumbled over this issue before, however I want toArray() to work as expected for generic types and already returning an integer array :/

How To Catch “Kill” Events in a C# console application

The fist step to catch a kill event in a C#/.NET console application is to install a “ConsoleCtrlCheck” HandlerRoutine. The HandlerRoutine will be called whenever the user presses CTRL+C or clicking on the X to close the console window.

So we have to define a delegate type for the HandlerRoutine then and import SetConsoleCtrlHandler from Kernel32.dll.

using System.Runtime.InteropServices;
class Foobar
     #region unmanaged

        /// <summary>
        /// This function sets the handler for kill events.
        /// </summary>
        /// <param name="Handler"></param>
        /// <param name="Add"></param>
        /// <returns></returns>
        public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

        //delegate type to be used of the handler routine
        public delegate bool HandlerRoutine(CtrlTypes CtrlType);

        // control messages
        public enum CtrlTypes
            CTRL_C_EVENT = 0,
            CTRL_LOGOFF_EVENT = 5,


Now we need to implement the handler function ConsoleCtrlCheck and define this function as our ConsoleCtrlHandler function in the main method.

        /// <summary>
        /// This method will be called if the user closes the console window or presses CTRL+C
        /// </summary>
        /// <param name="ctrlType"></param>
        /// <returns>always true</returns>
        private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
            // TODO: implement exit handler routine
            return true;

        static void Main(string[] args)

            HandlerRoutine hr = new HandlerRoutine(ConsoleCtrlCheck);
            // we have to keep the handler routine alive during the execution of the program,
            // because the garbage collector will destroy it after any CTRL event
            SetConsoleCtrlHandler(hr, true);

Iterating over Attributes of a Python Object

Today I needed to extract all attributes and their current value from a Python object. This is usually very handy for overriding __str__ or implementing a to_xml method. This should do the trick:

# functional style
def my_fancy_attribute_getter(self):
    attr_and_values = ((attr, getattr(self, attr)) for attr in dir(self) if not attr.startswith("__"))
    return [(attr, value) for attr, value in attr_and_values if not callable(value)]

# imperative style
def my_fancy_attribute_getter(self):
    result = []
    for attr in dir(self):
        if not attr.startswith("__"):
            value = getattr(self, attr)
            if not callable(value):
                result.append((attr, value))
    return result

Of course the line 4 can be changed to get method names too. All attributes beginning with “__” are considered to be private and should not be returned.

There is another shorter way to do this. Every Python object has a __dict__ attribute which returns all attributes, methods and their values as dictionary:

def my_even_fancier_attribute_getter(self):
    return [(attr, value) for attr, value in self.__dict__.items() if not callable(value)]

How To Catch “Kill” Events with Python

Currently I’m working on a small MRCPv2 client written in Python, which is part of a bigger project at my laboratory. The client is started remotely by a program which controls and monitors several applications in the whole network and is stopped by it again.

In the Linux world catching “kill events” would be a simple task, to shut down another program a process just has to send a SIGTERM signal which can be caught be Python easily using the signal module which comes with every Python installation. However, on Windows things are a little bit harder, because the operating system never produces SIGTERM (and SIGILL) events according to the signal.h documentation from MSDN. That’s why it took me some time to figure out how to catch “kill” events under Windows with Python.

First of all, there are two different ways to close a program in Windows using the .NET API. The first one is to use Process.Kill which is the Microsoft version of SIGKILL and there is Process.CloseMainWindow which works similar to SIGTERM. To catch the latter one with Python you have to install the pywin32 library and define a handler by using win32api.SetControlCtrlHandler.

Here is a small example how to install an “exit handler” under Linux or Windows:

import os, sys
def set_exit_handler(func):
	if == "nt":
			import win32api
			win32api.SetConsoleCtrlHandler(func, True)
		except ImportError:
			version = “.”.join(map(str, sys.version_info[:2]))
			raise Exception(”pywin32 not installed for Python ” + version)
		import signal
		signal.signal(signal.SIGTERM, func)

Use it like this:

if __name__ == "__main__":
	def on_exit(sig, func=None):
		print "exit handler triggered"
		import time
	print "Press  to quit"
	print "quit!"

Edit: I’ve cleaned up the code, this version should work with Python 2.4 and 2.6, I didn’t tried it with Python 3000 yet.

Resizing Image Files with Python

Yesterday I came back from my holidays in Korea with a whole bunch of pictures which I now want to upload to my website to share them with my friends. Usually I take high resolution pictures with a size of 3056×1334 pixel. That’s of course to big for publishing them in the internet, so I wrote a small python script to convert them to 800×600 automatically by using the Unix convert command:

#!/usr/bin/env python
  1. -*- coding: utf-8 -*-
import sys import commands def convert(file, resize="800x600", prefix="small"): try: cmd = "convert -resize " + resize + " " + file + " " + prefix + "_" + file commands.getstatusoutput(cmd) except e: print e def usage(prog): print "Usage:", prog, "-r RESIZE -p PREFIX FILES..." if __name__ == "__main__": argv = sys.argv[1:] if len(argv) <= 1: usage(sys.argv[0]) sys.exit(-1) resize = "800x600" prefix = "small" for i in range(len(argv)): arg = argv[i] if arg == "-r" and i+1 < len(argv): resize = argv[i+1] elif arg == "-p" and i+1 < len(argv): prefix = argv[i+1] elif argv[i-1] != "-r" or argv[i-1] != "-p": convert(arg, resize, prefix)

Run the script with *.jpg and it will convert all jpg file into 800×600 pixel images while preserving the original file and creating new ones named “small_ORIGINALFILENAME”. Use the parameters “-r” and “-p” to define the resize rate or to change the prefix, see man convert for more details.