Archive for Java

How to use Java Web21c SDK from Scala

It is an example how to use the Web21c SDK from a Scala application.

First couple of words about Scala. Scala was created in 2001 at the École Polytechnique Fédérale de Lausanne (EPFL) in Switzerland. It is platform independent, multi-paradigm language which integrates features of object-oriented and functional programming, is type-safe (but you don’t have to define redundant types of information) and extensible (good candidate for DSLs). It brings a lot of very nice syntactical sugar as well! As Scala smoothly integrates with Java and .Net worlds we can run Scala applications on JVM or .NET CLR and easily reuse existing libraries for those platforms.

One of those libraries is Web21c SDK which gives us easy way of integrating communication services and comes in couple of flavours: SDK for Java, .Net, Python and PHP. We could integrate Scala with Java or .NET SDK but for the purpose of this example we will see how easy it is to incorporate Java SDK into our Scala application.

Let’s assume we use Scala plugin for Eclipse and we created a new Scala project.

We can get the latest Web21c SDK for Java and before proceeding to next steps we have to register our application and obtain own certificate for sandbox server which is free. Then we will create two folders: lib and resources in our project and we will unzip content of the Web21C-JavaSDK-5.0.zip and copy content of the lib folder from SDK to our lib folder. Let’s copy the Web21C-JavaSDK-5.0.jar there as well. We will copy previously obtained certificate to the resources folder and we will create a properties file called security.properties where you can store name of your cert and its password:

org.apache.ws.security.crypto.provider=com.bt.security.PKCS12Crypto
org.apache.ws.security.crypto.merlin.keystore.type=pkcs12
org.apache.ws.security.crypto.merlin.keystore.password=YOUR_CERTIFICATE_PASSWORD
org.apache.ws.security.crypto.merlin.alias.password=YOUR_CERTIFICATE_PASSWORD
org.apache.ws.security.crypto.merlin.file=YOUR_CERTIFICATE.pfx

constants.provider=com.bt.sdk.common.SandboxConstants

Next from Eclipse in the project Properties/Java Build Path/Source/Add Folder… we will add resources folder to the classpath and all jars from lib folder to the Properties/Java Build Path/Libraries/Add JARs… to place them on the classpath as well. We should be good to go.

Then we will create the Scala singleton where we will use directly Java objects. For example Manager classes for one of the Web21c services, for instance One Way Messaging to create a simple sms client (src/SmsClient.scala):

import com.bt.sdk.capabilities.messaging.oneway.MessagingOneWayManager

object SmsClient {
    def main(args: Array[String]) {
        new MessagingOneWayManager().sendMessage("tel:44xxxxxxxxx", "Hello World")
    }
}

Or even simpler:

import com.bt.sdk.capabilities.messaging.oneway.MessagingOneWayManager

object SmsClient extends Application {
    new MessagingOneWayManager().sendMessage("tel:44xxxxxxxxx", "Hello World")
}

Is that close to the famous “one line of code”?

Our project’s structure should look more or less like:

+ Web21cAndScala
    L---+ src
        L--- Web21c.scala
    L---+ bin
        L--- //compiled classes
    L---+ lib
        L--- Web21C-JavaSDK-5.0.jar
        L--- //other jars from lib folder
    L---+ resources
        L--- sandbox.pfx
        L--- security.properties

We are ready to try if it works. Try Run As… Scala Application. Great if it works! If you get following error:

Exception in thread "main" Reporting Service: Unknown
com.bt.sdk.ServiceException: Unknown exception encountered: java.lang.ExceptionInInitializerError
null
    at com.bt.sdk.capabilities.messaging.oneway.MessagingOneWayManager.<init>(MessagingOneWayManager.java:26)
    at SmsClient$.main(SmsClient.scala:7)
    at SmsClient.main(SmsClient.scala)

Then it means that folks from Lausanne haven’t fixed the bug in Scala Eclipse Plugin yet. It simply doesn’t copy resources on the classpath to the output folder (bin) and the Web21c Java SDK can’t see security.properties and the certificate. For purposes of this exercise you can simply copy content of the resources folder to the bin folder. As hot fix you could also create an ant task similar to the one below. You can make the execution of one or more targets from an Ant build part of the normal build of your project:

<?xml version="1.0" encoding="UTF-8"?>
<project name="copyprops" default="default" >
    <target name="default" >
        <copy todir="${basedir}/bin">
            <fileset dir="${basedir}/src" includes="**/*.*" excludes="**/*.scala"/>
        </copy>
    </target>
</project>

I know that it is very simple demo but I hope it will be of any use for someone. Let me know if you are having any issues with the sample. And remember that Sandbox Usage is restricted.

Popularity: 65% [?]

Comments

Hibernate Shards

There are situations when you can’t put all data which you need in a single instance of a relational database. The reasons may differ. Maybe because it is too much of the data itself. Or there is a problem with network latency of a distributed architecture. Scaling? Or one of many other reasons. The answer is: horizontal partitioning. The process of splitting up your data sets that once has been called partitioning, now, it has a new name: sharding. If your data doesn’t fit on one machine you split it up into segments and each segment is called a shard. It is term used initially at Google but now spreading everywhere.

So… There is a new project Hibernate Shards which is a framework that is designed to encapsulate and minimize complexity of accessing multiple databases by adding support for horizontal partitioning on top of Hibernate Core. It was once the 20 percent project at Google but it is open-sourced now and licensed under the LGPL. If you know the Core Hibernate API you know the Shards API as its implementation hasn’t violated the Core API. Basic assumptions and paradigms for using Hibernate are still valid as Configuration, SessionFactory, and Session objects are almost exactly the same. Interfaces from Hibernate Core:

  • org.hibernate.Session
  • org.hibernate.SessionFactory
  • org.hibernate.Criteria
  • org.hibernate.Query

have shard-aware extensions:

  • org.hibernate.shards.session.ShardedSession
  • org.hibernate.shards.ShardedSessionFactory
  • org.hibernate.shards.criteria.ShardedCriteria
  • org.hibernate.shards.query.ShardedQuery

The implementations for these four interfaces serve as a sharding engine that knows how to apply an application-specific sharding logic. This logic is a set of rules how data is distributed across its shards. To specify this logic we have to implement the interfaces below:

  • org.hibernate.shards.strategy.selection.ShardSelectionStrategy
  • org.hibernate.shards.strategy.resolution.ShardResolutionStrategy
  • org.hibernate.shards.strategy.access.ShardAccessStrategy

Hibernate Shards comes with a couple of simple implementations of these interfaces. For instance for the Shard Selection Strategy we have choice of sequential (load balanced round robin) or parallel access.

To finish the topic of the sharding logic I shall mention the id generation as well. As the standard database sequences can’t be used in distributed environment we have a choice of two primary key generators:

  • ShardedUUIDGenerator - that generates a big random number
  • ShardedTableHiLoGenerator - that uses a table in one of the shards to generate the primary key. Obviously it is a single point of failure for our system.

Although project is still in its early stage and even the creators warn about possible glitches this nice wrapper for hiding all the complexity of distributing data around multiple relational databases is very much worth looking at, especially if the Hibernate is already used as the ORM tool of choice.

Popularity: 50% [?]

Comments

Eclipse 3.3 leaks permgen space

EclipseSome of you who use Eclipse 3.3 with Sun JVM might notice that it crashes from time to time. Those who have many plugins certainly experienced this more often. Problem and solution for this bug is very trivial but worth mentioning: leaking permgen space. Comes back like November flu! Just to remind the permgen space is a memory for storing “data needed by the virtual machine to describe objects that do not have an equivalence at the Java language level. For example objects describing classes and methods are stored in the permanent generation“. More information about permgen can be found in an article about tuning garbage collection.

To fix the problem edit your eclipse.ini and add following lines:

-XX:PermSize=128M
-XX:MaxPermSize=256M

You might also try Eclipse 3.3.1.1 which includes a fix for the above problem.

Enjoy!

Popularity: 48% [?]

Comments (1)

Integrating AStyle into your Ant build

AntThis blog entry will introduce you how to integrate AStyle into your Ant build.

Short introduction: In my current project I work on software which generates SDKs for multiple languages consuming Web21C services . The SDKs are SOAP webservice clients for multiple languages as Java, Python, PHP or .Net (new are comming soon). XSLT transformations are extensively in use to achieve the goal of generating those SDKs.

The problem is that we are facing a trade off:

  • we have ugly formatted XSL to be able to generate correctly formatted output code
  • we can have pretty formatted and easy to maintain and read XSL but not correctly formatted output in particular language

Let’s assume that we are not crazy yet and we will not follow the first option. The second option looks better but is still not perfect. We need to plug a tool which will do the dirty job for us: correct indentation, format and beautify our output source. Artistic Style (AStyle) has been selected as the tool as it is small, simple, fast tool and supports both Java and C#.

However the AStyle has couple of downsides:

  • doesn’t have easy integration with Ant
  • accepts only list of files for transformation, there is no recursive mode

Let’s assume that all source files to be transformed are in folder generated, with multiple subfolders. As there is no integration with Ant we will have to use <exec/> task. Something like:

<property name="astyle.exe" location="${astyle.home}/astyle.exe"></property>
<exec executable="${astyle.exe}" dir="${basedir}">
    <arg value="--mode=java"></arg>
    <arg value="--style=java"></arg>
    <arg value="--suffix=none"></arg>
    <arg value="${sourcefile}"></arg>
</exec>

AStyle accepts following arguments:

astyle [options] SourceFile1.java SourceFile2.java SourceFile3.java [...]

Wouldn’t it be nice to have -R option?

Our first approach could be construction of a space separated list of paths to all files in folder generated and then using this as argument in exec task. We would quickly realize that we have a possible problem with maximum length of a command line executed via exec task which is just 256 characters. Better will be to execute astyle many times, for each file to be formatted. Core Ant task are not enough in this case. We have to use ant-contrib tasks. First copy ant-contrib jar to your ANT_HOME/lib and add in your build:

<taskdef resource="net/sf/antcontrib/antlib.xml" />

It will let you use <for/> task which should help us to solve our problem as it will allow us to iterate over list of paths and execute external command for each one. The final ant task could look like:

<target name="format">
    <for param="file">
        <path>
  	    <fileset dir="${generated}" includes="**/*.java"/>
  	</path>
  	<sequential>
  	    <property name="astyle.exe" location="${astyle.home}/astyle.exe" />
	    <exec executable="${astyle.exe}" dir="${basedir}">
	        <arg value="--mode=java"/>
	        <arg value="--style=java"/>
	        <arg value="--suffix=none"/>
	        <arg value="@{file}"/>
	    </exec>
  	</sequential>
    </for>
</target>

Fist we define a name of the parameter to pass the tokens or files to the sequential, let’s call it just file. Note that for makes use of ant’s macrodef task, so the @{} notation is used for parameter substitution. Next we define path including all java files in generated folder. The last step is to use <sequential/> block where the execution of astyle.exe will happen for each source file defined using @{file} parameter.

Popularity: 41% [?]

Comments

Mylyn web connector

Again about the Mylyn plugin. If you install Eclipse 3.3 Europa there isn’t, due to the Mylar -> Mylyn renaming, the web connector plugin which could be found in the Mylyn 1.0. This plugin is useful when we are working with an unsupported web based bug repository. The plugin still exists but can be found in a separate update site. Simply add new remote update site: http://download.eclipse.org/tools/mylyn/update/extras to find a set of Mylyn plugins including the web connector.

If I find some time I will try to connect to Scrum Works repository using that plugin. If someone has done it already please let me know.

Popularity: 39% [?]

Comments

Serializing objects to HSQLDB using blobs

Our task is to persist a state object called State in a database. State object has globally unique identifier and some other properties. And is serialisable.

Let’s start with creating methods for serialisation/deserialisation:

protected byte[] serialise(T state) {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(state);
        oos.flush();
        return bos.toByteArray();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
protected T deserialise(byte[] byteArray) {
    try {
        ObjectInputStream oip = new ObjectInputStream(new ByteArrayInputStream(byteArray));
        return (T) oip.readObject();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException(e);
    }
}

So, we know how to serialise and deserialise object. The next step would be to think where to store that data. I have chosen HSQLDB for that example but it should be very easy to swap to some other db. It should be as easy as changing datasource properties and maybe amend a bit create script. Let’s crate one then for HSQLDB:

create table State (
object_id VARCHAR(32) not null primary key,
object_value LONGVARBINARY
);

Very simple table: object_id which a primary key and objet_value which is a binary representation of the object. And there is beauty of different flavours of databases (not!). We want to store the binary representation in a blob, and for HSQLDB there is no data type as blob. We have to use LONGVARBINARY. We have to be careful when switching to some other vendor and amend the create script. I will skip the part with details how to create schema etc. Contact me if you want more details on that.

Let’s create a datasource for HSQLDB in memory now using org.apache.commons.dbcp.BasicDataSource:

    String driver = "org.hsqldb.jdbcDriver";
    String url = "jdbc:hsqldb:mem:testdb";
    String username = "sa";
    String password = "";

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driver);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);

The datasource will be used by Spring JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate) which we will happily use for interactions with db. You can reuse this object:

JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

Let’s have a look how to store a serialised object in database (add necessary validation/exception handling):

public void add(T state) {
    Object[] params = new Object[] {state.getId(), new SqlLobValue(serialise(state))};
    int[] types = new int[] { Types.VARCHAR, Types.BLOB };
    jdbcTemplate.update("insert into State (object_id, object_value) values(?, ?)", params, types);
}

Retrieving of that object is slightly more complex. We have to create a callback RowMapper (org.springframework.jdbc.core.RowMapper) first which will map each row from database to our object. This object can be as well reused:

private RowMapper rowMapper = new RowMapper() {
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        byte[] bytes = rs.getBytes("object_value");
        return deserialise(bytes) ;
    }
};

And finally the code for retrieving and deserialising the object from database (validation and exception handling removed):

public T get(String id) {
    Object[] params = new Object[] {id};
    int[] types = new int[] {Types.VARCHAR};
    List results = jdbcTemplate.query("select object_id, object_value from State where object_id=?", params, types, rowMapper);
    if (results.size() == 0)
        return null;
    return (T)results.get(0);
}

Popularity: 44% [?]

Comments

Mylyn and Implementors

I migrated last week to Eclipse 3.3.0 and during usual routine of installing plugins (must to have: JBossIDE, SpringIDE, Subclipse) I decided to try two plugins I haven’t been using yet. First is a subproject from Eclipse Tools project called Implementors. It fills a gap in standard Eclipse source code navigation which doesn’t really well support working with interfaces. With Implementors plugin it is possible to jump to implementation of an interface and to an interface of implementation. Sounds unimpressive yeah? But it is really useful plugin and I could call it a “Plugin of the Month in Category Simple but Cool”. If I had that category. So, whenever you edit a class which has dependencies defined as interfaces just hit Alt-F3 on a method from an interface to go to implementation. If you have more than one implementation you will have a choice. Ctrl-Alt-F3 will take you to interface. Thanks Andy for introducing that plugin!

The second plugin I wanted to write about is Mylyn formerly known as Mylar. I have heard about this plugin long time ago, talked about it with Tomaz many times but never actually tried it out. My bad and now I regret that. Because I found Mylyn just awesome. In couple of words Mylyn is a task focused ui for Eclipse which filters all unneeded information noise, leaving you only relevant information. It monitors your activity when working on a particular task and creates a context of that task which makes it is very easy to switch between tasks. No more navigating, searching, scrolling again. Mylyn integrates with repositories like JIRA, Bugzilla or Trac. There is also option of using local task repository.

As I use Scrum Works for task management I would like to use that repository with Mylyn but couldn’t find a connector for that one. Anyone solved that problem?

Popularity: 37% [?]

Comments

Ant task generating random number

I created an ant task lately which generates random number and I thought that it might be useful for someone. The ant task will accept three parameters:

  • min
  • max
  • name of ant property to assign value to

Our class will extend org.apache.tools.ant.Task and the only thing which we have to do is really to override the execute method and to add setters for parameters. We can return value to ant environment using org.apache.tools.ant.Project which will give us a way of setting a property using its name. The code is as follows:


package your.package;

import java.util.Random;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class RandomTask extends Task {
    private String min;
    private String max;
    private String property;
    private Random random = new Random(System.currentTimeMillis());

    @Override
    public void execute() throws BuildException {
        if (min == null || min.equals(""))
            throw new BuildException("Min property not specified");

        if (max == null || max.equals(""))
            throw new BuildException("Max property not specified");

        int minInt = Integer.parseInt(min);
        int maxInt = Integer.parseInt(max);

        if (minInt > maxInt)
            throw new BuildException("Min is bigger than max");

        int randomInt = calculateRandom(minInt, maxInt);

        getProject().setNewProperty(property, String.valueOf(randomInt));
    }

    protected int calculateRandom(int minInt, int maxInt) {
        return minInt + random.nextInt(maxInt - minInt + 1);
    }

    public void setMin(String min) {
        this.min = min;
    }

    public void setMax(String max) {
        this.max = max;
    }

    public void setProperty(String property) {
        this.property = property;
    }
}

After compiling and building a jar we should copy that jat to ANT_HOME/lib and define the new task in our build.xml, lets call it “random”:

    <taskdef name="random" classname="your.package.RandomTask"></taskdef>

Let’s try if it works. We will generate a rundom integer from the range <4;10>, assign to a property and print it to console:

    <target name="testRandom">
        <random min="4" max="10" property="randomValue"></random>
        <echo>Random:${randomValue}</echo>
    </target>

Popularity: 42% [?]

Comments

GWT - first impression

I had a look at Google Web Toolkit today and just wanted to share my first impression. Me, as a person who really hates JavaScript, the idea of writing web pages in Java and later compiling this to html pages flavoured with JavaScript to get AJAX style of websites, sounds excellent. I had a quick look at API and examples and it looks pretty straitforward. So, if we want to create static site with cool AJAX interface it is easy. But what about more realistic use cases? I will have to investigate how easy would be using GWT with some MVC framework and of couse some back-end. Spring MVC, Spring, Hibernate + GWT? It would be a killer! But lets back to reality and my first bad impression from actually using GWT. It has different versions for Windows XP/2000 and Linux (GTK+ 2.2.1+). As a result we have different binaries and probably we cannot easily develop on different platforms. That’s one thing. Another is lack of integration with Ant. This bothers me even more.

But I will give it a chance. I created a project on Google Code Hosting for my sandbox for GWT.

I always wanted to created something what looks cool though*.

* the true is that I prefer server-side and even GWT cannot change this!

Popularity: 23% [?]

Comments

Groovy - write less code

I recently came across Scott Hickey’s article in IBM DeveloperWorks comparing writing code in Java and Groovy. Simply code written in Groovy has simplified syntax comparing to what we are used to. Hence is less noisy, easier to read and understand. Isn’t it great to focus on solving a problem than on typing curly brackets all the time? What I just realized is that we are boxed by our behaviour, we are get actually used to type the brackets, for loops with index, iterator. Type, type, type… And we think that’s the way software development should look like. Thank’s to good IDEs helping us to generate that noise we are not frustrated completely yet. In Java 5 we have got already some goodies like simplified loops, autoboxing, generics. That is a good change I believe. And I don’t care that generics can have bad influence on performance (see an article on TSS). Coming back to Groovy I will try to have a look how can I incorporate it to my current development behaviour. I’ve read an article about using Groovy for unit testing of java code. Sounds promising to me.

Popularity: 23% [?]

Comments

Close
E-mail It