Tuesday, 31 July 2012

ArgumentCaptor in Mockito

Use it to capture argument values for further assertions.
It should be used during verifications. It is very useful when assert on argument values to complete verification.
It can also be fined through annotation: @Captor
More info here: http://docs.mockito.googlecode.com/hg/org/mockito/ArgumentCaptor.html
and : http://docs.mockito.googlecode.com/hg/org/mockito/Captor.html

Mockito Matchers

When using Mockito you can use MockitoMatchers. You can use predefined ones or create own implementation.
assertThat(object, CoreMatchers.equalTo(0));
More examples as well as own implementations here: http://docs.mockito.googlecode.com/hg/org/mockito/Matchers.html

Cannot map request parameters as a Map parameter in Spring MVC

In Spring MVC you cannot map request parameters as a Map parameter in controller method using annotation @RequestParam
It is due to implementation of HandlerMethodInvoker.java, where Spring puts all parameters of the request to the parameter of Map type. Moreover the result map type is MultiValueMap or Linked HashMap.

CachingConnectionFactory for Spring JMS

CachingConnectionFactory is used as the proxy wrapping JMS Connection in the Spring JMS. It prevents from agressively closing and reopening JMS sessions and connections.
It is used for adding caching during usage Spring JMS templates.

<bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
  <property name="targetConnectionFactory" ref="connectionFactory"/>

Creating directories hierarchical on Linux

mkdir -p directory
to create directory with no error if existing and make parent directories as needed.

Monday, 30 July 2012

@InjectMocks - Mockito

It is an annotation used in Mockito on the variable definition telling Mockito to try to inject by type already defined mocks or spies on the annotated object
@InjectMocks private MyService service = new MyService();

More info here: http://docs.mockito.googlecode.com/hg/org/mockito/InjectMocks.html

Actions throwing exceptions in Spring MVC

When an action in the Spring MVC throws exception, you can handle it with specifying http response code, by annotation on the exception class definition: @ResponseStatus(httpStatus).
When you cannot annotate class, f.e. it is not your exception definition, you can add in the controller a method which is annotated with @ExceptionHandler(yourExceptionClass) and @ResponseStatus(httpStatus)

Saturday, 28 July 2012

Eclipse TCP/IP Monitor

It is a great tool for debugging Web Services. You can show it using CTRL+3 in the Eclipse. Use properties option for setting port that will forward request to an other port (the one used for the Web Service). You can use type of the output: XML, Byte, Web Browser, Image.

XJC - JaxB compiler

XJC is the compiler for JAXB Web Services. It generates classes from xsd file describing types in the Web Services communication.
Here is detailed information: http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html

Trang - opensource schema converter

You can use it to generate xsd files from example content.
More information here: http://www.thaiopensource.com/relaxng/trang-manual.html

Exposing Web Service WSDL in Spring WS

You can expose WSDL of the Service in the Spring WS using configuration:

<ws:dynamic-wsdl id="definitionName" portTypeName="Type" locationUri="http://host:8080/serviceName/">
<ws:xsd location="/WEB-INF/transfer.xsd"/>

It generates WSDL from XSD file. The wsdl can now be accessed through: http://host:8080/serviceName/definitionName.wsdl

Project Jigsaw deferred until Java 9

Project Jigsaw, java modularity is going to be deferred until Java 9. Java 8 release time is September 2013. There is still to much to do to make the deadline.
The goal is: A standard module system for the Java Platform will ease the construction, maintenance, and distribution of large applications, at last allowing developers to escape the “JAR hell” of the brittle and error-prone class-path mechanism.

Chief Java architect on his blog describes the situation: http://mreinhold.org/blog/late-for-the-train.

Project Jigsaw home page: http://openjdk.java.net/projects/jigsaw/

Sunday, 15 July 2012


CountDownLatch - A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

Javadoc here: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html

CodePro Analytix

CodePro Analytix - is the premier Java software testing tool for Eclipse developers who are concerned about improving software quality and reducing developments costs and schedules. The Java software audit features of the tool make it an indispensable assistant to the developer in reducing errors as the code is being developed and keeping coding practices in line with organizational guidelines.

It is a google product which is free for commercial and non-commercial usage.

Try it whether it helps in your development. F.e. Dead Code function is not working good with Spring applications and annotations. Finding similar code for me is the best!
More info on : https://developers.google.com/java-dev-tools/codepro/doc/

Fidbugs for eclipse

Findbugs is a program which uses static analysis to look for bugs in Java code. It is free software, distributed under the terms of the Lesser GNU Public License. The name FindBugs™ and the FindBugs logo are trademarked by The University of Maryland. FindBugs has been downloaded more than a million times.
You can read hera how to install Fingbugs plugin for Eclipse: http://findbugs.sourceforge.net/manual/eclipse.html


Simple utility methods for file and stream copying. All copy methods use a block size of 4096 bytes, and close all affected streams when done.
More on: http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/util/FileCopyUtils.html

Wiser - for testing mails by JUnit

Wiser is a simple SMTP server that you can use for unit testing applications that send mail. It accepts all messages and stores them in an internal ArrayList. Your unit test code can then examine the messages (or lack thereof) and verify their validity.
More on: http://code.google.com/p/subethasmtp/wiki/Wiser

Saturday, 14 July 2012


ResourceDatabasePopulator - useful class for populating a database from SQL scripts defined in external files.
Javadoc : http://static.springsource.org/spring/docs/3.0.0.M3/javadoc-api/org/springframework/jdbc/datasource/embedded/ResourceDatabasePopulator.html

Friday, 13 July 2012

XmlUnit - JUnit testing for XML

XMLUnit for Java provides two JUnit extension classes, XMLAssert and XMLTestCase, and a set of supporting classes (e.g. Diff, DetailedDiff,Transform,SimpleXpathEngine,Validator,NodeTest) that allow assertions to be made about:
  • The differences between two pieces of XML
  • The outcome of transforming a piece of XML using XSLT
  • The evaluation of an XPath expression on a piece of XML
  • The validity of a piece of XML
  • Individual nodes in a piece of XML that are exposed by DOM Traversal
XMLUnit for Java can also treat HTML content (even badly-formed HTML) as valid XML to allow these assertions to be made about the content of web pages too.

More information in the tutorial: http://xmlunit.sourceforge.net/userguide/html/index.html

Hazelcast - more then distributed cache

Hazelcast is an open source clustering and highly scalable data distribution platform for Java, which is:
  • Lightning-fast; thousands of operations/sec.
  • Fail-safe; no losing data after crashes.
  • Dynamically scales as new servers added.
  • Super-easy to use; include a single jar.

With its various distributed data structures, distributed caching capabilities, elastic nature, memcache support, integration with Spring and Hibernate and more importantly so many happy users, Hazelcast is feature-rich, enterprise-ready and developer-friendly in-memory data grid solution.

To run it you just run a single jar file!

Presentation is available here: http://www.hazelcast.com/screencast.jsp

JUnitParams - librabry for JUnit

This project adds a new runner to JUnit and provides much easier and readable parameterised tests for JUnit >=4.6.

Main differences to standard JUnit Parameterized runner:

  • more explicit - params are in test method params, not class fields
  • less code - you don't need a constructor to set up parameters
  • you can mix parameterised with non-parameterised methods in one class
  • params can be passed as a CSV string or from a parameters provider class
  • parameters provider class can have as many parameters providing methods as you want, so that you can group different cases
  • you can have a test method that provides parameters (no external classes or statics anymore)
  • you can see actual parameter values in your IDE (in JUnit's Prameterized it's only consecutive numbers of parameters):

More on project page: http://code.google.com/p/junitparams/

Bending the Java spoon - op4j

op4j is a powerful implementation of the Fluent Interface style of code. It allows you to create chained expressions which apply both predefined or user-defined functions to your objects in a fluid and readable way. This improves the way your code looks and greatly reduces the complexity of executing auxiliary low-level tasks in the highly bureaucratic, statically -and strongly- typed language that Java is.
It is a great library for complicated operations on Collections in one line.
More on: http://www.op4j.org/

Tuesday, 10 July 2012

Do not implement/generate getters and setters!

Project lombok is a java library which prevents you from implementing or generating getters and setters for POJOs. You just add annotation on the class or on the individual property. Having such code, that just gets and sets properties is unmaintainable and bad for class clarity.
This library has also some other useful features like f.e. @Delegate - annotation that ease creating classes with delegation methods.

Here you can see examples:http://projectlombok.org/features/index.html

Tomcat startup takes extra 3 minutes. Why?

I have faced a problem of long startup of tomcat 7 that used jvm 7 on the linux server. Tomcat without any application started over 3 minutes. In the catalina.out log there was a message:
May 22, 2012 10:02:48 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation
using [SHA1PRNG] took [131,611] milliseconds.
This problem appears due to Tomcat 7+ usage of SecureRandom class to provide random values for its session ids. You can use non-blocking setup, just set the following system property: -Djava.security.egd=file:/dev/./urandom
You can read more on this subject in tomcat wiki: http://wiki.apache.org/tomcat/HowTo/FasterStartUp

Monday, 9 July 2012

Invoke dynamic in java 7

Recently I have attended Confitura 2012 a Java Conference in Warsaw. One of the most interesting lectures was the one made by Waldemar Kot. He has introduced subject of the new instruction in Java 7: Invoke dynamic.
He has shown that it has a very big impact on the java development, not only on dynamic languages on JVM. Using invoke dynamic in java you can have dynamic behavior with speed comparable to static invocation.
You can see examples and benchmarks here: https://github.com/waldekkot/Confitura2012_InvokeDynamic

Wednesday, 4 July 2012

Let's try implement an algorithm

If you want to train implementing algorithms you can go to the Project Euler.

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

Corkboard online

If you want to have a place to stick your notes in the virtual then you can try: http://corkboard.me

Rod Johnson has left SpringSource

Rod Johnson the father of Spring, co-founded SpringSource has decided to leave SpringSource. He grew a company building a Spring Framework a better Java Enterprise Edition.
His leaving post: blog.springsource.org/2012/07/03/oh-the-places-youll-go/

Sunday, 1 July 2012

Exposing monitoring by JMX in Spring application

To expose methods as MBeans in the Spring Application by JMX you have to:
  • Declare in the application configuration: <context:mbean-export/>
  • Annotate java class with @ManagedResource
  • Annotate getters or setters with <@ManagedAttribute>
After that you can connect by jconsole to your application and use annotated methods.
You can also use annotations: @ManagedOperation, @ManagedNotification for methods that are not setters or getters.