niceideas.ch
Technological Thoughts by Jerome Kehrli

Bytecode manipulation with Javassist for fun and profit part II: Generating toString and getter/setters using bytecode manipulation

by Jerome Kehrli


Posted on Monday Apr 24, 2017 at 10:38PM in Java


Following my first article on Bytecode manipulation with Javassist presented there: Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code, I am here presenting another example of Bytecode manipulation with Javassist: generating toString method as well as property getters and setters with Javassist.

While the former example was oriented towards understanding how Javassist and bytecode manipulation comes in help with implementing IoC concerns, such as what is done by the spring framework of the pico IoC container, this new example is oriented towards generating boilerplate code, in a similar way to what Project Lombok is doing.
As a matter of fact, generating boilerplate code is another very sound use case for bytecode manipulation.

Boilerplate code refers to portions of code that have to be included or written in the same way in many places with little or no alteration.
The term is often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal job. And Java is unfortunately a clear winner in this regards.
Avoiding boilerplate code is one of the main reasons (but by far not the only one of course !) why developers are moving away from Java in favor of other JVM languages such as Scala.

In addition, as a reminder, a sound understanding of the Java Bytecode and the way to manipulate it are strong prerequisites to software analytics tools, mocking libraries, profilers, etc. Bytecode manipulation is a key possibility in this regards, thanks to the JVM and the fact that bytecode is interpreted.
Traditionally, bytecode manipulation libraries suffer from complicated approaches and techniques. Javassist, however, proposes a natural, simple and efficient approach bringing bytecode manipulation possibilities to everyone.

So in this second example about Javassist we'll see how to implement typical Lombok features using Javassist, in a few dozen lines of code.

Read More

Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code

by Jerome Kehrli


Posted on Monday Feb 13, 2017 at 09:30PM in Java


Java bytecode is the form of instructions that the JVM executes.
A Java programmer, normally, does not need to be aware of how Java bytecode works.

Understanding the bytecode, however, is essential to the areas of tooling and program analysis, where the applications can modify the bytecode to adjust the behavior according to the application's domain. Profilers, mocking tools, AOP, ORM frameworks, IoC Containers, boilerplate code generators, etc. require to understand Java bytecode thoroughly and come up with means of manipulating it at runtime.
Each and every of these advanced features of what is nowadays standard approaches when programming with Java require a sound understanding of the Java bytecode, not to mention completely new languages running on the JVM such as Scala or Clojure.

Bytecode manipulation is not easy though ... except with Javassist.
Of all the libraries and tools providing advanced bytecode manipulation features, Javassist is the easiest to use and the quickest to master. It takes a few minutes to every initiated Java developer to understand and be able to use Javassist efficiently. And mastering bytecode manipulation, opens a whole new world of approaches and possibilities.

The goal of this article is to present Javassist in the light of a concrete use case: the implementation in a little more than 300 lines of code of a lightweight, simple but cute IoC Container: SCIF - Simple and Cute IoC Framework.

Read More

Java - Create enum instances dynamically

by Jerome Kehrli


Posted on Saturday Nov 13, 2010 at 09:08PM in Java


I remember the introduction of the brand new enum type in Java 5 (1.5) was a very exciting announce. However, when I finally switched from 1.4 to 1.5 and actually tried Java's flavoured enum types, I was a bit disappointed.

Before that, I was using Josh Bloch's "Typesafe enum" pattern (effective java) for quite a long time and I didn't really see what was so much better with the new Java native enum construction. Ok, fine, there was the ability to use enum instances in switch - case statements which seemed fine, but what else ?

Besides, what I used to find great with the "typesafe enum" pattern is that it could be tricked and changed the way I wanted, for instance to be able to dynamically (at runtime) add enum instances to a specific typesafe enum class. I found it very disappointing not to be able to do the very same thing easily with the native Java enum construction.

And now you might wonder "Why the hell could one ever need to dynamically add enum values ?!?". You do, right ? Well, let's imagine this scenario:

You have a specific column in a DB table which contains various codes as values. There are more than hundred different codes actually in use in this column. Related to this, you have a business logic which performs different operations on the rows coming from this table, the actual kind of operation applied on the row depends on the value of this code. So there are chance you end up with a lot of if - elseif statements checking the actual value of the code.
I myself am allergic to using string comparison in conditions so I want to be able to map the values from this column to an enum type in Java. This way I can compare enum values instead of strings in my conditions and reduce my dependency on the format of the string value.

Now when there are more than a hundred different possible codes in the DB I really don't have any intent to define them all manually in my enum type. I want to define only the few I am actually using the Java code and let the system add the other ones dynamically, at runtime, when it (the ORM system or whatever I am using for reading the DB rows) encounters a new value from the DB.

Hence my need for dynamically added enum values.

So recently I faced this need once again and took a few hours to build a little solution which enables one to dynamically add values to a Java enum type. The solution is the following :

Read More

Java rocks !

by Jerome Kehrli


Posted on Wednesday Nov 03, 2010 at 08:40AM in Java


I've been facing an interesting problem with string manipulation in Java lately at work. The requirement was the following :

We have a field on some screen where the user can type in a comment. The comment can have any length the user wants, absolutely any. Should he want to type in a comment of a million characters, he should be able to do so.

Now the right way to store this comment in a database is using a CLOB, a BLOB or a LONGVARCHAR or whatever feature the database natively provides to do so. Unfortunately that's not the way it was designed. Due to legacy integration needs, all these advance DB types are prohibited within our application. So the way we have to store the comment consists of using several rows with a single comment field of a maximum length of 500 characters. That means the long comment has to be split in several sub-strings of 500 characters and each of them is stored in a separate row in the DB table. The table has a counter as part of the primary key which is incremented for each new row belonging to the same comment. This way we can easily spot every row part of the same comment.

Now another problem we have is that under DB2 a field defined as VARCHAR(500) can contain 500 bytes max even though the strings are encoded in UTF-8 in the database. That means we might not be able to store 500 characters if the string contains one or more 2 bytes UTF-8 characters. Working in a french environment, this happens a lot.
So we had to write a little algorithm taking care of the splitting of the string in 500 bytes sub-strings.

The very first version of our algorithm was quite stupid and ended up in splitting the string in a quite naive way: we converted the string to a byte array following an UTF-8 encoding and split the byte array instead of the string. Then each of the 500 bytes arrays was converted back to a string before being inserted in the database.
Happily, we figured out quite soon that this doesn't work as it ends up quite often splitting the string right in the middle of a 2 bytes character. The byte arrays being then converted back to strings, the split 2 bytes character was corrupted and could not be corrected any more.

Before writing as smarter version of the algorithm which would manually test the byte length of the character right at the position of the split, we took a leap backward and wondered : "Can it be that Java doesn't offer natively a simple way to do just that ?"

And the answer is yes of course.

Read More

CommunityBoard : a sample multi-module maven / glassfish / eclipse Java EE project.

by Jerome Kehrli


Posted on Sunday Oct 24, 2010 at 10:29PM in Java


CommunityBoard is a sample multi-module maven / glassfish / eclipse Java EE project.

It realizes is a little Forum / Note publishing application. Its main purpose it to act as an introducing laboratory to Java EE programming. As such the functionalities are rather limited. Yet it covers the most fundamental aspects or issues with Java EE programing in the way it show hows to :

  • write entity beans with bi-directional relationship;
  • use these Entity beans in EJBs (Stateless session beans);
  • use other EJBs in EJBs;
  • use EJBs in a servlet or a JSP located in a WAR (i.e. no processing of the @EJB annotation);
  • build a multi-module Java EE maven project with jars, wars, ears;
  • how to write JSPs with the JSTL (Ok I am not very proud of these JSPs yet they do the job) and
  • deploy a multi-module ear within Glassfish and use a container defined datasource

Read More

DWR : A paradigm shift in web development

by Jerome Kehrli


Posted on Thursday Apr 29, 2010 at 04:57PM in Java


I discovered DWR recently and I believe it to be an amazing breakthrough in the world of HTTP client-server comunications.

First what is DWR ?

DWR stands for Direct Web Remoting - Easy Ajax for Java.

DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.

Quoting the official website :

"DWR is a RPC library which makes it easy to call Java functions from JavaScript and to call JavaScript functions from Java (a.k.a Reverse Ajax)."
Read this : http://directwebremoting.org/dwr/introduction/index.html.

Read More

hibernate's [not-found="ignore"] is buggy as hell

by Jerome Kehrli


Posted on Wednesday Jan 27, 2010 at 07:52PM in Java


I'm working on a java application which makes an extensive usage of hibernate's relation mapping system. The later offers several ways to define association mapping. We mostly use many-to-one relation declarations. The problem comes from the database. It's a pre-relational, pre-transactional, legacy database running on a prehistorical IBM zSeries host. The data on this database is very often dumb or corrupted. The lack of a proper referential integrity support and the foolish design make us end up quite often following non-existent relations.

Happily, hibernate provides a semantic which allow the application not to bother when a relation is missing, just as the legacy app does. This semantic is the not-found="ignore" parameter on the relation definition.

However, the usage of this semantic resumes to open very wide the doors to oblivion.

Read More