Tag Archives: Java

Writing numbers in French

Numbers in French are difficult.
As a native French speaker, I did not realized that at once. But when talking to foreign friends who were trying to learn French, I figured out how illogical and tricky is our way to numerate things.
Why do we say “four twenty eleven” for 91? Why 70 is said “sixty ten”? It can look quite weird…
This video from Numberphile (what a great website) is self-explanatory about how confusing French numbers are. It seems our weird way to count comes from ancient time when we used base 20.
Note that the way to count in Belgium or Switzerland seems to be far more logical since they get rid of the 70s and 90s with “septante” and “nonante” (vs “soixante-dix”=sixty-ten and “quatre-vingt-dix”=four-twenty-ten in France).

Even French are confused, especially when we need to write them down. It does not happen much, but when I do for writing checks, it is sometimes a bit painful. I often forget the rules and always go to this Wikipedia article. Should I put an “s”, should I put a dash…? I always need a refresh…

That is why I did this small application on Google app engine to help you writing French numbers. It is available in English and in French.

Screenshot French number webapp

Update from June 9 2013
Following cyChop valid comment, I updated the webapp with a radio button to enable switching between the traditional and modern spelling of numbers (following the reform of 1990).

Java source code generation and Maven

Imagine you are working on a project where you use some Java code generated from a tool.
For the moment, you generate the code and integrate it yourself to the project:

Original Maven project structure

How would you automate this code generation step in your Maven build?

1. Create a separate Maven project where you will package the result of the code generation.

We package the result of the code generation in a separate JAR. Therefore, we need a different project structure.

New Maven project structure

We create a parent project with two child Maven modules. One with the original code, the other where the generated code will be located.
The parent POM looks like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.clempinch</groupId>
		<artifactId>myproject</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<groupId>com.clempinch</groupId>
	<artifactId>sample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>com.clempinch</groupId>
			<artifactId>generated-code</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
	</dependencies>

</project>

2. Automate the code generation in Maven.

If a Maven plugin is not already provided to generate the source code, then you can probably use the Exec Maven plugin to do the job.

Here is the pom.xml of the code generation project (we assume you generate the code via a Java application – hence the use the exec:java plugin).

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.clempinch</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.clempinch</groupId>
  <artifactId>generated-code</artifactId>

  <dependencies>
    <!-- For generating source code -->
    <dependency>
      <groupId>com.clempinch</groupId>
      <artifactId>some-generation-jar</artifactId>
      <version>1.0.0</version>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>generateCode</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>java</goal>
            </goals>
            <configuration>
              <mainClass>com.clempinch.generation.MainClass</mainClass>
              <classpathScope>runtime</classpathScope>
              <sourceRoot>${project.build.directory}/generated-sources/main/java</sourceRoot>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>addtoSourceFolder</id>
            <goals>
              <goal>add-source</goal>
            </goals>
            <phase>process-sources</phase>
            <configuration>
              <sources>
                <source>${project.build.directory}/generated-sources/generation_place</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

3. Add the dependency to your initial project.

The pom.xml of the initial project needs to add a dependency to the generated-code JAR package:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>	
	<parent>
		<groupId>com.clempinch</groupId>
		<artifactId>myproject</artifactId>
		<version>0.0.1-SNAPSHOT</version>
        </parent>
	<groupId>com.clempinch</groupId>
	<artifactId>sample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>com.clempinch</groupId>
			<artifactId>generated-code</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
	</dependencies>
</project>

4. Build the project from the parent POM.

mvn clean install

Now everything should be done automatically: the code generation and the build of the project.

Monitor an Active MQ queue with Hermes JMS

Hermes JMS is a great tool to monitor the activities on your JMS broker. Especially, it is quite useful to see what are the messages transiting in the queues and topics (you can also record them and replay them, which is pretty cool).

HermesJMS

However, when you are monitoring the messages transiting in a queue, Hermes JMS only takes a snapshot of what is pending, i.e. not yet delivered. That means that if you have a consumer plugged on this queue, you will barely see any message since they are immediately consumed as they are sent (most of the cases at least)… It is a problem when you want to see the flow of messages, record it and replay it.

Mirrored queues

I am using Apache ActiveMQ as a JMS Broker. My solution for this broker is to use mirrored queues.

This feature of ActiveMQ enables to route messages from one destination to another without any external interventions. So if we route messages from the queue we want to monitor to a topic, messages coming to the queue will be automatically sent to the topic. If we subscribe to this topic with Hermes JMS, then we are able to see all messages which have been sent to the original queue. Indeed, topics are easier to monitor with Hermes JMS. We see there the continuous flow of messages as they arrive.

How is this done in ActiveMQ? I requires very few configuration in your activemq.xml.

First you need to configure the broker instance as enabling virtual topics:

<broker brokerName="localhost" 
   useVirtualTopics="true" 
   dataDirectory="${activemq.data}" ... >

Then, if we assume the queue to monitor is called test.queue and if you want to route the messages to be routes to a topic called test.queue.mirror, you have to create a destination interceptor:

<destinationInterceptors>
	<virtualDestinationInterceptor>
		<virtualDestinations>
			<compositeQueue name="test.queue" forwardOnly="false">
				<forwardTo>
					<topic physicalName="test.queue.mirror"/>
				</forwardTo>
			</compositeQueue>
		</virtualDestinations>
	</virtualDestinationInterceptor>		
</destinationInterceptors>

Be sure the queue and topic destinations exists as well:

<amq:destinations>
	<amq:queue physicalName="test.queue"></amq:queue>
	<amq:topic physicalName="test.queue.mirror"></amq:topic>
</amq:destinations>

Back to Hermes JMS

Here we are! Restart ActiveMQ and you will notice that when you send a message to queue.test, this message is also sent to test.queue.mirror.

Start to Hermes JMS and connect to the topic: you see the flow of messages sent to the queue arriving.

Hermes JMS with mirrored queue

Transient and final instance variables in Java

In Java, transient and final are two important keywords and it is legal to put them as modifier of instance variables.

But how does it behave when it comes to object serialization? Since it is transient, we can guess such variable are not serialized and therefore, when the object is deserialized, they are initialized to their default values, like for regular non final instance variable.

But in fact, it depends! See the code below:

public class Diplodocus implements Serializable {

	private final transient String s1 = "test";
	private final transient String s2;
	private final transient String s3 = new String("hello");
	private final transient String s4 = s1 + s1 + 1;
	private final transient int i1 = 7;
	private final transient int i2 = 7 * 3;
	private final transient int i3 = Integer.MIN_VALUE;
	private final transient int[] a1 = {1,2,3};

	public Diplodocus() {
		s2 = "s2";
	}

	public static void main(String[] args) {

		File f = new File("diplo");
		try {
			FileOutputStream fos = new FileOutputStream(f);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(new Diplodocus());
			oos.flush();
			oos.close();

			FileInputStream fis = new FileInputStream(f);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Diplodocus diplo = (Diplodocus) ois.readObject();
			ois.close();
			System.out.println("s1 = "+diplo.s1);
			System.out.println("s2 = "+diplo.s2);
			System.out.println("s3 = "+diplo.s3);
			System.out.println("s4 = "+diplo.s4);
			System.out.println("i1 = "+diplo.i1);
			System.out.println("i2 = "+diplo.i2);
			System.out.println("i3 = "+diplo.i3);
			System.out.println("a1 = "+diplo.a1);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

What we expect here is that the instance variables after the deserialization will be equals to the default initialization values : null for objects like Strings and 0 for the integers.

But, in fact the code has the following output:

s1 = test
s2 = null
s3 = null
s4 = testtest1
i1 = 7
i2 = 21
i3 = -2147483648
a1 = null

What happened?

During deserialization, the constructor of the object is not called. This is a special object instantiation process handled by the JVM. For regular non-final transient instance variable, they are assigned with their default values.

But what happened for final variables? There is a little trick.

If the final variable is blank, meaning that it is first initialized in the object constructor(s) (like on line 13), the deserialization will put the default value. That is why s2 = null.

On the contrary, for a final variable explicitly initialized, the value is reaffected, but only if this initializations is done in a certain manner, in fact, only if the initialization is done with what the Java specification calls a compile-time constant expression (§15.28).

Constant expressions are the ones you are allowed to use in the case labels of a switch statement. A constant expression is an expression, which can be resolved at compile-time with no ambiguity: somehow, it gives the guarantee that the resulting value will never change during the execution.

In our case, these are considered constant expressions and that is why the values are reaffected to the final variables (even if they are transient).

  • literals (like a String on line 3, or an integer on line 7)
  • + operation between literals and reference to a constant final variables (like on line 6)
  • * operation between integers (like on line 8)
  • reference to constants (like on line 9)

There are other types of constant expressions (e.g. cast operation to a primitive or a String). I suggest you to have a look at the specifications for more details1.

However, object instantiations are not considered to be constant expressions and that is why these are assigned to the default values (like on lines 5 and 10).

Conclusion

Be careful when you use transient final instance variable! You may expect to get attributes initialized or not according to the context. And the worst part is that, since they are final you cannot modify them directly afterwards.

  1. or simply check this: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28 []

Java EE startup and shutdown callbacks

Hurray, this is the first post of this blog!
As a first subject, I would like to discuss a problem where it was quite hard to find a solution on the Web. Let me share this with you.

The problem

Given a standard Java EE 5 application (with EJBs, Servlets…), how to develop some code which will be started when the application startup/shutdown?

In other words, how to execute something when you start or stop your application?
Indeed, when you start the server you may need to initialize some stuff like initializing your cache, and when you stop the server, wouldn’t it be great to do some data cleanup?

In my case, our application was a pure back-end application (only EJBs) which embedded a remote service interface and we wanted to register it (resp. unregister it) to a service locator at the application startup (resp. shutdown).

Unsatisfactory solutions

Application server and framework tricks

In fact, most of the application servers already come with their own solutions. In Weblogic, for example, we have the notion of startup/shutdown classes (but admittedly, I have not tested it).

But in our case, we had to deploy on a JBoss 6 server! And moreover, wouldn’t it be preferable to have a pure Java EE way, so that it could be deployed anywhere with minimal configuration?

If we were using some Java development framework like Seam, there are also some tricks, like using an observer on the org.jboss.seam.postInitializatio event like this:

@Name("initializer")
public class Initializer {

   @Observer("org.jboss.seam.postInitialization")
   public void init() {
      // startup code here
   }
}

But once again, this is a specific solution and if you are not using Seam then you should find something else (besides, I haven’t looked for the implementation of the shutdown callback with Seam).

Static blocks in EJBs

So what if we just put static block in EJBs and let’s just hope that when the EJB class will be loaded, the static code will be executed?
Well, this is a bad idea. By definition, you have no control on how the EJBs are loaded by the application server. It may even not be called before the first invocation of the EJB.
So this is obviously not a good solution.

EJB 3.1

It is true that we are speaking only about Java EE 5 in this post, but I just want to mention that in Java EE 6 with EJB 3.1, we can use the pretty code below:

@Singleton
@Startup
public class StartupShutdownBean {

	@PostConstruct
	private void startup() {
		// your startup code here
	}

	@PreDestroy
	private void shutdown() {
		// your shutdown code here
	}

}

The solutions

So, the only solution found was to use the servlet API. But the good news is that you have two choices:

Using Servlet init and destroy methods

The idea here is to have the startup and shutdown code in the init() and destroy() methods of a servlet embedded in your application. So if you do not have any servlet in your application, you will have to create one like this with these methods.

public class InitServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
		// startup code here
	}

	@Override
	public void destroy() {
		// shutdown code here
	}
}

You should guarantee that this servlet is loaded on start-up, (and potentially before the other servlets). This is guaranteed by the following statement in the web.xml.

<servlet>
        <servlet-name>Init</servlet-name>
        <servlet-class>com.clempinch.InitServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>

The number between the load-on-startup tag indicates the order in which servlet are loaded on startup (the lowest are first).
This solution is ok admittedly, especially if you have already servlets in your application. But what if you have none? Isn’t it a bit costly to create a servlet listening to coming requests just for two methods to call during the application life?
For that reason, I prefer therefore the second solution, which is…

Using Servlet context listeners (the one I prefer)

The other solution is still in the servlet API, and it is to use a servlet context listener.
This comes as a Java interface ServletContextListener. Classes implementing this interface will be loaded before (resp. after) the instantiation (resp. the destruction) of all servlets, therefore, it is a good place to put your application startup/shutdown code.
Here is how it is done:

public class InitContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent ce) {
        // startup code here
    }

    @Override
    public void contextDestroyed(ServletContextEvent ce) {
        // shutdown code here
    }
}

You will also need to declare the context listener in the web.xml with the following statement:

<listener>
	<listener-class>com.clempinch.InitContextListener</listener-class>
</listener>

That’s all…

Conclusion

So, to sum up, it seems that to have some startup/shutdown code in your application there is no other clean solution than to use the servlet API, either with the init()/destroy() methods or with a servlet context listener.

The other best/long-term/cleanest solution is of course to migrate to Java EE 6, but not everyone is ready to do it, right?