Thursday, March 23, 2017

LRU Cache

A simple Least Recently Used Cache implementation in Java, with thanks to Chris Wu for the idea.

package demo;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Thanks to http://chriswu.me/blog/a-lru-cache-in-10-lines-of-java/
 *
 * @author Marcel Dullaart
 */
class LRUCache extends LinkedHashMap {

    private Integer sizeLimit;

    LRUCache(Integer size) {
        super(16, 0.75f, true);
        this.sizeLimit = size;
    }

    /**
     * Removes the eldest entry if the {@link #size()} exceeds the {@link #sizeLimit}
     *
     * @param entry the eldest entry
     * @return always false
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry entry) {
        if (size() > sizeLimit) {
            remove(entry.getKey());
        }
        return false;
    }
}

Thursday, September 15, 2016

Replace switch statements using lamda's

Complex switch statements with many possible cases tend to result in cluttered code. When code checkers start to complain about the complexity of a method, it becomes time to refactore that piece, but often that sounds simpler than it actually is.
With lambda's in java 8 these switch statements can easily be simplified resulting in cleaner, easier to read code.
Lets take for example the below switch statement and turn that into a nice and easy to understand piece of code using a Map and some lamba expressions.

public List<string> findUsingSwitch(Bicycle bicycle) {
  switch (bicycle) {
    case RACE:
      return listRacers();
    case ATB:
      return listAtbs();
    case CITY:
      return listCityBikes();
    case HPV:
      return listHumanPoweredVehicles();
    default:
      throw new IllegalArgumentException();
    }
}

Its easy to imagine that such a switch statement can grow and become pretty complex.
In java 8 we now have the ability to use lambda expressions and pass them around to functions. This allows us to replace the switch/case block with a more flexible and more natural implementation.
Lets first start with creating a map that associates the enum with the lambda that produces the result for the given enum value.

private Map<Bicycle, Supplier<List<String>>> typeMap = new HashMap<Bicycle, Supplier<List<String>>>() {
  {
    put(Bicycle.RACE, () -> listRacers());
    put(Bicycle.ATB, () -> listAtbs());
    put(Bicycle.CITY, () -> listCityBikes());
    put(Bicycle.HPV, () -> listHumanPoweredVehicles());
  }
};

Now the find method can be changed to use the lambdas instead:

public List findUsingLambdas(Bicycle bicycle) {
  if (!typeMap.containsKey(bicycle)) {
    throw new IllegalArgumentException(String.format("%s is not supported", bicycle));
  }

  return typeMap.get(bicycle).get();
}

The sources can be found on github.

Replace switch statements using lamda's

Complex switch statements with many possible cases tend to result in cluttered code. When code checkers start to complain about the complexity of a method, it becomes time to refactor that piece, but often that sounds simpler than it actually is.
With lambda's in java 8 these switch statements can easily be simplified resulting in cleaner, easier to read and extend code.
Lets take for example the below switch statement and turn that into a nice and easy to understand piece of code using a Map and some lamba expressions.

public List<string> findUsingSwitch(Bicycle bicycle) {
  switch (bicycle) {
    case RACE:
      return listRacers();
    case ATB:
      return listAtbs();
    case CITY:
      return listCityBikes();
    case HPV:
      return listHumanPoweredVehicles();
    default:
      throw new IllegalArgumentException();
    }
}

Its easy to imagine that such a switch statement can grow and become pretty complex.
In java 8 we now have the ability to use lambda expressions and pass them around to functions. This allows us to replace the switch/case block with a more flexible and more natural implementation.
Lets first start with creating a map that associates the enum with the lambda that produces the result for the given enum value.

private Map<Bicycle, Supplier<List<String>>> typeMap = new HashMap<Bicycle, Supplier<List<String>>>() {
  {
    put(Bicycle.RACE, () -> listRacers());
    put(Bicycle.ATB, () -> listAtbs());
    put(Bicycle.CITY, () -> listCityBikes());
    put(Bicycle.HPV, () -> listHumanPoweredVehicles());
  }
};

Now the find method can be changed to use the lambdas instead:

public List findUsingLambdas(Bicycle bicycle) {
  if (!typeMap.containsKey(bicycle)) {
    throw new IllegalArgumentException(String.format("%s is not supported", bicycle));
  }

  return typeMap.get(bicycle).get();
}


The example sources can be found on github

Sunday, December 20, 2015

Agile culture at spotify

Here are some interesting vid's showing the development culture at spotify, a very interesting variation of scrum organizing development teams.
I think this could work great for companies continuously improving a product or suite of products. But does this also work work for single independent projects? Perhaps its better to stick with the pre defined scrum practise in those cases.

Monday, November 02, 2015

Unit testing a Spring MVC REST service

Properly testing a Spring MVC based REST service controller is made easy using MockMvc.
Validating the results is made easy using both JsonPath and XmlUnit

Tuesday, June 09, 2015

Removing files from svn without removing from the file system

Every now and then it happens that I have shared a project to subversion and noticed that while committing a number of files have been added (albeit not yet committed) to subversion.
Excluding these files from the commit only solves that problem temporarily, with the next commit these same files are again presented as changed files.

Removing these files from the local subversion administration is not hard, but each time I find myself searching again for the correct command, so today I decided to spent a blog on it, although the actual content is just a one-liner:

svn rm --keep-local

This will remove the file from subversion but will leave the files on the file system. This is quite useful with IDE files for instance.

Wednesday, November 19, 2014

Installing a JDK on windows without admin rights

Here at the office I do not have admin rights.
This is a pain because I cannot update the JDK to a version I'd like/have to use.
Well there is an option.

Download the desired JDK from the regular location.
Open the executable file using 7-zip or something similar. The executable contains only a single file named tools.zip. Unzip that file to a location where you want the JDK installed and you have write access to, for instance c:\development\jdk-8.20.
This will create the installation structure, although many of the jar file components are still compressed. These must be de compressed using a tool provided with the JDK itself, unpack200, that is found in jre\bin.
Locate all .pack files using dir *.pack /s/b and de-compress each of them using upack200:

c:\development\jdk-8.20\jre\bin\unpack200.exe -v -r path\file.pack path\file.jar.
The '-v' option provides for verbose output and the '-r' option removes the original pack file afterwards.

Tuesday, August 05, 2014

Mocking the InitialContext

Unit testing with JNDI

One of the issue's with unit tests is that it is not always easy to control the java.naming.InitialContext provided to the object under test.
Mock frameworks cannot create mocks for JRE classes like InitialContext, so how can we solve this challenge?

One solution could be to create a simple implementation for the javax.naming.spi.InitialContextFactory that returns a mock implementation provided by mockito. Through configuration, our implementation is then used.

public class InitialContextFactoryMock implements InitialContextFactory {

  private static Context mockContext;

  /**
    * The mockContext is created here to be able to use the {@link Context}
    * mock object while defining the expectations.
    * Remember to call this method each time a new test case is run.
    * 
    * @return a fresh {@link Context} mock.
    */
  public static Context getMockContext() {
    mockContext = mock(Context.class);

    return mockContext;
  }

  /**
    * This factory returns the {@link Context} mock created earlier.
    */
  public Context getInitialContext(Hashtable environment) throws NamingException {
    return mockContext;
  }
}

To use the InitialContextFactoryMock you need to specify it in the jndi.properties:


java.naming.factory.initial=the.mocks.InitialContextFactoryMock

Tuesday, April 12, 2011

Fine grained authorization with Spring Security 3

For a project I'm currently working on the authorization requuirements are such that we need method level authorization.
The projects will create a REST service whoes functionality I will not describe here, but it is based on Spring MVC, requires authentication based on Kerberos and user ID/password and fine grained authorization based on roles. The roles are taken from the Active Directory.

Since Spring is already used and because we need two distinct manners for authentication, spring security seems to be the best choice for this.
Using spring security, the authorization checks can be configured using annotations on the MVC controller using @PreAuthorize("hasRole('ROLE_USER')") and the like.

Starting with spring security works like a breeze, until you try to step outside of the boundaries.
Setting up simple authentication based on hard coded user ID's with hard coded password and hard coded roles goes like this:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">

    <sec:http auto-config="true">
        <sec:intercept-url pattern="/*" access="ROLE_USER" />
    </sec:http>

    <sec:authentication-manager alias="authenticationManager">
        <sec:authentication-provider>
                <sec:user-service>
                    <sec:user authorities="ROLE_USER"
                        name="jim" password="morisson"/>
                    <sec:user authorities="ROLE_USER,ROLE_OPERATOR"
                        name="stevie" password="vaughan"/>
                    <sec:user authorities="ROLE_USER,ROLE_OPERATOR,ROLE_DEPLOYMENT_ENGINEER"
                        name="brian" password="jones"/>
                </sec:user-service>
        </sec:authentication-provider>
    </sec:authentication-manager>
</beans>

According to the documentation, all you need to do to enable the @PreAuthorize annotation is adding <sec:global-method-security pre-post-annotations="enabled"/>
So I did, but the authorization checks did not kick in at all.
I have been struggling with this for a while until I stumbled over this post on stackoverflow. The solution is as simple as it is strange, I only needed to move the line <sec:global-method-security pre-post-annotations="enabled"/> from the security-context.xml to the dispatcher-servlet.xml. Nowhere else can I find this suggestion, even in Peter Mularien's book its written as:
Instructing Spring Security to use method annotations
We'll also need to make a one-time change to dogstore-security.xml, where we've got the rest of our Spring Security configuration. Simply add the following element right before the <http> declaration:

<global-method-security pre-post-annotations="enabled"/>

It seems that the above declaration registers a bean post-processor that is applied to the context in which it is declared, that means that declaring it in the security context, the post-processor is not applied to beans declared in the web context.

Wednesday, February 02, 2011

Create mock objects in spring configuration

In case you ever need to supply a mock object in spring configuration, here's a snippet that does just that:

<!-- Define the Mockito class as factory for creating the mock -->
<bean id="restTemplate" class="org.mockito.Mockito" factory-method="mock">
  <!-- The constructor contains the full name of the class being mocked -->
  <constructor-arg value="org.springframework.web.client.RestTemplate"/>
</bean>


The defined restTemplate bean can be be referenced in other bean definitions, for instance the object under test.

Wednesday, August 11, 2010

How to test a class that directly uses java.rmi.Naming

While in the process of doing a handover of a project, some pieces of the projects source do not comply with the code standard. In this holiday season the original developer wasn't available, so I made my sleeves wet and hands dirty again, and started fixing it.

The major thing the code lacked was a proper unit test with coverage higher than 80%, well it didn't have a unit test at all.
Adding a unit test normally is not a big deal, but in this case, the class, a simple servlet that connects to a remote RMI object and calls a status method on it, directly uses java.rmi.Naming.
java.rmi.Naming is notorious for its static methods, which are hard to mock when unit testing.
There are great products out there, like powermock that can actually mock static methods, but not in system classes.
I could change the servlet code and provide a wrapper around accessing the java.rmi.Naming class, but I didn't want to change the code.

Instead I chose to not mock java.rmi.Naming, but instead just create my own instance:
@BeforeClass
public static void initNamingRegistry() throws RemoteException {
// Create a local registry with an arbitrary port number
rmiRegistry = LocateRegistry.createRegistry(9901);
This registry is alive and kickin' during the execution of my test suite, so I can now register the mock object that implements the remote business interface:
@Before
public void registerRemoteMock() throws Exception {
// Register the mock of the remote business object
rmiRegistry.bind("testName", remoteMock);
}
Then the actual servlet method can bet tested:
@Test
public void testSomeBehaviour()
// Prepare the mocks
when(requestMock.getParameter("name").thenReturn("val");
...
// Call the test method
testObject.doGet(requestMock, responseMock);

// Verify the calls if needed
verify(remoteMock).doIt();
Nice, clean and simple!

Thursday, June 26, 2008

Passed !!

Grade: P
Score: 75
Comment: This report shows the total points that could have been awarded in each section and the actual amount of points you were awarded. This information is provided in order to give you feedback on your relative strengths on a section basis. The maximum number of points you could have received is 100, minimum to pass is 70.

Class Diagram (44 maximum) .......................... 31
Component Diagram (44 maximum) ...................... 32
Sequence/Collaboration Diagrams (12 maximum) ........ 12

Tuesday, June 17, 2008

SCEA part III

As we say in holland, "the bullit has gone through the church", altough we usually say it in Dutch like: "De kogel is door de kerk", which means something like I have finally done it...
Last week Sunday I've uploaded my assignment, and today I took me essay exams.

So now its waiting, and waiting...
Until the results are published.

Keep you posted.

Monday, March 10, 2008

java.io.NotSerializableException

I can't fully dedicate my time to the SCEA assignment, I am also fulltime working on projects.
Today I ran into a java.io.NotSerializableException.
The stack trace is not at all helpfull, it just says "Caused by: java.io.NotSerializableException: foo.bar.FooBar."
While I am sure that foo.bar.FooBar implements java.io.Serializable.
I checked all the class members and marked some of the members transient (log4j Logger), but still the thing is popping up.

Googling for that exception showed this blog post. As it appeared, their first attempt wasn't very useful, although the idea looked promising.
Their DebugObjectOutputStream doesn't handle private fields, and can't cope with inheritance.
These issues seem to have been resolved in the wicked code itself, but that is a bit too harsh to just get

Browsing the comments posted underneath the post showed a link to Bob Lee's blog where he tackles the same problem.
Although the output generated by his solution isn't as verbose as the other one, it does give the expected results.
This showed me that I missed out on some of the fields.
Great help. Thanks Bob.


Tuesday, February 12, 2008

Creating sequence diagrams

The sequence diagrams are getting complicated.
I am now looking at the benefits that UML 2.0 can bring us in reducing the complexity.
I mean I started off modelling the sequence diagram for the prepare itinerary use case and ended up with a diagram that didn't fit on the screen any more, and I didn't even modelled the business functionality yet, I stopped at the business delegate.
So looking at the new elements in UML 2.0 I found the Interaction Overview diagrams useful for splitting the complex sequence diagram into smaller more usable chunks.
I'd like to soon finish the sequence diagram for this first, but major, use case and then start modelling the class diagram.
When that has been done, most likely I will need to correct my sequence diagrams again to reflect corrected flaws discovered when doing the class diagram.


In the mean time I am having a great discussion on javaranch about a discrepancy in the requirements. The prepare itinerary scenario mentions alternative flights within one hour and less than the selected, while in the given interview with CEO and CIO the flights have a flat price per destination, per seat class. Another thread on javaranch discusses the difference (or lack off) between flight and segment.


Speeking with UB40: both these discussions give me quite some food for thought!

Monday, January 28, 2008

Going thru the requirements

I have some problems getting myself up to speed on this assignment. I can blame lots of things like work load, my wife and children needing atention, but in the end I can only just blame myself. It seems to be hard just starting on it.
But allright finally I started really reading the requirements specs a couple of times.
Going thru them I wrote down the things that seemed unclear.

Then going over the scenario's given, I started out in writing down the entities I discovered in there, these are possible classes and/or attributes.

Now I am working on the creation of the sequence diagrams based on the scenraio's this will also result in class diagrams.

Well I just must make sure that I keep this up and continue...

Monday, January 21, 2008

Using stereotypes to describe J2EE components

For the SCEA assignment the architecture needs to be documented using UML.
Most architectures will have J2EE components like EJB's or servlets.
When these are documented you can opt to fully document each EJB, meaning adding all interfaces as separate elements on a class diagram, and incorporating the complete message flow in sequence diagrams containing all standard EJB message calls, like ejbCreate, etc.
I think that documenting the design and architecture in such a way will clutter the diagrams too much, thereby making the design/architecture harder to read.

Simplifying the diagrams by adding stereotypes to these elements, like &lt;ejb&gt; makes reading the the design/architecture easier and keeps the focus on the essential parts.

Sun has documented some annotations they use in their pattern catalog.

In addition to these stereotypes I will add Stateless/Stateful to designate the different session beans when needed, and maybe come up with some additional stereotypes when necessary.

Thursday, January 17, 2008

Netbeans 6.0 Keyboard shortcuts

I am trying to switch from eclipse to Netbeans when doing some Java coding.
The biggest problem that came up is the keyboard shortcuts, obviously they all differ, so I miss the ones I learned to love and use a lot in eclipse, like pressing Ctrl-1, in eclipse this opens an assistant that helps you resolve compilation problems.

I found a link that at least shows some of the shortcuts, and one that describes where to find a keyboard shortcut list in the netbeans installation. The shortcuts.pdf file also contains a link to a wiki page that describes the keyboard shortcuts specification.

From the wiki page I learned that the shortcut I so desperately need is Alt + Enter, as explained in the 'Coding in Java' section under 'Show suggestion/Tip/Hint'.


Wednesday, January 02, 2008

SCEA Part I

On December 14th I passed for the first part of the Sun Certified Enterprise Architect exam (SCEA), with a score of 93%.
Immediately after this multiple choice exam I registered for its follow-up: the assignment.
The assignment consists of some requirements, a business domain model and use cases for a flight booking system for the airliner Fly By Night. Due to the non diclosure agreement I have signed when registering for the assignment, I cannot write about the assignment and my solution in much detail, but I will try to keep a record of my doings here on the blog from now on.

Friday, October 05, 2007

Using spring's webflow package

As an architect I get a lot of challenging questions.
Like this week, a team of the company I am currently working for needs to migrate a number of simple applications written in PHP to a J2EE environment.
In addition to this, the first release will run as standalone web applications while in the (near) future they need to be incorporated into the soon to be released company web portal.
So I needed to come up with a way that simplifies the transition of a web application into a portlet application.
Since almost any web application can be in different states, as is the case with these applications, I thought of Spring's webflow package.
Spring's webflow uses either Spring Web MVC or Spring Portlet MVC underneath, so is it possible to easily swap either of them without changing the code?

Let's find out...