Как коммунизм помогает либертарианству

Збавный пример дилемы для хакеров с пролибертарианским мировозрением.
Хакер из WhisperSystems, создателей защищённого месенджера Signal (AppStore, GooglePlay)  который Сноуден советовал, написал программу для защищённой от прослушки радиосвязи USRP.
Даже добавил в описание программы анархисткий призыв «Dismantle the state, fight the police».

Лицензию для программы он выбрал GPLv3. Лично я в шутку называю эту лицензию «коммунистической» поскольку она отребует делиться своими доработками. Это делает эту лицензию неудобной для бизнесе: ты взял программу, потратил силы и доработал её и теперь хочешь заработать денег но вместо этого вынужден бесплатно делится своими наработками с конкурентами.
Я даже иногда я прошу авторов программ поменять лицензию на дружественную к бизнесу Apache Commons  v2 которая позволяет делать изменения и не публиковать их. Обычно это работает классно — ты берёшь код, подпиливаешь его под свои нужды, если видишь что часть можно законтрибьютить в оригинальный проект — отправляешь.  А то что нужно чисто тебе оставляешь у себя.

А теперь ситуация: чувак из компании которая делает электроные системы для государственой гебни попросил автора-анархиста поменять лицензию его программы на такую которая позволит им её использовать, чем изрядно посмешил всех.


Кстати  это  одна из причин почему большинство криптографических программ идут с лицензией GPL


[LinkSet] Compatibility

Theoretical part


Articles from Oracle


Six kinds of compatibility

Each Joda-Time relase has descriptions of incompatible changes categorized by six kinds:

Compatibility between 2.8 and 2.9
Build system — Yes
Binary compatible — Yes
Source compatible — Yes
Serialization compatible — Yes
Data compatible — Yes
— DateTimeZone data updated to version 2015g
Semantic compatible — Yes

When binary compatibilities are broken then Majour Version changed. For example v2.0 changelist

Explanation from  Stephen Colebourne, author of Joda-Time:

Build system

Not part of compatibility, just a fact about the build system in use

Example:  in v2.2

 - Ant build removed. Build only on Maven now.

Also, I think, it may be changing in artifact coordinates: groupId, artifactId or even changed repository. Maybe some changes in manifest, for example required dependencies. Or added OSGI manifest info. Maybe some classes was repackaged. Or old artifact was built with ANT and doesn’t contains a Maven’s pom.xml manifest like horrible Xerex library  and then was mavenized.

It also may be recompilation with optimizations or without debug information.

But I think that changing in packaging may be a separate kind of compatibility change.

Binary compatible and Source compatible

Whether the whole API is binary compatible or source compatible. See this document

Serialization compatible

Whether the serialization format is compatible with the previous version.

Data compatible

Whether the data, time-zone data in this case, has changed.

For example: some time zone was changed or even removed. If your database stores old timezone id and application trying to create a date object with this timezone id you’ll get an exception.

Semantic compatible

Whether there is some other semantic change. This is relevant when the classes and methods have not changed, but the meaning of a method has.

See section Serialization incompitables below

For example:  v2.0 has a lot of semantic changes

Previously, DateTimeZone.forID matched time zone names case-insensitively, now it is case-sensitive

I think it always hard to separate semantic changes when dealing with bugs. For example, JDK has bug when using null as key in Map

And that was a question is this a bug or feature.

Another one example, is Apache Commons Lang library. In version 3 the methods StringUtils.isAlpha(), isNumeric() and isAlphanumeric() now all return false when passed an empty String. Previously they returned true.

Semantic looks like correlated with behavior compatibility. When changed not signatures but they flow or contract.

Also it’s often situation when behavior was just undefined by contract. For example old class Vector doesn’t declare behavior about removing elements during iteration.  That’s why was created new class ArrayList and Vector was accepted as Superseded.
So, deprecation, as any changes in contract may be also some kind of semantic change.


Serialization incompitables

Compatible incopatibility

Also I think that it should be some kind of «reverse compatibility» that means a contract usage. For example, I saw an issue when subclass of HashMap doesn’t follow a contract. This change was compatible in all ways but all clients become incompatible. How to predict it, I don’t know.

Each of developer has experience when you can’t change something in your API because there is some clients that abuse it or implemented incorrectly. So it should have it’s own classification and developers should think about this kind of reverse incompatibility.

Complexity compatibility

I mean the complexity of program in wide sense: algorithm speed, it’s derivate and consumption of resources (memory, i/o, CPU, disk space), and even source code beautification and structural changes like refactoring. You know,  some algorithms may use more memory but use low processor.

For example, in some early versions of 64 bit JDK your application may fail with OutOfMemory error. This was change absolutely compatible in all categories mentioned before.

Another one sample is when new version of program is working more slowly than previous.

It may not change a contract and flow or anything else may it’s also may be changes that requires an attention.


Tool for checking API and BPI

JAR Hell

[LinkSet] Dependency duplicates in Maven and Jar Hell with Java Classloader

Theoretical part:
Java Classloader

Maven: Introduction to the Dependency Mechanism

What is JAR hell? (Or is it classpath hell? Or dependency hell?)

Jar Hell made Easy — Demystifying the classpath with jHades
See JHades documentation, it very useful to find overlapping jars.

Another tool for dealing with Jar Hell is Weblogic Classloader Analysis Tool.

One of the most problematic dependency is Xeres Xerces Hell. It’s a good example how not to do library.

This presentation is a great resource about Jar Hell and the different type of classpath related exceptions:

But little bit boring.

Maven Dependency Wrangling

dealing with dependency chain issues in maven

Maven Enforcer plugin has extra rule
Ban Duplicate Classes
Also it should be very useful if you have legacy project that still runs under Java 6 or 7 you should avoid dependencies compiled with never Java 8.
You can use enforceBytecodeVersion

Please also make sure that you also specified requireJavaVersion (to compile), requireUpperBoundDeps, requireReleaseDeps, requirePluginVersions and other useful standard rules .

Also if you have a submodules in project it will be also useful ono-extra-enforcer-rules

So, your enforcer rules may looks like:

                        <!-- will only display a warning but does not fail the build. -->
                        <message>Please consider using the maven-invoker-plugin (!</message>
                        <message>No Snapshots Allowed!</message>
                        <!-- 'uniqueVersions' (default:false) can be set to true if you want to compare the timestamped SNAPSHOTs  -->
                        <!-- <uniqueVersions>true</uniqueVersions> -->
                        <message>The reactor is not valid</message>
                        <message>Best Practice is to always define plugin versions!</message>
                            <!-- example of ignoring one specific class -->

                            <!-- example of ignoring with wildcards -->
                            <!-- guava in parent is too old, so allow to override it -->

Two attempts to find duplicated classes with Maven
Remove duplicate classes the agile way: Maven Duplicate Finder Plugin

Finding Duplicate Class Definitions Using Maven

Both of this plugins are discussed here:
Figuring out duplicate class definitions using the Analyze goal

Also maven-shade-plugin does check for overlapping classes during packaging of uber-jar.

Resolving conflicts using the dependency:tree -Dverbose
It shows which dependencies are duplicated (omitted for duplicate), with are evicted with newer version (version managed from 1.6) but it doesn’t show which dependencies was excluded.

Another one good thing that worst to do is enable Failing the build on dependency analysis warnings. Note: it binded to verify phase that runed after package.

JDEPS Java Dependency Analysis Tool from JDK 8

Also some related articles

Versions compitable

For example changelog of Joda-Time v2.9

Compatibility with 2.8

Build system — Yes
Binary compatible — Yes
Source compatible — Yes
Serialization compatible — Yes
Data compatible — Yes
— DateTimeZone data updated to version 2015g
Semantic compatible — Yes

See another [Linkset] Compatibility


It is possible a situation when some two libraries wanting to use the same dependency but of different versions. Unfortunately, in this cases we can’t manage this and should use -nodep versions.
Finally this problem will be resolved in JDK 9 Jigsaw: a jar can be declared as a module and it will run in it’s own isolated class loader, that reads class files from other similar module class loaders in an OSGI sort of way.
This will allow multiple versions of the same Jar to coexist in the same application if needed.

Working with deprecation

Upgrading of dependncies may require to remove some old codebase that depends on them.
This is also should be done in right way, so here some links that may helps:
* JEP 277
* Dr. Deprecator Prescriptions: important things that you should know about obsolete Java API

Speed up maven build

It’s also related topic. The main reason why I decided to add it here is because usually during speeding up build you will find a lot of problems with dependency graph.
It will helps you to make yoir project more modulized. Also for example paralell build may fails if your tests are in conflict (shares same resources, for example integration tests may use the same port).

Power Assert in Vim

Power Assert for Java and others

Peter Niederwieser, creator of Spock, the best testing framework ever, also contributed to Groovy programming language a very handy feature: Power Asserts.

int x = 1;
assert x == 2;

// Output:             
// Assertion failed:
// assert x == 2
//        | |
//        1 false

As you can see, we can see each value of each statement, and this is very cool, especially for unit tests.
It makes all this JUnit bullshit like assertEquals(), assertTrue, assertNull, and all matchers like Hamcrest absolutely unneeded.
I really hate all matchers like FEST or Hamcest, because they aren’t natural and repeat code itself.

So now you can breathe freely without any repeating yourself.

You can see a talk where Peter Niederwieser present Spock specifications

Also Peter created Power Asserts lib for Scala

Unfortunately, you can’t make a Power Asserts in Java, because it doesn’t have a AST preprocessor.

If you, like me, have a big project with tests written in Java+JUnit, the only one way that I found, is convert them to Groovy (in 99% just change file extension from Java to Groovy) or you can compile your tests with groovyc — it’s Groovy Compiler but compiles Java too as well.
After compiling with groovyc asserts in Java behaves like in Groovy. Maybe this is the only one case when something written in Java works differently when compiled with Groovy.

For example here is simple test in Java

import org.junit.Test

class UserTest {
    public void testName() {
        String username = "olololo";
        assert username.equals("trololo");


After compiling with groovyc it’s decompiled bytecode will looks like:

// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.powerassert.AssertionRenderer;
import org.codehaus.groovy.runtime.powerassert.ValueRecorder;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.junit.Test;

public class UserTest implements GroovyObject {
    public UserTestGroovy() {
        CallSite[] var1 = $getCallSiteArray();
        MetaClass var2 = this.$getStaticMetaClass();
        this.metaClass = var2;

    public void testName() {
        CallSite[] var1 = $getCallSiteArray();
        String username = "olololo";
        ValueRecorder var3 = new ValueRecorder();

        try {
            CallSite var10000 = var1[0];
            var3.record(username, 8);
            Object var6 =, "trololo");
            var3.record(var6, 17);
            if(DefaultTypeTransformation.booleanUnbox(var6)) {
            } else {
                ScriptBytecodeAdapter.assertFailed(AssertionRenderer.render("assert username.equals(\"trololo\")", var3), (Object)null);

        } catch (Throwable var5) {
            throw var5;

As you can see, it uses ValueRecorder to store all evaluated expressions and it will render a source code line. And it may be executed as class file (may require groovy-all dependency in classpath):

Assertion failed: 

assert username.equals("trololo")
       |        |
       olololo  false

	at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(
	at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.assertFailed(
	at com.github.stokito.UserTest.testName(

Unfortunately currently IntelliJ can’t compile Java files with Groovyc. It always compiles *.java files with javac.
I created an issue Allow groovyc as compiler for Java classes, please vote for it.

Power Asserts in other languages


does not exist but authors know about Power Assertions and had intentions to do them.

.NET languages

JavaScript for TypeScript for Cofee Script


There is a gem and here is presentation from author: for Pry REPL

Others XCTest by Swift for Crystal (static Ruby) for Elixir for Rust for Vim script

TODO: write about power assets in

Always use interfaces for dependency injection

I working on a big legacy project that uses Spring IoC. And when it started I see in console warning messages like:

WARN  org.springframework.aop.framework.Cglib2AopProxy - Unable to proxy method [public final javax.sql.DataSource] because it is final: All calls to this method via a proxy will be routed directly to the proxy.

Here a sample code:

public class UserServiceImpl implements UserService {


public class UserController {

    UserServiceImpl  userService; // Here a problem: we declared field as concrete class UserServiceImpl  instead of interface UserService


As I found it happens when fields autowired as concrete class instead of injection by interface.

According to Spring AOP documentation:

Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. (JDK dynamic proxies are preferred whenever you have a choice).
If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied. If the target object does not implement any interfaces then a CGLIB proxy will be created.

Thus since userService injected by concrete class UserServiceImpl instead of interface UserService, so Spriong IoC tries to create a proxy class via CGLIB bytecode magic that shows this error message.

Also this CGLIB magic proxying may be disabled by configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <ehcache:annotation-driven cache-manager="genericCacheManager" proxy-target-class="false"/>
    <tx:annotation-driven proxy-target-class="false"/>
    <aop:aspectj-autoproxy proxy-target-class="false"/>

In this case this exception will be thrown during runtime:

Caused by: java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy56 implementing,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [] for property ‘userService’: no matching editors or conversion strategy found

To fix this we just need to use autowiring by interface and this is in common simple refactoring.

Please vote for this feature request to make IntellijIdea helpful in this New inspection: Use dependency injection by interface instead of concrete class

See also:
Spring: Why do we autowire the interface and not the implemented class?
Why always have single implementaion interfaces in service and dao layers?

[LinkSet] Avoiding NullPointerException in Java