All posts by admin

Select a bunch of values from the DB sequence at a time

Sometimes you need to select multiple values from certain sequence. Surprisingly it is not that easy to find the relevant information on how to do it in Google.
Here is the quick snippets for those who need it. In this snippet my_seq assumed to be a name of the previously created sequence (e.g. CREATE SEQUENCE my_seq) and 42 assumed to be the number of sequence values you want to pick from sequence in one turn.

For Oracle:

SELECT my_seq.nextval FROM dual CONNECT BY level <= 42

For H2 (I heavily use it for unit testing in favor to Oracle because it is fast, small and cool):

SELECT my_seq.nextval FROM system_range(1, 42)

Offtopic:
It is worth to mention that in H2 you can very easily select a sequence of natural numbers by accessing system_range function. E.g. if you want to get a set of {1, 2, 3, 4, 5, 6, 7, 8} you may just do SELECT * FROM system_range(1, 8). I never knew this function before and I'm happy for being accidentally find it.

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

NB: Control SBCL optimizations

Note, that you can control how SBCL optimizes certain function (or performs global optimizations).

You can use declare block in functions:

(declare (optimize (safety 3) (debug 3) (speed 0) (space 0)))

This directive means: favor safety and debug over speed and space. The more value is associated with the corresponding directive (i.e. safety, speed, debug or space) the more SBCL compiler values this parameter when it compiles your source.

Debugging priority might be established globally by similar declaration:

(declaim (optimize (safety 3) (debug 3) (speed 0) (space 0)))

SBCL also has internal function that restricts compiler to assign the corresponding weight to the certain compilation parameter:

(sb-ext:restrict-compiler-policy 'debug 3)

Prime Obsession

While being on the vacations I found an excellent popular math book, probably the best book in its genre: Prime Obsession by John Derbyshire.

This book tells about one of the greatest and deepest mathematical problems: The Riemann Hypothesis.

One of the best qualities of this book is its style – you don’t need to be a professional mathematician to understand that, especially to understand depth and beauty of this problem (which seem to me overly complex when I first seen it a few years ago, out of pure interest).

The book also briefly introduces all the required mathematical basis to understand the hypothesis and the related things. It does so in brief but understandable manner, even quite a complex mathematical concepts as operator theory and theory of functions of a complex variable are given in elegant and understandable manner. You don’t need to be a professional mathematician to understand that yet you will be able to verify the formulas and theorems given in the book by yourself and find that the mathematics beyond that hypothesis is beautiful beyond words. It is amazing to see how seemingly disparate mathematical branches as math analysis, complex numbers, matrix stuff, number theory and even quantum mechanics are related to this problem and discover its fantastic depth.

Unlike most of the ordinary fictional and popular books you can return to this one again and again since it is very deep and versatile.

Hope you’ll enjoy it as I did :)

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