Posts Tagged 'java'

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”).

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

	@Override
	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;
		}
	}

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

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

<authentication-manager>
	<authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>

And that’s it!

Advertisements

Java & Multicore

Recently I needed to run some very CPU intensive calculations in Java. In order to harvest the full power of my multicore machine I took a look at Java’s concurrent package. I never used this package before. Either I had some convenient third party library functions at my hand which successfully were able to hide all the multithreading stuff from me, sometimes I struggled with Thread, Runnable and synchronized statements or … I just used another language :P

So here are my results from a short trip into the adventurous realm of multicore programming in Java. To make things a little bit simpler in this post I will demonstrate to run several functions calculating a high Fibonacci number instead of using a more complicated real world example. The calculations will be distributed via a thread pool and all classes used in this example belong to the Java standard library, so there won’t be a need to install any extra packages.

Continue reading ‘Java & Multicore’

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 :/

Java Mocking Frameworks Comparison

I found a very nice comparison of mocking frameworks for Java/JVM. If you already have a basic understanding about mocking and are looking for a good framework with easy to learn syntax this site will definitely be helpful.

However my favourite is Mockito, which comes with a very intuitive syntax and allows mocking by stub methods. Let’s say you have a class Foobar with a public method int callMe(String s) to stub the method use the following code:

Foobar mockedFoobar = mock(Foobar.class);
when(mockedFoobar.callMe("bla")).return(42);

That’s all, just two lines of code and you successfully mocked a method without complicated inheritance strategies :)