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.

Links:

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:

Messaging-related:

  • 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

Spring-related:

  • 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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:/greeter-jms.properties"/>

    <bean id="greeterConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
        <property name="connectionFactory">
            <bean class="org.apache.activemq.ActiveMQConnectionFactory">
                <property name="brokerURL">
                    <value>${greeter.brokerUrl}</value>
                </property>
            </bean>
        </property>
    </bean>

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

and use it then in the java code:

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

    @Override
    public void send(final Greeting greeting) {
        jmsOperations.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                final StreamMessage message = session.createStreamMessage();
                message.writeString(greeting.getMessage());
                message.writeInt(greeting.getCount());
                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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:amq="http://activemq.apache.org/schema/core"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
        http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <!--JMS broker, sample for CLUSTER URL: 'failover:(tcp://12.13.14.100:61616,tcp://12.13.14.101:61616)?randomize=true'-->
    <amq:connectionFactory id="listenerAmqConnectionFactory" brokerURL="tcp://127.0.0.1:61616"/>

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

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

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

    <!-- Camel context -->
    <camelContext id="listenerCamelContext" xmlns="http://camel.apache.org/schema/spring">
        <routeBuilder ref="listenerRouteBuilder"/>
    </camelContext>

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

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

public final class ListenerRouteBuilder extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("activemq:alexshabanov.cameldemo.greeter").to("greetingHandler");
    }
}

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

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

    @Autowired
    private GreetingSinkService greetingSinkService;

    @Override
    public void process(Exchange exchange) throws Exception {
        log.info("Got exchange id={}", exchange.getExchangeId());
        final StreamMessage message = exchange.getIn().getBody(StreamMessage.class);
        final Greeting greeting = new Greeting(message.readString(), message.readInt());
        log.info("- Parsed {}", greeting);
        greetingSinkService.putGreeting(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 --url=alexshabanov.com

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
        applicationContext.register(Config.class);

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

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

        try {
            applicationContext.getBean(Runnable.class).run();
        } finally {
            applicationContext.close();
        }
    }

    @Configuration
    public static class Config {
        @Autowired
        private Environment environment;

        @Bean
        public Runnable myBean() {
            return new MyBean(environment.getProperty(URL_PARAM_KEY, "http://127.0.0.1:8080"));
        }
    }

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

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

        @Override
        public void run() {
            LOG.info("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.

    Test.java:7: warning:
    [unchecked] unchecked generic array creation
    for varargs parameter of type List<String>[]
        Arrays.asList(Arrays.asList("January",
        ^
    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 README.md 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 readme.md

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 + inferior.foo(); }
}

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

    final Superior superior = context.getBean(Superior.class);
    assertEquals(11, superior.bar());
}

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
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SchedTest.Config.class })
public class SchedTest {

    private static final String SERVICE_KEY = "SERVICE_KEY";

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ApplicationContext context;

    @Test
    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));
        }
        Thread.sleep(1000L);
    }

    private Trigger createSingleshotTrigger(String triggerName, long delay) {
        final SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
        simpleTrigger.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
        simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + delay));
        simpleTrigger.setRepeatCount(0);
        simpleTrigger.setName(triggerName);
        simpleTrigger.setRepeatCount(0);
        return simpleTrigger;
    }

    private JobDetail createJobDetail(String jobName, String url) {
        final JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        jobDetailFactoryBean.setApplicationContext(context);
        jobDetailFactoryBean.setName(jobName);
        jobDetailFactoryBean.setJobClass(JobStarter.class);
        jobDetailFactoryBean.afterPropertiesSet();

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

        return jobDetail;
    }

    public static class JobStarter implements Job {

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

                final ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(
                        ApplicationContext.class.getName());

                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);
            }
        }
    }

    @Configuration
    public static class Config {

        @Bean
        public SchedulerFactoryBean schedulerFactoryBean() {
            final SchedulerFactoryBean bean = new SchedulerFactoryBean();
            bean.setApplicationContextSchedulerContextKey(ApplicationContext.class.getName());
            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");
    unsafeField.setAccessible(true);
    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)!