Friday, March 13, 2015

Codility Lessions 4 Sorting - NumberOfDiscIntersections Simple Solution

Essentially, we treat the input as a set of line segments with different start and end values. If we sort the lines by their start values, and iterate from the smallest start value line, then for a given line segment, what it overlaps can be calculated by counting the lines which start before the end of the give line segment. After we have to remove this line's start value from the start values array, otherwise we get duplicate counts from other line segments overlapping with the one we already counted. When we remove, any duplicate start values won't matter. I tried to implement this using a Line class, creating two arrayLists for start values and lines. Which is somewhat lots of code.

But for this question, there is another input property we can use. Notice that for the input array A, the end value of A[j] line cannot be smaller than the start value of A[i] line if i<j. So we can just sort the start values array and iterate through input array A. For any A[i] and A[j] where i<j, if end value of A[i]  is larger than start value of A[j], they must overlap.

Also, be careful with integer overflow.

Wednesday, March 4, 2015

A Simple Multi-Tenancy Implementation with Hibernate and Spring

For our implementation of the multi-tenant application, Each tenant's data is kept in a physically separate database instance. For each database instance a connection pool is set up when the application starts. For any http request that is not authenticated, a default connection pool is used, pointing to where the user login info is stored. After login the tenant identifier is stored in the Spring Authentication object, so that the corresponding connection pool for that user can be identified. For Spring Security login, we use hibernate, entity manager, and UserDetailService for user authentication.

The User class implements UserDetails interface, so that after user is authenticated we can retrieve this user instance from security context.



For Spring Security, we have to implements UserDetailService.


Then we have to config Persistence configurations.


Notice that we don't have to config a DataSource bean. Instead, we added additional configuration properties for hibernate. We have to create both MyTenantIdentifierResolver and MyMultiTenantConnectionProvider.

First let's look at the MyTenantIdentifierResolver, which essentially output a string for MyMultiTenantConnectionProvider class to choose the right connection pool.


Inside MyMultiTenantConnectionProvider, we first initialize a map containing all connection pools for all tenant. For the overridden method selectConnectionProvider(String s), the input string is provided by MyTenantIdentifierResolver, and the output is a ConnectionProvider object containing a datasource for the specific tenant.



Lastly all we need to define is a custom ConnectionProvider to hold a DataSource.