Friday, November 30, 2012

Exploring open source licenses

A presentation to remind me on the (well-known) licenses out there.

Addendum:

1. License for SaaS. AGPL (v1 and v3) are two copyleft licenses that cover this. Again, the rationale behind them is to be able to provide source code for software being used over the web. v1 is very similar to GPL v2 and v3 is on the lines of GPL v3.
2. EPL. A business-friendly license having weaker copyleft license than GPL. Not compatible with GPL and hence a work combining GPL and EPL cannot be redistributed. EPL requires distribution of a separate license (hence not very much in the free spirit) for the original work in the software which are supported by patents. EPL also contains a patent-retaliation clause which causes the contract between the author and user to terminate when the user initiates a lawsuit for patent infringement against the author.

Wednesday, November 28, 2012

Don’t let tx:annotation-driven get you


When we start developing a new application, we typically have a single data source that we define and all of our business logic revolves around getting data back and forth the data source. As the application matures, we often run into scenarios where we need to depend on jars given my others or we give out our jars to others for them to use. With Spring involved, the context also becomes part of the contract between the two sub-systems. Here is where tx:annotation-driven can get you. Typically, we define a PlatformTransactionManager of org.springframework.jdbc.datasource.DataSourceTransactionManager and bind it to the datasource that it should manage.
    <bean id="testerDataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
        <property name="url" value="${tester.datasource.url}" />
        <property name="username" value="${tester.datasource.username}" />
        <property name="password" value="${tester.datasource.password}" />
    </bean>
    <bean id="testerTransactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="testerDataSource" />
    </bean>
Next, to achieve declarative transactional functionality on specific methods in our service, we can use tx:advice in conjunction with aop:pointcut to indicate the advice that will act on the methods matching the pointcut. However, I prefer defining annotations on the service method itself to effect this declaratively. The upside of this, in my opinion, is that the reader of the code is clearly made aware of what are the transactional boundaries the service method is going to honor.
    @Transactional
    public void getReferenceData() {
        referenceDataDAO.getReferenceData();
    }
From Spring’s manual:
Declaring transaction semantics directly in the Java source code puts the declarations much closer to the affected code. There is not much danger of undue coupling, because code that is meant to be used transactionally is almost always deployed that way anyway.
To get @Transactional to work its magic, i.e. create a proxy which does the heavy lifting of beginning the transaction, delegating the call to the actual class, and either committing or rolling back the transaction based on the result of the call, we need to inform Spring to scan all beans that have this annotation on it. We inform Spring using the “tx:annotation-driven” directive. It is a namespace handler which scans all beans in the Spring container to proxy all methods that have been annotated with @Transactional. The @Transactional can also be placed at the class level, when it is applicable to all methods in the class. So this namespace handler will by default look for a bean named ‘transactionManager’ of class PlatformTransactionManager. If your transaction manager bean happens to be named any differently, you have to state it explicitly. Another note of caution from Spring:
Method visibility and @Transactional
When using proxies, you should apply the @Transactionalannotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the@Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (using mode=”aspectj”) if you need to annotate non-public methods.
Using the “proxy-target-classes” clause, we are able to choose whether we create interface-based JDK proxies or CGLIB based proxies. The former will only work if the class you are proxying is implementing an interface whereas CGLIB-based ones work with either one. OK, so far so good, how is that tx:annotation-driven is going to get me? Just when it is all so comfortable, there is another data source that now comes in the context, either because you imported someone else’s jar or because you started talking to a new data source, tx:annotation-driven will try to hijack any @Transactional annotations intended for those data sources as well and ask the existing transaction manager to try and manage it. All that the transaction manager does is hold a connection from the data source it had been configured with in a threadlocal. When trying to manage a hijacked data source the threadlocal that it has kept with it is non-consequential in rolling back the transaction if required. The worst part is that there is no error that is thrown, just that the effect will not happen.
On a related note, because the connection is held in a threadlocal, if you are spawning threads or delegating control to other threads from a  method that is annotated with @Transactional, all bets are off and you might end up with infinite waits or deadlocks.
So, what is the recommended solution? Spring suggests that we qualify your transaction managers and rather than giving a bare @Transactional, specify the transaction manager (via qualifier) that you intend to use. In addition to this, one can also choose to avoid specifying the transaction manager when specifying the tx:annotation-driven which will force every user of @Transactional to specify the transaction manager it wishes to use (otherwise the container throws an exception saying that it didn’t find a bean with the name ‘transactionManager’). While this is more work, I think it is worth the clarity it provides and makes it explicit for users of the service method in other contexts.
References:
1. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative
2. Test bed available at https://github.com/kilokahn/spring-testers/tree/master/spring-tx-annotation-tester

Wednesday, November 21, 2012

My first one... on blogspot :)

I thought I should have a place where I can store all of the random thoughts that I come across everyday. Initially, I was maintaining a blog at my workplace, but for ready access I am thinking I will link it to my gmail account. It would be interesting to see if I can export blogs from there (apparently it is a wordpress based platform) in here. Update: I was able to import most blogs - yay! Have to blur out all the firm specific details in there before publishing them which reminds me that I need to install something like GIMP which can give me a blur tool rather than my present approach of using erase from mspaint! :)

Final note of caution: This is meant more as a place where I vent out my thoughts and rants on where and how (mostly technology) issues can be bettered.

Thursday, November 1, 2012

Spring PropertyPlaceholderConfigurer Tip

With the increased scrutiny on preferring to keep passwords in files and not as part of the source code, our reliance on PropertyPlaceholderConfigurer (PPC) has greatly increased. An important property of a PPC is the ignoreUnresolvablePlaceholders which is by default set to false. Setting this to false means that if any placeholders being passed to it were not resolved by it, it throws an exception and the entire context load fails. With the existence of multiple PPC's in a spring context (many of our own plus a few from all the transitive contexts we load), it helps to understand the interplay between them. Ideally every modules' that defines a PPC should necessarily have it's ignoreUnresolvablePlaceholders to true - and most do it as it will cause a context failure on loading. However, one may argue that the topmost context may need to know if all properties from all contexts were correctly resolved. By setting the ignoreUnresolvablePlaceholders to true, you may end up loading the context but having placeholders unresolved. The order in which the different PPC's are consulted is determined by the order property. However, if it is not defined, it defaults to Integer.MAX_VALUE. If order is not defined in any of the PPC's, the order is slightly non-deterministic but will mostly correspond to the order in which they are defined. The reason I say mostly is because Spring can choose to eagerly initialize beans to resolve circular dependencies. This is not limited to PPC's but also encompasses our vanilla beans referring other beans. This has been a topic that I believe we don't really pay a lot of attention to - but bites when you are least expecting. Anyway, there is a spring ticket out there to also have an "order" for vanilla beans as well. Coming back to ensuring that the context load is successful only when all placeholders have been able to be resolved - you can define an empty PPC that will act as the signaller for any unresolved placeholders. We will not define any locations for this PPC, and will have an order that is the highest among all - say Integer.MAX_VALUE with the default value of ignoreUnresolvablePlaceholders as false. Since this is the last guy that will get triggered, any unresolved placeholders will be flagged and context load stopped. Ofcourse this depends on the premise that the contexts (from different jars) that the topmost context loads will not have PPC's that are defined without order (defaulting to Integer.MAX_VALUE) and hence will not get loaded after the empty PPC in the topmost context.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="ppc1"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>file:///tmp/p1.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="order" value="10000" />
    </bean>

    <bean id="ppc2"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>file:///tmp/p2.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="order" value="10001" />
    </bean>

    <bean id="overallPPC"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="20000" />
    </bean>

    <bean id="simpleBean" class="com.kilo.SimpleBean">
        <property name="property1" value="${com.kilo.property1}" />
        <property name="property2" value="${com.kilo.property2}" />
        <property name="property3" value="${com.kilo.property3}" />
        <property name="property4" value="${com.kilo.property4}" />
    </bean>

</beans>

So all you nice people out there giving out their jars with spring contexts to others, please ensure that your set an order of your PPC other than the default of Integer.MAX_VALUE. A good rule of thumb could be to use 10000-90000 for our own non-toplevel PPC.

References:

1. http://tarlogonjava.blogspot.in/2009/02/tips-regarding-springs.html
2. Sample setup available at https://github.com/kilokahn/spring-testers/tree/master/spring-ppc-tester