Category Archives: Java

Non-AOP based approach for implementing service layer in Kotlin

Usually when you’re adding a service layer in java you have to deal with so-called cross-cutting concerns in your service such as adding uniform logging for your service methods and dealing with exceptions in a uniform way.

This can be done in multiple ways. As any seasonal programmer knows, direct, brute-force approach when you’re writing this code every time for each method just doesn’t work well. If you’re doing it yourself for every method and every service in your application you’re cluttering your code and just making it harder to maintain and extend as for any significant changes in your cross-cutting code you have to rewrite service implementations for every method. Or, simply put, it requires O(n) efforts, where n is a count of methods in your service layer.

More traditional approach to address this problem is to use AOP. Comparing to the previous approach it requires just O(1) efforts. However AOP is viewed as a hack by OOP purists.

In this article I’ll try to describe another approach which doesn’t use anything besides plain old OOP and at the same time will require the same O(1) efforts for implementing cross-cutting concerns in your code.

So, let’s start. We’ll need a some sort of API for that framework that would support cross-cutting concerns. Let’s define it.

Public API for our framework

If we want to deal with input and output data in a uniform way, we can start with the generic Request and Result traits that would define input and output data for our service calls:

trait Result trait Request

These traits will merely designate (or mark) your domain objects that will carry the data that will be needed to make a particular request or will identify your service response.

As a service might return result of a remote call or any lengthy operation we can come up with a trait that will represent a result of asynchronous call:

trait Response {
  fun get(): TResult

As you may probably noticed this trait looks like a simplified version of Future interface. The reason why we might not want to use Future here is because usually we just don’t need to deal with its complicated interface: it also has get() method and its more complicated counterpart, but using these methods may not be convenient for application programmer as get() waits for a response indefinitely and we may not want to do that as usually we want to work with service that define certain SLA. And the other get(time, timeUnit) method is just not convenient to call as you need to know and set that time manually. In our Response trait we defined get() method out of an assumption that it will deal with setting service timeouts according to those services SLAs (as well as dealing with retries) and we won’t let the consumers of our service API deal with this operational burden.

Also, for our service implementers we’ll need to provide a convenient way of creating Response objects:

trait ResponseCreator {
  fun create(request : TRequest, calcFun: (TRequest) -> TResult) : Response

This trait will provide an interface to the service implementer that will abstract away dealing with cross-cutting stuff such as logging request and responses, measuring execution time etc.

Sample Usage

So, here is how it may look like from the service implementer’s point of view:

// Sample Service API

trait GetUserProfilesRequest : Request {
  val userIds : List

trait UserProfile {
  val id : Long?
  val name : String
  val avatarUrl : String

trait GetUserProfileResult : Result {
  val profiles : List

trait UserService {
  fun getUserProfiles(request : GetUserProfilesRequest) : Response

// Sample Service Impl

data class UserProfileImpl(override val id : Long?,
                           override val name : String,
                           override val avatarUrl : String) : UserProfile

data class GetUserProfileResultImpl(override val profiles : List) : GetUserProfileResult

data class GetUserProfileRequestImpl(override val userIds : List) : GetUserProfilesRequest

class UserServiceImpl(val responseCreator : ResponseCreator) : UserService {
  override fun getUserProfiles(request: GetUserProfilesRequest): Response {
    return responseCreator.create(request, { (r) -> /* hey mom, look at this amazing type inference! */
      val result = ArrayList(r.userIds.size)
      for (id in r.userIds) {
        result.add(UserProfileImpl(id = id, name = "user#${id}", avatarUrl = "http://avatarUrl_${id}"))
      GetUserProfileResultImpl(profiles = result)

Sample Framework Implementation

Sample, synchronous implementation of ResponseCreator is shown below (note, that this code also contains “aspect” behavior which may be common for all the services you’re working with in your application):

 * Sample response, in real applications may use Futures with the default service SLA timeouts/retries
class ImmediateResponse(val result : TResult) : Response {
  override fun get(): TResult = result

 * Sample response creator
class ImmediateResponseCreator : ResponseCreator {
  override fun create(request: TRequest,
                                         calcFun: (TRequest) -> TResult): Response {
    // [1] log request
    println(" > request = ${request}")
    // [2] start measuring time
    val startTime = System.currentTimeMillis()
    try {
      val result = calcFun(request)
      // [3] stop measuring time
      val timeDelta = System.currentTimeMillis() - startTime
      // [4] log result and execution time
      println(" > result = ${result}, timeDelta = ${timeDelta}")
      return ImmediateResponse(result)
    } catch (e : Exception) {
      // [3] stop measuring time
      val timeDelta = System.currentTimeMillis() - startTime
      // [4] log exception and execution time
      println(" > error = ${e.getMessage()}, timeDelta = ${timeDelta}")
      throw e // rethrow an exception

Full listing may be found in this gist.


Oracle+JDBC: how to insert value to the ANYDATA field

This is a short note about working with Oracle’s ANYDATA type, mostly for myself, but may be it will be useful to those who works with Oracle DB via JDBC.
In short: ANYDATA is a “variant” type that allows user to write arbitrary value to it including number, string, structure and so on.

So, assuming you have a table

CREATE TABLE mytable (
    myval        sys.ANYDATA

You can use the following SQL to insert the data to it:

INSERT INTO mytable (myval) VALUES (anydata.convertNumber(1));
INSERT INTO mytable (myval) VALUES (anydata.convertVarchar2('hi'));

The main question to me was how to do the same via JDBC. And this is pretty simple if you are aware of the Oracle’s JDBC driver domain model.
Basically Oracle guys provide you with oracle.sql.ANYDATA type that can work with the oracle.sql.Datum instances so that you can construct ANYDATA instance via oracle.sql.ANYDATA.convertDatum(oracle.sql.Datum datum) public static method.

Notice, that Oracle have wrappers for all the standard DB types including numbers and strings, and all of that wrappers, e.g. oracle.sql.NUMBER actually implement oracle.sql.Datum base.

So in JDBC you can do the following:

final ANYDATA value = ANYDATA.convertDatum(new NUMBER(1)); // throws SQLException
// here I use spring's JDBC template, but you can do the very 
// same via the standard PreparedStatement means
jdbcOperations.update("INSERT INTO mytable (myval) VALUES (?)", value);

Maven: Build selected projects

I was surprised when I re-discovered that feature in maven a few days ago. You don’t need to read any further if you constantly use this feature, but those who don’t know about it may find this useful. In fact I never have a dire need in a “partial build” feature, but still it is very nice to have in multimodular maven project especially with multiple heavy projects.

So, in short: in multimodular maven project you can build the selected artifacts without the need to rebuild all again.

Here is how we can do it by sample – the following snippet tells maven to build two projects: myproj-domain and myproj-service without running tests:

mvn install -pl myproj-domain,myproj-service -DskipTests=true

Demo: Spring + Apache Camel + Active MQ

I created this project as an illustration to my colleagues that are new to java and J2EE. The project is hosted on github.

This demo project illustrates how to use ActiveMQ in multiple-modular Spring project with shared code. One demo project is greeter-web-app or just greeter, application, that sends greeting message to the listener or listener-web-app.

The most interesting things about this code:


  • Illustration on how to send custom java bean over the JMS by using binary serialization to the StreamMessage.
  • Spring JMS module usage. See GreeterServiceImpl
  • Apache Camel usage. Consuming messages from the ActiveMQ queue and putting them to the custom bean. See ListenerRouteBuilder


  • Loading properties.
  • Using mixed configuration: both annotation-driven and xml-driven configs are used in listener-web-app.
  • Spring MVC web applications.

It is fairly simple to configure JMS:

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

    <context:property-placeholder location="classpath:/"/>

    <bean id="greeterConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
        <property name="connectionFactory">
            <bean class="org.apache.activemq.ActiveMQConnectionFactory">
                <property name="brokerURL">

    <bean id="greeterJmsOperations" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="greeterConnectionFactory"/>
        <property name="defaultDestinationName" value="${greeter.channelName}"/>

and use it then in the java code:

    @Resource(name = "greeterJmsOperations")
    private JmsOperations jmsOperations;

    public void send(final Greeting greeting) {
        jmsOperations.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                final StreamMessage message = session.createStreamMessage();
                return message;

As for listener part I used Apache Camel, its configuration is fairly simple:

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

    <!--JMS broker, sample for CLUSTER URL: 'failover:(tcp://,tcp://'-->
    <amq:connectionFactory id="listenerAmqConnectionFactory" brokerURL="tcp://"/>

    <!-- JMS channel: alexshabanov.cameldemo.greeter -->

    <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
        <property name="connectionFactory" ref="listenerAmqConnectionFactory"/>

    <bean id="listenerRouteBuilder" class="com.alexshabanov.cameldemo.listener.route.ListenerRouteBuilder"/>

    <!-- Camel context -->
    <camelContext id="listenerCamelContext" xmlns="">
        <routeBuilder ref="listenerRouteBuilder"/>

    <!-- Camel handlers -->
    <bean id="greetingHandler" class="com.alexshabanov.cameldemo.listener.route.handler.GreetingHandler"/>

the most interesting parts in this config is a route builder, it’s really simple in this sample:

public final class ListenerRouteBuilder extends RouteBuilder {

    public void configure() throws Exception {

and JMS handler (greeting handler) that receives JMS stream message:

public final class GreetingHandler implements Processor {
    private final Logger log = LoggerFactory.getLogger(GreetingHandler.class);

    private GreetingSinkService greetingSinkService;

    public void process(Exchange exchange) throws Exception {"Got exchange id={}", exchange.getExchangeId());
        final StreamMessage message = exchange.getIn().getBody(StreamMessage.class);
        final Greeting greeting = new Greeting(message.readString(), message.readInt());"- Parsed {}", greeting);

Command Line Applications with Spring

It was quite a surprising for me to find that Spring already have built-in support for CLI applications – I was particularly interested in the argument parsing.

I’ve created a small spring demo project on github.

You can try to start it by java -jar target/cli-demo-jar-with-dependencies.jar

The code is quite simple and self evident:

public final class CliDemoApp {
    public static final Logger LOG = LoggerFactory.getLogger(CliDemoApp.class);

    public static final String URL_PARAM_KEY = "url";

    public static void main(String[] args) {
        LOG.trace("CLI demo app");

        // should use parameterless constructor as the other one invoke refresh which we certainly don't want
        // as it automatically trigger property injection and our CLI property is not ready yet
        final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // setup configuration

        // add CLI property source
        applicationContext.getEnvironment().getPropertySources().addLast(new SimpleCommandLinePropertySource(args));

        // setup all the dependencies (refresh) and make them run (start)

        try {
        } finally {

    public static class Config {
        private Environment environment;

        public Runnable myBean() {
            return new MyBean(environment.getProperty(URL_PARAM_KEY, ""));

    public static final class MyBean implements Runnable {
        private final String url;

        public MyBean(String url) {
            this.url = url;

        public void run() {
  "MyBean run with url = {}", url);

jnova – One another Java 6 parser

I’ve decided to opensource one experimentation project I did some time ago.
This project is a set of libraries that include common library that might be useful for compiler construction.
The project is available on github.

Core module defines reusable parts that is not tied to java, such as

  • DiagnosticsLog – the reporter component that is able to provide the user with nicely formatted message, e.g. warning:
    [unchecked] unchecked generic array creation
    for varargs parameter of type List<String>[]
    1 warning
  • Naming module – efficient UTF-8 symbol table
  • Bundle – Resource bundle support
  • Tag – generic taggable base class that may be subclassed to provide certain class hierarchy with customizable user data
  • ImmList – a very small and efficient immutable alternative to the java’s LinkedList

See on how this works and unit tests as usage demos.

REST API and Spring 3.1

I’ve updated my github project that illustrates the best practices for building client-server applications with RESTful interface between server and client.
This sample uses maven, spring mvc and jackson and illustrates code sharing between client and server and quick approach to testing the exposed RESTful API by using JUnit tests.

Happy coding!

Micro DI module

Some time ago I wrote a small dependency injection library (really small, footprint is about 10 Kb!) and I’d like to share it with you.

The project page on git is here.

The project is released under Apache 2.0 license.

You can easily add this to your maven project – see

Sample usage:

public interface Inferior {
    int foo();

public interface Superior {
    int bar();

public class InferiorImpl implements Inferior {
    @Override public int foo() { return 1; }

public class SuperiorImpl implements Superior {
    @Resource protected Inferior inferior;

    @Override public int bar() { return 10 +; }

public void shouldInjectOneBeanWithinAnother() {
    context.registerBean(new SuperiorImpl());
    context.registerBean(new InferiorImpl());

    final Superior superior = context.getBean(Superior.class);

Quartz+Spring scheduling-on-demand sample

Some time ago I stumbled at issues with Quartz 2 and Spring 3. All the standard samples illustrate fairly simple use cases and there were no samples dedicated to quite a frequent task: schedule certain job on demand, not to mention that some “standard” spring classes dedicated to ease work with Quartz are outdated and introduces some misterious errors in runtime (IncompatibleClassChangeError is one of these ones).

To illustrate this particular kind of task when you need scheduling-on-demand suppose you have a procedure that must be scheduled after the user entered some data and then executed after some time.

One of the best solution that is reliable and has fail-over on top of inner DB persistence, clustering capabilities is Quartz.

I’ve wrote a JUnit test that doesn’t test anything but actually illustrates the work with Quartz, it is quite self evident:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Date;

 * Test scheduling-on-demand with spring and quartz
@ContextConfiguration(classes = { SchedTest.Config.class })
public class SchedTest {

    private static final String SERVICE_KEY = "SERVICE_KEY";

    private Scheduler scheduler;

    private ApplicationContext context;

    public void shouldExecuteSampleJob() throws Exception {
            final String id = "1";
            scheduler.scheduleJob(createJobDetail(id, "task1"), createSingleshotTrigger(id, 100L));
            final String id = "2";
            scheduler.scheduleJob(createJobDetail(id, "task2"), createSingleshotTrigger(id, 150L));

    private Trigger createSingleshotTrigger(String triggerName, long delay) {
        final SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
        simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + delay));
        return simpleTrigger;

    private JobDetail createJobDetail(String jobName, String url) {
        final JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();

        final JobDetail jobDetail = jobDetailFactoryBean.getObject();
        // data
        jobDetail.getJobDataMap().put("url", url);

        return jobDetail;

    public static class JobStarter implements Job {

        public void execute(JobExecutionContext context) throws JobExecutionException {
            try {
                final SchedulerContext schedulerContext = context.getScheduler().getContext();

                final ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(

                final JobDetail jobDetail = context.getJobDetail();
                final String url = jobDetail.getJobDataMap().getString("url");
                System.out.println("url=" + url + ", applicationContext=" + applicationContext);
            } catch (SchedulerException e) {
                throw new JobExecutionException(e);

    public static class Config {

        public SchedulerFactoryBean schedulerFactoryBean() {
            final SchedulerFactoryBean bean = new SchedulerFactoryBean();
            return bean;

Sun unsafe API

It is quite interesting that though Unsafe API is forbidden to be used in the “normal” java applications, it is still possible to access it, though it is strictly discouraged in the production code. I do it “just for fun” and don’t recommend for use in any “real” applications.

In short: unsafe API (sun.misc.Unsafe) allows access to native sun-specific API such as allocating chunk of native memory, get internal offsets for quick property sets and etc.
Though addressing Unsafe.getUnsafe generates compiler error it is possible to access it via reflection by reading static private properties from some classes, such as AtomicReference:

try {
    final Field unsafeField = AtomicReference.class.getDeclaredField("unsafe");
    final Unsafe u = (Unsafe) unsafeField.get(null);
    System.out.println("unsafe: " + u);
    // ...
catch (Exception e) { /* ... */ }

I was especially curious on quick, non-reflection driven property access.
It may be done via Unsafe.put* methods, such as Unsafe.putInt.

For example, if you have the following point object:

class Point2DV {
    int x;
    int y;

you may access x and y fields by addressing them directly.

The following snippet demonstrates it:

final long xOffset = u.objectFieldOffset(Point2DV.class.getDeclaredField("x"));
final long yOffset = u.objectFieldOffset(Point2DV.class.getDeclaredField("y"));
final Point2DV p = new Point2DV();
u.putInt(p, xOffset, 872);
u.putInt(p, yOffset, 1134);
System.out.println("offsetof(Point2DV.x) = " + xOffset + ", p.x = " + p.x);
System.out.println("offsetof(Point2DV.y) = " + yOffset + ", p.y = " + p.y);

It is quite curious to see that the offset of the very first property is 12 which tells us that *every* java object contains at least 12 bytes in memory which in its turn results that in reality even an object with no fields would occupy at least 16 bytes since jvm uses 8-bytes offsets).

Have fun (and never use it in real projects)!