Sunday, December 25, 2011

How to decide which technology hype is worth personal investments?

I think it's very important question. Because studding some new technology requires some time (and maybe money).

So, I've created for myself brief checklist which helps me to make this non-easy decision.
  1. How long it will take for me to master the major approaches of selected technology?
  2. Can I reuse the gained knowledge during my daily development work?
  3. How long it will take to train/coach my team mates to use this technology?
  4. How big is the market for the selected technology?
  5. How big is the local community for the selected technology?
  6. How easily can we hire new developers with appropriate knowledge in selected technology?
  7. Will it be profitable to have the knowledge in that technology?

I know  that some items are very boring  and mercantile, but it's life, real life. And we should align our priorities appropriately.

Thursday, November 03, 2011

How to run ANT script from .BAT/.CMD?

Imagine you need to call ANT script from BAT/CMD file.
Ant script:


And here is BAT file:

@echo off
echo BAT - Before Ant run
ant -f build.xml
echo BAT - After Ant run

Unfortunately, when you run this BAT you get the next output:
BAT - Before Ant run
Buildfile: D:\Projects\blog\build.xml

     [echo] Message from ANT

Total time: 0 seconds

So, where is the "BAT - After Ant run" echo message?

The problem is that Ant on Windows executed via ant.bat file and based on this we're calling one BAT file from another. We have to use CALL command to solve this issues, here is official note from CALL help:
Calls one batch program from another.
CALL [drive:][path]filename [batch-parameters]
batch-parameters   Specifies any command-line information required by the batch program. 
And, here is the update BAT file:

@echo off
echo BAT - Before Ant run
call ant -f build.xml
echo BAT - After Ant run

Friday, October 21, 2011

Java Reflection: Invoke Constructor Issue

Let's imagine we have the next classes:

package test.clazz;

public class First {
 private FirstArg arg;

 public FirstArg getArg() {
  return arg;

 public First (FirstArg arg) {
  this.arg = arg;
  System.out.println("First() - constructor");

public class FirstArg {
 public FirstArg() {

public class SecondArg  extends FirstArg{
 public SecondArg() {
And we can easily instantiate First class with FirstArg or SecondArg:
First f1Old = new First(new FirstArg());
First f2Old = new First(new SecondArg());
We'll get the next output:
First() - constructor
First() - constructor
class test.clazz.FirstArg
class test.clazz.SecondArg

Now, we have to instantiate First class with FirstArg or SecondArg, but via Java reflection:

public final class ConstructionUtil {
 public static Object instantiateClassOld(String className, Object iView) {
  try {
   Class iViewClass = iView.getClass();
   Class clazz = Class.forName(className);

   Constructor ctor = clazz.getDeclaredConstructor(iViewClass);
   return ctor.newInstance(iView);
  } catch (Exception e) {
   return null;
Check reflection based class instantiation:
Object cls = instantiateClassOld("test.clazz.First", new FirstArg());
First f1 = (First) cls;
Object cls2 = instantiateClassOld("test.clazz.First", new SecondArg());
First f2 = (First) cls2;
And we'll get Exception:
First() - constructor
java.lang.NoSuchMethodException: test.clazz.First.(test.clazz.SecondArg)
 at java.lang.Class.getConstructor0(Unknown Source)
 at java.lang.Class.getDeclaredConstructor(Unknown Source)
 at test.ConstructionUtil.instantiateClassOld(
 at test.ConstructionUtil.main(
Reflection mechanism can't find First(SecondArg arg) constructor.
We have to patch instantiateClassOld method like this:

public final class ConstructionUtil {
 public static Object instantiateClassNew(String className, Object iView) {
  try {
   Class iViewClass = iView.getClass();
   Class clazz = Class.forName(className);
   try {
    Constructor ctor = clazz.getDeclaredConstructor(iViewClass);
    return ctor.newInstance(iView);

   } catch (NoSuchMethodException e) {
    Constructor[] constructors = clazz.getDeclaredConstructors();
    for (Constructor c : constructors) {
     if (c.getParameterTypes().length > 1)
     Class type = c.getParameterTypes()[0];
     if (type.isAssignableFrom(iView.getClass())) {
      return c.newInstance(type.cast(iView));

   return null;

  } catch (Exception e) {
   return null;
And run it again:
Object cls = instantiateClassNew("test.clazz.First",new FirstArg());
First f1 = (First) cls;
Object cls2 = instantiateClassNew("test.clazz.First",new SecondArg());
First f2 = (First) cls2;
First() - constructor
First() - constructor
class test.clazz.FirstArg
class test.clazz.SecondArg
We should be careful when invoke methods via reflection with polymorphic arguments.

Monday, October 10, 2011

Overview: Optimistic vs. Pessimistic Locking

Data Concurrency is a real problem in multi-user environment. How can we manage the data consistence when several users try to modify the same record(s) at the same time?
This is a very interesting subject. Mostly, it's compromise. We can't easily pick one approach and forget about another.
This subject was quite nice discussed in Martin's Fowler book: "Patterns of Enterprise Application Architecture"
And, you can find here the short Martin's overview: Pessimistic Offline Lock and Optimistic Offline Lock.

JBoss community documentation has nice quotes about the subject:
The disadvantage of pessimistic locking is that a resource is locked from the time it is first accessed in a transaction until the transaction is finished, making it inaccessible to other transactions during that time. If most transactions simply look at the resource and never change it, an exclusive lock may be overkill as it may cause lock contention, and optimistic locking may be a better approach. With pessimistic locking, locks are applied in a fail-safe way. In the banking application example, an account is locked as soon as it is accessed in a transaction. Attempts to use the account in other transactions while it is locked will either result in the other process being delayed until the account lock is released, or that the process transaction will be rolled back. The lock exists until the transaction has either been committed or rolled back.
With optimistic locking, a resource is not actually locked when it is first is accessed by a transaction. Instead, the state of the resource at the time when it would have been locked with the pessimistic locking approach is saved. Other transactions are able to concurrently access to the resource and the possibility of conflicting changes is possible. At commit time, when the resource is about to be updated in persistent storage, the state of the resource is read from storage again and compared to the state that was saved when the resource was first accessed in the transaction. If the two states differ, a conflicting update was made, and the transaction will be rolled back.
The most popular example of optimistic locking is SVN commit operation.

Wednesday, August 31, 2011

Java Code Quality Tools - Overview

Recently, I had a chance to present the subject at the local IT community meetup. Here is the basic presentation:
and more meaningful mind map:
But, I think I need to cover this subject more deeply. This blog post should be something like start point for further investigation in this direction.

1. CodePro Analytix
It's a great tool (Eclipse plugin) for improving software quality. It has the next key features: Code Analysis, JUnit Test Generation, JUnit Test Editor, Similar Code Analysis, Metrics, Code Coverage and Dependency Analysis.
2. PMD
It scans Java source code and looks for potential problems: Possible bugs, Dead code, Suboptimal code, Overcomplicated expressions and Duplicate code.
3. FindBugs
It looks for bugs in Java programs. It can detect a variety of common coding mistakes, including thread synchronization problems, misuse of API methods, etc.
4.  Cobertura
It's a free Java tool that calculates the percentage of code accessed by tests. It can be used to identify which parts of your Java program are lacking test coverage. It is based on jcoverage.
5. Emma
It is a fast Java code coverage tool based on bytecode instrumentation. It differs from the existing tools by enabling coverage profiling on large scale enterprise software projects with simultaneous emphasis on fast individual development.
6.  Checkstyle
It is a development tool to help programmers write Java code that adheres to a coding standard.
7. JBoss Tattletale
JBoss Tattletale is a tool that can help you get an overview of the project you are working on or a product that you depend on. The tool will recursive scan a directory for JAR files and generate linked and formatted HTML reports.
8. UCDetector
UCDetector (Unecessary Code Detector) is a Open Source eclipse PlugIn Tool to find unecessary (dead) java code. It also tries to make code final, protected or private. UCDetector also finds cyclic dependencies between classes.
9. Sonar
Sonar is a continuous quality control tool for Java applications. Its basic purpose in life is to join your existing continuous integration tools to place all your development projects under quality control.
10. XRadar
The XRadar is an open extensible code report tool that produces HTML/SVG reports of the systems current state and the development over time. Uses DependencyFinder, JDepend, PMD, PMD-CPD, JavaNCSS, Cobertura, Checkstyle, XSource, JUnit, Java2HTML, ant and maven.
11. QALab
QALab consolidates data from Checkstyle, PMD, FindBugs and Simian and displays it in one consolidated view. QALab keeps a track of the changes over time, thereby allowing you to see trends over time. You can tell weather the number of violations has increased or decreased - on a per file basis, or for the entire project. It also plots charts of this data. QALab plugs in to maven or ant.
12. Clirr
Clirr is a tool that checks Java libraries for binary and source compatibility with older releases. Basically you give it two sets of jar files and Clirr dumps out a list of changes in the public api. The Clirr Ant task can be configured to break the build if it detects incompatible api changes. In a continuous integration process Clirr can automatically prevent accidental introduction of binary or source compatibility problems.
13. JDiff
JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared. This is very useful for describing exactly what has changed between two releases of a product. Only the API (Application Programming Interface) of each version is compared. It does not compare what the source code does when executed.
14. JLint
It checks your Java code and find bugs, inconsistencies and synchronization problems by doing data flow analysis and building the lock graph.
15. JDepend
JDepend traverses Java class file directories and generates design quality metrics for each Java package. JDepend allows you to automatically measure the quality of a design in terms of its extensibility, reusability, and maintainability to effectively manage and control package dependencies.
16. cloc
cloc counts blank lines, comment lines, and physical lines of source code in many programming languages.
17. Dependometer
Dependometer performs a static analysis of physical dependencies within a software system. Dependometer validates dependencies against the logical architecture structuring the system into classes, packages, subsystems, vertical slices and layers and detects cycles between these structural elements. Furthermore, it calculates a number of quality metrics on the different abstraction layers and reports any violations against the configured thresholds.
18. Hammurapi
Hammurapi is an open source code inspection tool. Its release comes with more than 100 inspectors which inspect different aspects of code: Compliance with EJB specification, threading issues, coding standards, and much more.
19. JavaNCSS
JavaNCSS is a simple command line utility which measures two standard source code metrics for the Java programming language. The metrics are collected globally, for each class and/or for each function.
20. DCD
DCD finds dead code in your Java applications.
21. Classycle
Classycle's Analyser analyses the static class and package dependencies in Java applications or libraries. It is especially helpful for finding cyclic dependencies between classes or packages. Classycle is similar to JDepend which does also a dependency analysis but only on the package level.
22. ckjm
The program ckjm calculates Chidamber and Kemerer object-oriented metrics by processing the bytecode of compiled Java files. The program calculates for each class the following six metrics proposed by Chidamber and Kemerer.
23. Jameleon
Jameleon is an automated testing framework that can be easily used by technical and non-technical users alike. One of the main concepts behind Jameleon is to create a group of keywords or tags that represent different screens of an application. All of the logic required to automate each particular screen can be defined in Java and mapped to these keywords. The keywords can then be organized with different data sets to form test scripts without requiring an in-depth knowledge of how the application works. The test scripts are then used to automate testing and to generate manual test case documentation.
24. DoctorJ
DoctorJ analyzes Java code, in the following functional areas: documentation verification, statistics generation and syntax analysis.
25. Macker
Macker is a build-time architectural rule checking utility for Java developers. It's meant to model the architectural ideals programmers always dream up for their projects, and then break -- it helps keep code clean and consistent. You can tailor a rules file to suit a specific project's structure, or write some general "good practice" rules for your code. Macker doesn't try to shove anybody else's rules down your throat; it's flexible, and writing a rules file is part of the development process for each unique project.
26. Squale
Squale is a qualimetry platform that allows to analyze multi-language software applications in order to give a sharp and comprehensive picture of their quality: High level factors for top-managers and Practical indicators for development teams.
27. SourceMonitor
The freeware program SourceMonitor lets you see inside your software source code to find out how much code you have and to identify the relative complexity of your modules. For example, you can use SourceMonitor to identify the code that is most likely to contain defects and thus warrants formal review.
28. Panopticon
The Panopticode project provides a set of open source tools for gathering, correlating, and displaying code metrics.
29. Eclipse Metrics plugin

Provide metrics calculation and dependency analyzer plugin for the Eclipse platform. Measure various metrics with average and standard deviation and detect cycles in package and type dependencies and graph them.
30. QJ-Pro
QJ-Pro is a comprehensive software inspection tool targeted towards the software developer. Developers can automatically inspect their Java source code and improve their Java programming skills as they write their programs. QJ-Pro provides descriptive Java patterns explaining error prone code constructs and providing solutions for it.
31. Byecycle
Byecycle is an auto-arranging dependency analysis plugin for Eclipse. Its goal is to make you feel sick when you see bad code and to make you feel happy when you see good code.
32. Coqua
Coqua measures 5 distinct Java code quality metrics, providing an overview and history for the management, and down-to-the-code, detailed views for the developer. Metrics can be defined per team. Ideal for mid- to large-sized and/or offshore projects.
33. Dependency Finder
Extracts dependencies and OO metrics from Java class files produced by most Java compilers.
34. Jalopy
Jalopy is an easily configurable source code formatter that can detect, and fix, a number of code convention flaws that might appear in Java code. Jalopy is more of a code fixer than a code checker. Jalopy plug-ins are present for most IDEs and, in most cases, they gel quite seamlessly with the IDE.
35. JarAnalyzer
JarAnalyzer is a dependency management tool for .jar files. JarAnalyzer will analyze all .jar in a given directory and identify the dependencies between each. Output formats include xml, with a stylesheet included to transform it to html, and GraphViz DOT, allowing you to produce a visual component diagram showing the relationships between .jar files. The xml output includes important design metrics such as Afferent and Efferent coupling, Abstractness, Instability, and Distance. There is also an Ant task available that allows you to include JarAnalyzer as part of your build script.
36. Condenser
Condenser is a tool for finding and removing duplicated Java code. Unlike tools that only locate duplicated code, the aim of Condenser is to also automatically remove duplicated code where it is safe to do so.
37. Relief
Relief provides a new look on Java projects. Relying on our ability to deal with real objects by examining their shape, size or relative place in space it gives a "physical" view on java packages, types and fields and their relationships, making them easier to handle. Lets discuss quickly how we interprete physical properties and how it can help us to grasp project characteristics.
38. JCSC
JCSC is a powerful tool to check source code against a highly definable coding standard and potential bad code. The standard covers naming conventions for class, interfaces, fields, parameter, ... . Also the structural layout of the type (class/interface) can be defined. Like where to place fields, either before or after the methods and in which order. The order can be defined through the visibility or by type (instance, class, constant). The same is applicable for methods. Each of those rules is highly customizable. Readability is enhanced by defining where to put white spaces in the code and when to use braces. The existence of correct JavaDoc can be enforced and various levels. Apart from that, it finds weaknesses in the the code -- potential bugs -- like empty catch/finally block, switch without default, throwing of type 'Exception', slow code.
39. Spoon
Spoon is a Java program processor that fully supports Java 5. It provides a complete and fine-grained Java metamodel where any program element (classes, methods, fields, statements, expressions...) can be accessed both for reading and modification. Spoon can be used on validation purpose, to ensure that your programs respect some programming conventions or guidelines, or for program transformation, by using a pure-Java template engine.
40. Lint4j
Lint4j ("Lint for Java") is a static Java source and byte code analyzer that detects locking and threading issues, performance and scalability problems, and checks complex contracts such as Java serialization by performing type, data flow, and lock graph analysis.
41. Crap4j 
Crap4j is a Java implementation of the CRAP (Change Risk Analysis and Predictions) software metric – a mildly offensive metric name to help protect you from truly offensive code.
42. PathFinder
Java PathFinder (JPF) is a system to verify executable Java bytecode programs. In its basic form, it is a Java Virtual Machine (JVM) that is used as an explicit state software model checker, systematically exploring all potential execution paths of a program to find violations of properties like deadlocks or unhandled exceptions. Unlike traditional debuggers, JPF reports the entire execution path that leads to a defect. JPF is especially well-suited to finding hard-to-test concurrency defects in multithreaded program
43. Soot
Soot can be used as a stand alone tool to optimize or inspect class files, as well as a framework to develop optimizations or transformations on Java bytecode.
44. ESC/Java2
The Extended Static Checker for Java version 2 (ESC/Java2) is a programming tool that attempts to find common run-time errors in JML-annotated Java programs by static analysis of the program code and its formal annotations. Users can control the amount and kinds of checking that ESC/Java2 performs by annotating their programs with specially formatted comments called pragmas.
CODERU is a java code quality tool to enforce good design in respect to package dependencies. The CODERU-rules rely on reserved package names and the allowed dependency rules between them expressed in a general way.

 * * *

This list includes open sourced and free tools. I intentionally have excluded commercial tools. I'm sure there are much more tools. In case your know some of them which isn't listed here please add comment to this post.

Monday, August 15, 2011

My reflection on "Programming Achievements: How to Level Up as a Developer"

Recently, I've read an amazing blog post "Programming Achievements: How to Level Up as a Developer". Also, it worth to read comments to this post, they are really interesting, subjective and personal. But, in any case you'll get something to think about. How to measure your own professional achievements, different ways for improvements and some start point for planning all these stuff.

The author suggests to use GitHub Gist as a natural way of improvements to keep them tracking. So, I've just forked his gist and performed several initial changes (see

Saturday, July 30, 2011

IT Booze Meetup #2: Scala, Clojure, Groovy

Today, I had a chance to attend local user group IT Booze. It was the second meetup and it was very interesting, because of topics which were under discussion: Scala, Clojure And Groovy. I love such events especially in my town. :-)

I'd like to share my reflections regarding these cool languages.

As you know these languages are very popular on JVM (of cause not so popular as Java :-). And I'm sure every passionate Java/JVM developer has been thinking "what's the Next Big Language". It's really hard to choose the next one.

So, here is a short "brain snapshot":
  1. Scala and Clojure are great languages with huge amount of interesting features, but to master them we need to use Scala (or Clojure) on daily basis.
  2. Scala appeared as complex language. I think it requires a steeper learning curve then Clojure or Groovy. It means we must invest much, much more.
  3. Clojure has lisp syntax, but innovative concurrency concept is worth to look into. I say lisp, because it might be a stopper for someone to evaluate it as a next big language.
  4. Clojure and functional programming require to "patch" our way of thinking. And it can be difficult.
  5. Groovy is agile language. We (Java developers) can start using it right away. I think we should invest more in Groovy just to boost our productivity in: scripting, testing, automation routine work, etc. It doesn't require big investments and we can learn as we go.
So, here is outcome from this meetup:
  • start using Groovy
  • look into Clojure concepts
  • postpone Scala for now
Could you please share your thoughts regarding this?

Wednesday, July 20, 2011

How to disable System.out?

I have a legacy code base with tons of System.out.println(). Actually, I don't need this in production, but during development it's cool enough to have. So, I've decided to disable System.out:
package org.halyph;


public class DisableMain {
	public static void main(String[] args) {
		PrintStream printStreamOriginal = System.out;

		boolean DEBUG = true;
		if (!DEBUG) {
			System.setOut(new PrintStream(new OutputStream() {
				public void close() {}
				public void flush() {}
				public void write(byte[] b) {}
				public void write(byte[] b, int off, int len) {}
				public void write(int b) {

		long a = System.currentTimeMillis();
		for (int i = 0; i < 1000000; i++) {

		long b = System.currentTimeMillis() - a;


So, plain looped println required ~10 seconds on my laptop, and only ~1 second with null output stream.

Tuesday, July 19, 2011

Ubuntu Server 10.04.2 VM Basic Configuration

 + +
Required tools:
  • VMware Worstation
  • Ubuntu Server 10.04.2
  • Kitty (Putty ssh client fork)
I suppose that You know how to setup plain VM via VMware.
And here is my basic Ubuntu VM configuration:
  1. Ubuntu Server 10.04.2 doesn't include SSH server by default. That's why you have to install it:
  2. sudo apt-get install ssh
  3. Check your Ubuntu VM IP:
  4. $ ifconfig
    eth0      Link encap:Ethernet  HWaddr 00:0c:29:04:55:d6
              inet addr:  Bcast:  Mask:
              inet6 addr: fe80::20c:29ff:fe04:55d6/64 Scope:Link
              UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
              RX packets:50 errors:0 dropped:0 overruns:0 frame:0
              TX packets:52 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:1000
              RX bytes:6303 (6.3 KB)  TX bytes:7366 (7.3 KB)
              Interrupt:19 Base address:0x2000
  5. Configure Kitty connection host name: 
  6. Create two scripts for:
    • startup VM in background (start_vm.bat)
    • set MYVM="F:\VMs\ubuntu-10.04.2-server\Ubuntu Server 10.04.2.vmx"
      set VMRUN="E:\Program Files\VMware\VMware Workstation\vmrun"
      %VMRUN% -T ws start %MYVM% nogui
    • shutdown VM (stop_vm.bat)
    • set MYVM="F:\VMs\ubuntu-10.04.2-server\Ubuntu Server 10.04.2.vmx"
      set VMRUN="E:\Program Files\VMware\VMware Workstation\vmrun"
      %VMRUN% stop %MYVM% soft
  7. Configure Kitty for auto-login:
  8. VM startup and Kitty run can be combined into one script

Monday, July 11, 2011

Clojure Books


Books which aren't fully dedicated to Clojure

Coming Soon (in progress)

Tuesday, June 28, 2011

How to Add Jars at Runtime?

Suppose you have the next project structure:

Here is the source code:


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.halyph.three.MyClassThree;
import org.halyph.two.MyClassTwo;

public class DynamicClassLoader {
 public static void main(String[] args) throws Exception {

  MyClassTwo myClassTwo = new MyClassTwo();
  MyClassThree myClassThree = new MyClassThree();


package org.halyph.two;

public class MyClassTwo {
 public void printMessage() {

package org.halyph.three;

public class MyClassThree {
 public void printMessage() {

And each of these classes are packed in separate jar:
  • - dynone.jar
  • org.halyph.two.MyClassTwo - dyntwo.jar
  • org.halyph.three.MyClassThree - dynthree.jar
To run this application you should put all these jars on classpath,
E.g. the application output
# java -cp dynone.jar;dyntwo.jar;dynthree.jar

But there are some cases when dyntwo.jar and dynthree.jar jars location can be known during runtime only. And we have to run our application in the next way:
# java -cp dynone.jar

Of cause, you'll get the next (or similar) error:
# java -cp dynone.jar
Exception in thread "main" java.lang.NoClassDefFoundError: org/halyph/two/MyClassTwo
Caused by: java.lang.ClassNotFoundException: org.halyph.two.MyClassTwo
        at$ Source)
        at Method)
        at Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more

So, how can we solve this problem?
Here is the patched

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.halyph.three.MyClassThree;
import org.halyph.two.MyClassTwo;

public class DynamicClassLoader {

 public static void main(String[] args) throws Exception {

  String[] jars = new String[] { "dyntwo.jar",  "dynthree.jar"};
  addJarsToClasspath(getRootFolder(), jars);
  MyClassTwo myClassTwo = new MyClassTwo();
  MyClassThree myClassThree = new MyClassThree();


 public static void addJarsToClasspath(String rootFolder, String[] jarNames)
   throws SecurityException, NoSuchMethodException,
   MalformedURLException, IllegalArgumentException,
   IllegalAccessException, InvocationTargetException {

  Method addURL = URLClassLoader.class.getDeclaredMethod("addURL",
    new Class[] { URL.class });
  addURL.setAccessible(true); // you're telling the JVM to override the
         // default visibility

  File[] files = new File[jarNames.length];
  int i = 0;
  for (String jarName : jarNames) {
   files[i++] = new File(rootFolder + jarName);

  // returning the jars to add
  ClassLoader cl = ClassLoader.getSystemClassLoader();
  for (i = 0; i < files.length; i++) {
   URL url = files[i].toURL();
   addURL.invoke(cl, new Object[] { url });

 public static String getRootFolder() {
  String result = null;
  try {
   String qualifiedClassName = DynamicClassLoader.class.getName();

   Class qc = Class.forName(qualifiedClassName);
   CodeSource source = qc.getProtectionDomain().getCodeSource();
   if (source != null) {
    URL location = source.getLocation();
    File file = new File(location.toURI());

    result = file.getParent() + "/";
   } else {
    System.out.println(qualifiedClassName + " : "
      + "unknown source");
  } catch (Exception e) {
   System.err.println("Unable to locate class on command line.");
  return result;


Here is the output of patched application:

# java -cp dynone.jar

So, two additional methods were added to support this "magic":
  • public static String getRootFolder()- this method simply identifies the folder where dynone.jar (on behalf of class) is located. Because for this demo we put all application-related jars in one folder
  • public static void addJarsToClasspath(String rootFolder, String[] jarNames) - and here the "magic" happen. Based on this post on forums:
There is a well-known hack for dynamically extending the class path.
It generally works, and we use it in production releases of our software. It uses reflection, plus the knowledge that the default ClassLoader *is* a URLClassLoader.
As I said, this is a hack, undocumented, and subject to change at any
time. Indeed, there's no guarantee that extant JREs use a URLClassLoader as a default class loader. Moreover, it only works if your program doesn't have a security manager (it probably doesn't), or your code is trusted.
We've never seen problems with it, although our software is used on a plethora of different boxes and OSs.
It works for me and I hope it will be useful for you as well.
Happy hacking!

Monday, June 20, 2011

@Override Java Annotation Issue

Let's create one simple interface and class which implements this interface:

public interface IOverride {
    void doSomething();
public class Overridden implements IOverride {
    public void doSomething() {

And compile this stuff on JDK v.1.5:
# javac -d classes src\*.java
src\ method does not override a method from its superclass
1 error

Let's try to do the same on JDK v.1.6 - And, You've got no compilation error.
Between Java 5 and Java 6 changes to the specification of @Override have been made. In Java 6 it is possible to add the @Override annotation to methods that implement methods of an interface which is not allowed in Java 5. (

Also, I've found very interesting discussion on Stackoverflow:

What are the best practices for using Java's @Override annotation and why?
It seems like it would be overkill to mark every single overridden method with the @Override annotation. Are there certain programming situations that call for using the @Override and others that should never use the @Override?

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

Sunday, June 12, 2011

ITEvent 2011, Local Conference – Report

Yesterday (June 11, 2011) I attended the local (Ivano-Frankivsk, Ukraine) IT related conference “itEvent 2011”. I must say I am impressed. There were more than a hundred participants. And it’s amazing. We live in a very small city and this local event/conference waked up so many developers to attend this event.

The conference had three parallel flows/stages. And it’s a good sign. The organizers give us a chance to choose the most preferable topic(s) to attend. Additional good point is that each presentation was shot on video. So, I could see missed interesting topics.

Here is the talks (which I saw and hear) overview:

1. “Two sides of IT interview” by Nataliya Mukhitdunova. To tell the truth I wasn’t expected that such boring subject can be presented in such interesting way. Just wow. The speaker was concentrated on two interview stakeholders: HR and Developer. She clearly defined their goals and expectations, tips for HRs (as interviewer) and for Developers (as interviewee). And this speech was so easy made and “light” that I felt “I’m in right place in right time”. The presenter doesn’t use any slides or other supportive material, she was just well prepared with good background in this area.

2. “Kanban and the creation of the high effective teams” by Sergiy Fitsak and Anatoliy Okhotnikov. I’ve expected to hear some advices, case studies (especially BAD experience) and of cause the process implementation issues. And I’ve got all these. Thanks to the presenters. The one “minus” was that this talk wasn’t well coordinated between two presenters and they overused the presentation’s time limit. They hadn't predicted that they got so many questions and discussions. I can say that this talk really revived the audience. And it was cool.

3. “Facebook as a mobile application platform” by Yevgen Vershynin. The presenter showed us from the very begging what the Facebook platform is and how to use it. This area was absolutely new for me. Additionally, he was well prepared and his speech was very dynamic. And, even more, he showed some passion during the speech. That’s why it was so interest. I must admit that Yevgen (the presenter) showed very high presentation, communication skills, and good domain knowledge. Very impressive.

4. “How to meet customer expectations” by Ruslan Seredyuk. This topic was absolutely new for me. I mean I’ve never thought about “customer expectations” and “what is the successful project”. I like to discover something new. The presenter showed real knowledge which is based on work experience. And it’s very important. Every single case in his presentation had small life sample, which was very useful to demonstrate the all dark places in this mess area (i.e. customer expectations). Again, the presenter was well prepared with real case studies. The one "minus" is that the target audience wasn’t mentioned. And this topic wasn’t dedicated for the junior developers, IMHO.

Now, let’s talk about conference organizations:


1. There were a lot of coffee, cakes and water.

2. The registration was straightforward.

3. The atmosphere was VERY friendly.

4. The presentations' quality was good.

5. And the most important, the itEvent organizer overdid their own expectation, they gathered huge amount of IT related people in one place and gave them a chance to talk to each other and share personal knowledge, vision and contacts. As for me, the goal was perfectly achieved.


1. I think that Conference, Camp or similar event should have some motto.

2. It’s good to have agenda for every presentation/speech in English as well

3. It’s good to have target audience for every presentation/speech. It’s even more important in multi-target conference (here we can see management, technical and usability directions, etc.)

4. The conference’s web resource is in Ukrainian only. It’s good to have English as well. Also, the web resource structure could be improved.

So, the overall impression is good. This local conference exceeded my expectations. I hope we’ll have the similar event next year.

Monday, June 06, 2011

Top 15 Java Web Resources

Here is the top 15 Java-related resources I'd like to share with you.

Blogs, News aggregator
1. is a very big aggregator for news, articles, video interviews, tutorials, reviews, and announcements. Also, you can use some particular, dedicated "zones": - Javalobby
IDEs and Tools:

This resource contains huge amount of information and you could easily lost there (50-80 new items per day). So, I suggest to use Javalobby as a start point.
2.  News, videos, interviews, conference reports, etc.
3. Articles, blogs, wiki, news.

Forums and Q&A
4. is one of the biggest Java forum
5. it's one of the biggest Q&A site which includes such features as Q&A, forum, wiki, blog, collaboration and community based content moderation.

6. is a directory of videos, interviews and tutorials focused on software development activities with the Java™ programming language.
7. SoftDevTube is a repository of videos, interviews and tutorials focused on all software development activities.

8. Common Java Cookbook
This collection provides expert tips for using Java-based utilities from projects such as Apache Commons, Apache Lucene, and Apache Velocity. You don't have to be an expert, the book's solution-based format contains code examples for a wide variety of web, XML, network, testing, and application projects. If you want to learn how to combine common open-source Java utilities to create powerful Java applications and tools, the Common Java Cookbook is for you.
9. Canadian Mind Products Java & Internet Glossary
10. Collected Java Practices. It offers concise presentations of Java practices, tasks, and designs, illustrated with syntax-highlighted code examples.
11. Java Notes.
These Java programming notes are written to fill in missing or weak topics in textbooks the Author has taught from.
12. Javamex is the author attempt to gather together information on some of the more intricate aspects of Java programming, building on the experience with the language.
13. This site holds all the examples from The Java Developers Almanac and more. Copy and paste these examples directly into your applications. Over a thousand useful examples can be found there.

14. references the tools you need for Java development.
15. On-line community-based exam system

Wednesday, June 01, 2011

How to choose between Scala and Clojure?


I think it's very popular question nowadays. The Java-haters produce so many buzz around this. So, want you or not, but You passively have been trying to choose the

I've found several interesting posts which cover pretty much about this subject:
by Stephan Schmidt
by Lau B. Jensen

Hint: Try to read comments to these posts, there are very interesting discussions. Some of them are even more useful than the actual post(s)/article(s).

These articles don't give you any advices or strong opinions which language is the best. But, it's a good start point, for sure.

Tuesday, May 24, 2011

JEEConf - Kiev, 2011 - Report

I had a chance to attend the first and totally dedicated to Java conference in Kiev (May 21, 2011).
It was a great. The atmosphere was amazing. The organization was good, really good. The most noticeable thing was that almost every presentation was based on real problem, no metaphysical stuff :-)
There were three stages, that's why I couldn't attend every talk and that's a pity.

Here is a short overview of all attended talks:

1. "What Riding the Camel can do to make integration easier for you" by Claus Ibsen.
I had an idea what the Camel is, but this presentation gave me the "big picture". Actually, the speaker has been well prepared and known the presentation technique very well. He showed all major aspects of Camel framework and explain its purpose.

He's shown the several Camel's DSLs: XML-based, Java and Scala. That short code snippets were really cool and clean. So, I've added into my todo list "the Camel DSL digging" ;-)

2. "The Scala and GridGain usage for the distributed systems with high efficiency" by Renat Ahmerov.
This talk and master-class inspired me to start Scala learning. I've never seen the cloud computing in action. But during that master-class was created real application for distributed computing. And the code base was so tiny and clean, so my heart falling in love to this language. The last time I had had the similar feeling when I've seen the Rails in action.

3. The problem diagnosing and GC tuning in HotSpot Java VM by Vladimir Ivanov.
This talk was like a JVM magic :-). The speaker discovered the darkest GC places I've never known about. He's opened my eyes. I even couldn't expect that GC tuning is so interesting.

4. To be in ten times faster kudos Groovy by Evgeny Kompaniec
This guy has shown the real case study:
- Why he choose the Groovy as Java substitution.
- Java code snippets vs Groovy (functionally equal) code snippets. IMHO, the most interesting and inspiration part of talk.
- Groovy knowledge sharing via pros & cons.

5. Unitils for Java testing by Mikalai Alimenkou
To be honest I've never heard about this tools. This presentation was full of practical samples and advices like a cookbook. Great talk, the presenter had a good mood and used the right jokes in the right places, he was very impressive. I wish every speaker had such good presentation technique.

6. How Graph Databases can make you a super star by Andrés Taylor
This talk was dedicated to the "beauty" of Neo4j graph DB. It was just a start point for this DB.

7. Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript by Joonas Lehtinen
I've been following this framework about a year. And I must admit that it was really impressed to see CEO of company behind Vaadin.
The talk was short and pragmatic. The major areas of Vaadin were highlighted. Then, the presenter has shown the Vaadin in action and it was cool. The community and the whole framework evolved in one year. As for me it was great to see the real person who developed so interesting stuff.

It was my 6th IT conference. I must admit it was the best, no doubts. I hope to attend the Java conference next year again.

Tuesday, May 03, 2011

XP, Scrum and Kanban: How to make the first step?

There are so many books, articles and blog posts about the topic. And it's not the easy way to chose the right one, laconic and simple, with pragmatic advices and some real case studies.
The biggest issues for almost every "agile" related book is their size, about 300 pages (in general). But what about brief, all-sufficient book?
I can suggest two, short enough, books: Scrum and XP from the Trenches and Kanban and Scrum - making the most of both. The names of the books are self-explained.

You've got the "big picture" after the reading of these books.

Sunday, April 17, 2011

Axis2 and Tomcat work together with SecurityManager

  1. First of all download the latest Tomcat and axis2.war.
  2. Read Tomcat Security Manager HOW-TO
  3. Setup Tomcat and deploy axis2.war.
  4. Edit <TOMCAT install dir>/conf/catalina.policy file and add the next:
  5. grant {
        permission "${catalina.base}/webapps/axis2/WEB-INF/-", "read";
        permission java.lang.RuntimePermission "getClassLoader";
    grant codeBase "file:${catalina.home}/webapps/axis2/-" {
        permission java.lang.RuntimePermission "createClassLoader";  
        permission java.lang.RuntimePermission "setContextClassLoader";  
        permission java.lang.RuntimePermission "checkPropertiesAccess";  
        permission java.lang.RuntimePermission "getClassLoader";  
        permission java.lang.RuntimePermission "getProtectionDomain";  
        permission java.lang.RuntimePermission "";  
        permission java.lang.RuntimePermission "";
        permission java.lang.RuntimePermission "shutdownHooks";  
        permission java.lang.RuntimePermission "accessDeclaredMembers";  
        permission java.util.PropertyPermission "*", "read,write";  
        permission "localhost:8080", "resolve, connect";  
        permission "${catalina.base}/webapps/axis2/WEB-INF/modules/*", "read,write";  
        permission "${catalina.base}/webapps/axis2/WEB-INF/services/*", "read,write";  
        permission "${catalina.home}/common/classes", "read";  
        permission "${catalina.home}/shared/classes", "read";  
        permission "${catalina.base}/common/classes", "read";  
        permission "${catalina.base}/shared/classes", "read";  
        permission "${catalina.home}/common/i18n/*", "read";  
        permission "${catalina.home}/common/lib/*", "read";  
        permission "${catalina.home}/lib", "read";  
        permission "${catalina.home}/lib/*", "read";  
        permission "${catalina.home}/bin/*", "read";  
        permission "${catalina.base}/webapps/axis2/WEB-INF/scriptServices/*", "read";  
        permission "${java.home}/lib/ext/*", "read";  
        permission "${catalina.base}/webapps/axis2/WEB-INF/web.xml", "read";  
        permission "${}${/}-", "read, write, delete"; 
        permission "${}", "read, write, delete";
  6. Start Tomcat with SecurityManager: 
  7. $CATALINA_HOME/bin/ start -security    (Unix)
    %CATALINA_HOME%\bin\catalina start -security      (Windows)
  8. Verify axis2 "HappyAxis" page as follows: http://localhost:8080/axis2/axis2-web/HappyAxis.jsp
NOTE: other application servers can and have different security policy file options/permissions.

Tuesday, February 15, 2011

Lisp Balkanization?

I've heard this words' pair too often and I never knew what does it mean?

Until I read these two posts: Ultra-Balkanization Makes Lisp Autistic and Reddit and Lisp psychosis.

In general every Lisp developer tends to write "new" super-puper Lisp, invent the wheel, write own "cool" emacs extension and tell to the world that he is a HACKER. I love this.

Nowadays, Clojure is the real answer for Lisp guys. It can consolidate the Lisp language flexibility and JVM power. I think it's a good choice.

Friday, February 11, 2011

How to choose the next programming language to learn?

I believe that this question has been appearing in the brains very often.
Note: I'm writing from Java developer point of view.

How to solve this dilemma? I said "dilemma" because it's investment in the new knowledge. And every new knowledge should bring some benefits. The wrong investment is equal to waste of your time.

As a Java developer I think I should invest outside the JVM. It's even more important in nowadays. Oracle is more aggressive then Sun was. So, investment in non-JVM "platform"/language can protect the own future.

I don't want to write about some definite language. It's not important right now. The most important thing is to learn something new which is totally separated from JVM.

Someone can say: "Try Groovy, Scala or Clojure". Good point. But,  it's JVM (even if they are "beautiful" and interesting choices). One exception: you can have a possibility to use these languages on the job project. In that case it's ok. Just pick the right one and start the party. In other case avoid them.

There is NO right answer. Just define your own philosophy (language to learn) and keep it alive.

Wednesday, January 26, 2011

Review: Language Grubbing

Yet another interesting reading from Steve Yegge: Language Grubbing.

He reviewed several programming languages (C, C++, Java, Perl, Python, Ruby, Smalltalk, Lisp family, ML family, Haskell, Erlang). He mentioned pros and cons for each of them, criticized some of them (Perl, Common Lisp). Also told that Lua, Tcl, Prolog, Pascal wouldn't be in his learning "backlog".

I looked at a lot of other languages: JavaScript, Lua, Tcl, Prolog, Eiffel, Pascal, and a bunch of others. None of them really stood out as being "special" like the others I've talked about.

For instance, you can do Prolog-like logic/constraint programming in Lisp or OCaml pretty easily, and they're both broader/better languages than Prolog. Pascal gives you nothing that C doesn't already do better. ... Lua is a cleaned-up Tcl, but neither one of them is as interesting (to me, anyway) as Python for doing embedded languages, unless you really need to strip it down to practically nothing, in which case Lua is useful.

IMHO, reasonable comments.
He mentioned about language groups:
  • Java, C# and C++ (I would add Objective-C and Smalltalk)
  • Haskell, SML, OCaml (I would add F#, Scala)
  • Common Lisp, Emacs Lisp, Scheme (I would add Clojure)
  • Perl, Python, Ruby (I would add PHP)
  • Erlang (I would add Prolog, Oz)
  • Lua, Tcl, JavaScript (I would add Io, Ioke, R, REBOL)
  • C, Pascal

I wrote about this but I'll repeat again. I time wasting if you learn several languages from the same group. E.g. Python and Ruby, or Java and C#.
So, just a pick the "major" language from each group and learn it. E.g.: Java, Haskell, Clojure, Ruby, JavaScript and C.

C language is like Latin for the plain developer. JavaScript is must be know by anyone involved in web-related development.

For myself I formed the next language priority list:
  1. Java
  2. JavaScript
  3. Ruby or Python (I haven't decided yet)
  4. Clojure, Scheme or Common Lisp (I haven't decided yet)
  5. C

Tuesday, January 25, 2011

Review: Beating the Averages

This Paul's Graham essay (Beating the Averages) is very popular among Lisp community. Someone told that it was the new Lisp push, the new Lisp wave. I read this essay and companion technical article "Lisp in Web-Based Applications" in one short. It's really inspired reading.

Paul Graham described the "hidden" power of Lisp. Unfortunately, the Common Lisp community is fragmented so much. Too many different implementations. It hurts Lisp as a sub-culture. I hope this situation will be resolved by Clojure vibrant community

Definitely, if you want to open your Lisp mind you should read this essay. Nothing special from technical point of view, but really cool as Lisp catalyst. Read it, feel the power, feel the spirit.

The general idea (IMHO): startup is the right place to try something new and revolutionary to "kill" your competitors.

Saturday, January 22, 2011

Lisp, Ruby, Acceptable and not Acceptable

There is one really (in)famous essay Why Ruby is an acceptable LISP by Eric Kidd. The most interesting of all this stuff are comments and other responsive blog posts (e.g. Lisp is Not an Acceptable Lisp by Steve Yegge)
I can say this is something like "vs" essay which is very popular nowadays.

Here is the list of some quotes and key ideas:

  • Lisp macros are far more powerful than the trivial use cases you’ve listed. I could give a lot of examples here, but just ask yourself: why is most of the programming community so fond with “Design Patterns”, while the Lisp community generally isn’t? Well, that’s because patterns are nothing but high-level specifications for code being rewritten again and again and again. The Lisp approach is to create some macros and auxiliary functions that actually implement the pattern, thus extending the language capabilities and avoiding continuous reinvention of the wheel.
  • This article sounds like it was written for folks who really want to use Lisp, but have chosen Ruby because all the cool kids are using it and want to reasonably justify an emotional decision.
  • If you want to learn a language that can change with the times and incorporate whatever latest fad the programming cool kids have to offer, Lisp is the choice. Lisp is the red pill.
  • A final example: look at the 2 open source Computer Algebra Systems written in Common Lisp available as Open Source: 1) Axiom – originally from IBM Thomas Watson Research Center; 2) Maxima – originally Department of Energy (US). This is software written in the 70s. You can’t write software that lasts so long with a language that is a moving target. This is the kind of survival and complex domain which shows the power of Lisp.
  • The real reason that brought me to Lisp (and never will get me away from it) is simply this:
    You can build it out of 7 (s-e-v-e-n) primitive operators!
    And, as a consequence, no other language can be expressed in itself as short as Lisp. (As you probably know, quite any language can be expressed in itself.)
    So let me repeat: really no other language can be expressed in itself that short, and (as a natural consequence) can be built out of less primitive operators.
  • Ruby has a syntax, and Ruby needs a full parser to get from that syntax to an AST. Because Lisp code is naturally an AST, things are very different
And small summary of the Steve's blog post Lisp is Not an Acceptable Lisp:
There is no acceptable Lisp. This is a problem. It's not a little teeny one, either. The Lisp communities (yeah, there are a bunch) are going to have to realize that if Lisp is ever going to be massively successful, it needs an overhaul. Or maybe a revolution. Contrary to what some might tell you, it doesn't need a committee, and it doesn't need a bunch of money. Linux proved exactly the opposite. Lisp needs a benevolent dictator. Lisp needs to ditch the name "Lisp", since it scares people. And Lisp needs to learn from the lessons of the 45 years of languages that have followed it.
Based on this comments and I'm attaching this funny picture:
The programmer's superiority complex... in hierarchy format.

Friday, January 14, 2011

Review: You Should Write Blogs?

I've just finished reading the Steve Yegge's post "You Should Write Blogs".
As for me it's very impressive and honest writing about blogging I've ever read. I like this style of writing.
The general idea is to explain why You should write blogs.
So don't worry about whether people will read it. Just write it!
No matter where you are in your education, some people will be interested in hearing your struggles. This is an important thing to keep in mind when you're blogging. Each person in your audience is on a different clock, and all of them are ahead of you in some ways and behind you in others. The point of blogging is that we all agree to share where we're at, and not poke fun at people who seem to be behind us, because they may know other things that we won't truly understand for years, if ever.
He described some reasons why people don't like to write blogs and commented it:
  1. I'm too busy.
  2. I'm afraid to put my true thoughts on public record.
  3. Nobody will read my blog.
  4. Blogging is narcissistic.
I must say that Steve inspired me to write more. Just for fun.

Wednesday, January 12, 2011

Should I learn Lisp?

I had been asking this question myself every time I had found something (blog post, article, book title, etc.) interesting related to Lisp. But those “ugly” brackets put me away again and again :-). So, what was happen and why I changed my vision?

I think I’ve got three triggers to change my mind: a) friends of mine works with Gensym/G2 platform and they are really inspired by Lisp power; b) I saw several Rich Hickey’s talks about Clojure and the last one c) Paul Graham essays.

Then, I started googling to find other opinions about Lisp (when I say “Lisp” I mean Common Lisp, Scheme, Clojure and other Lisp dialects).

Monday, January 10, 2011

Review: How To Become A Hacker?

It's worth reading. I think that it's like hacker "mantra" ;-) I don't want to retell all that stuff. Just want to sum up.

1. Programming language learning.
We should learn different programming languages from paradigm point of view: "classical" OOP languages (C++, C#, Java), procedural languages (C), functional languages (Lisp family languages: Common Lisp, Scheme, Clojure), dynamic and scripting languages (Perl, Python, Ruby) and web-related (JavaScript).
"Besides being the most important ... languages, they represent very different approaches to programming, and each will educate you in valuable ways."
It means that you should  learn languages from different paradigms to get some conceptual  knowledge.
E.g. You shouldn't learn Java and  C#, or Python and Ruby. I think it's just waste of your time.
"To be a real hacker, you need to get to the point where you can learn a new language in days by relating what's in the manual to what you already know.This means you should learn several very different languages."
2. Learn Unix/Linux.
I think the best way to learn is to start playing with Ubuntu.

3. Learn English and native language. 
You should be able the speak and write fluently in both.

4. Persistent learning
It's the key point to success in any profession.

"To follow the path:
look to the master,
follow the master,
walk with the master,
see through the master,
become the master."