jorisvdbJoris Van den Bogaert

Popular articles by jorisvdb

All articles by jorisvdb

 

Hibernate 4 Integrator pattern and Spring’s DI

Enabling @Autowired in Hibernate entities. Create an EventListener that kicks in after a Hibernate LOAD event.  Using AutowireCapableBeanFactory to wire @Autowire’d dependencies. (SpringLocator is a simple custom class that is ApplicationContextAware in order to have static access to the ApplicationContext) Register your new listener in Hibernate’s EventListenerRegistry. To register your SPI (see service loader), create a (text)
Continue reading...  

Converting an InputStream to a String

Main.java:
Continue reading...  

Using covariant return types in JDK 1.5

An argument or return type in an overridden method that is made more specialized is called to be covariant. Allowing covariant return types in Java has been in Sun’s bugparade for a long time (http://bugs.sun.com/bugdatabase/view_bug.do? bug_id=4144488. Now finally, JDK 1.5 supports it. The protected clone() method of the Object class can be overridden, made public
Continue reading...  

Loading properties from an XML file in JDK 1.5

ReadProps.java:
Continue reading...  

Storing properties into an XML file in JDK 1.5

StoreProps.java: Generates the file config.xml:
Continue reading...  

Comparing StringBuiler with StringBuffer

StringBuilder is a replacement for the thread-safe StringBuffer class. It works much faster as it has no synchronized methods. So, if you are doing lots of String operations in a single thread, you will gain a lot of performance when using this class. Here’s a comparison. Main.java: outputs:
Continue reading...  

Using the tool jconsole in JDK1.5

The JMX compliant tool jconsole comes with JDK1.5. It allows to manage the VM, check the memory usage of the different memory managers, monitor the thread usage, see how many classes are loaded, etc. The simplest way to use jconsole is to start up the Java application a JMX agent: Then, specify the process ID
Continue reading...  

Get started with CopyOnWriteArrayList

The CopyOnWriteArrayList class allows to quickly (no synchronization required) iterate over a list while other threads have the possibility to insert elements to it meanwhile. The following example shows that you simply can’t do that with an ordinary ArrayList: outputs, in one run: The new java.util.concurrent.CopyOnWriteArrayList solves this problem, but comes at a cost. The
Continue reading...  

Using a ConcurrentLinkedQueue

A ConcurrentLinkedQueue is an unbounded non-blocking FIFO queue. Although there is already a thread-safe implementation of a linked list: the ConcurrentLinkedQueue offers better concurrent performance and scalability. Main.java:
Continue reading...  

Using an ArrayBlockingQueue

This example provides an example of all the significant methods in ArrayBlockingQueue. Main.java: outputs:
Continue reading...  

Get started with an ArrayBlockingQueue

An ArrayBlockingQueue is a FIFO blocking queue with an array used by the underlying implementation. At construction, you specify the maximum space used by the queue. Attempting to put more elements in the queue than is allowed by its capacity constraint will result in a blocking wait. Similarly, attempting to take an element from an
Continue reading...  

Catching exceptions in threads in JDK1.5

Sometimes, a thread may abruptly terminate, for example due to a NullPointerException. In large applications, a bug due to a thread that vanished just like that may be very hard to spot. In JDK1.5, there is a new inner interface Thread.UncaughtExceptionHandler that will make it a lot easier to detect exceptions. When a thread is
Continue reading...  

Publishing a Websphere MQ ConnectionFactory in an LDAP

The following working code sample allows you to create a QueueConnectionFactory (MQQueueConnectionFactory) and register it as an administered object in an LDAP tree. I used iPlanet Directory Server 5.0 to test it out. RegisterWebsphereMQ.java: LDAPObject.java: Sample run:
Continue reading...  

Using the ClassFileTransformer in JDK 1.5

The package java.lang.instrument allows you to modify class classfiles as they are loaded. On the command line, you register your own implementation of the ClassFileTransformer and this will be called by the VM every time a class is loaded. On this page, you’ll find a working example of a ClassFileTransformer that will add a log
Continue reading...  

Get Started with AspectJ

Download AspectJ Run java -jar aspectj-[version].jar and perform the installation. Add the bin directory of to your path to make it easier to run the AsjpectJ compiler ajc. Add aspectjrt.jar to your classpath. The goal of this example is to extend this simple class with logging functionality. Every time a method is called or exited,
Continue reading...  

Get the current process ID in JDK 1.5

The following example is platform-dependent and was only tested with Sun’s JVM 1.5.0 on Windows XP. It first shows you how to get it using the standard management API’s and then using some reflection tricks and the undocumented sun.* classes. Main.java (Using RuntimeMBean): Main.java (Using reflection): Note that I’ve written a DLL / so before
Continue reading...  

Decompiling JDK 1.5 classes

jad expects class file versions (major.minor) to be 45.3 or 46.0. Sources compiled with 1.5 have the file version 48.0. The following error message is displayed when trying to decompile a 1.5 .class file: To be able to use JAD, we can simply change the class file version of a 1.5 compiled class into 46.
Continue reading...  

Get a verbose output of the classes loaded by the VM

With JDK 1.5 java.lang.management package: Main.java:outputs:
Continue reading...  

Get the number of classes loaded by the VM

With JDK 1.5 java.lang.management package: Main.java:outputs:
Continue reading...  

How long has the VM been running

In JDK 1.5, use the RuntimeMBean management class in the java.lang.management package. Main.java: outputs:
Continue reading...  

Getting the state of a thread (running, blocked, etc)

This becomes very simple with the new java.lang.management package in JDK 1.5. The following example starts up a Task thread and a Monitor Thread. The Monitor thread prints out the state of the Task thread every half a second. All possible thread states are documented in the API docs. Main.java: outputs:
Continue reading...  

Getting the parameters passed to the VM at runtime

With the new java.lang.management package in JDK 1.5, this becomes very simple now. Main.java: For example, run it with outputs:
Continue reading...  

Detecting a deadlock with ThreadMBean in JDK 1.5

This example shows how to use the ThreadMBean class in JDK 1.5 to detect a deadlock. ThreadMBean is a management class (package java.lang.management) that provides functionality to query the thread system of the JVM. The example creates three threads A, B and C which end up in a deadly embrace: A waits for a lock
Continue reading...  

Creating a JComboBox that doesn’t close when I click one of its JCheckBox items

Main.java: JComboCheckBox.java:
Continue reading...  

Putting a JCheckbox in a JComboBox

Here’s a working example: Main.java: JComboCheckBox.java:
Continue reading...  

Converting a ByteArrayInputStream to a ReadableByteChannel

Main.java:
Continue reading...  

Using the classes CacheRequest and CacheResponse

JDK 1.5 provides a framework into which an caching implementation can be plugged. A standard protocol handler can use the ResponseCache class to get documents from the cache. For example, if the flag useCaches is set on a URLConnection (true by default), an attempt is made to fetch the content from the cache, implementation specified
Continue reading...  

Using a ProxySelector

Here’s a working example that says everything. MyProxySelector is automatically contacted when URLConnection is about to make a connection. Main.java:
Continue reading...  

Setting the a connect timeout on an URLConnection

JDK1.5 allows you to set connect and read timeouts on URLConnection (HttpURLConnection, etc.). Here is an example: Main.java:
Continue reading...  

Pinging a host in JDK1.5

JDK1.5 provides the functionality to test the reachability of a host. Before JDK 1.5, you had to implement this yourself (for example by sending UDP packets to the echo port (7) of the target machine). Actually, the strategy of the implementation of isReachable is to try to use ICMP if it is available, or else
Continue reading...  

Changes to java.text.MessageFormat in JDK1.5

Before the new 1.5 feature that allows for a variable number of arguments in methods, the class MessageFormat could only be using an array of Objects as shown in the following example Main.java: With 1.5, there is a new overloaded format method declared as follows: This allows you to rewrite the above code as follows:
Continue reading...  

Creating a method with a variable number of arguments

JDK1.5 allows methods to have a variable number of arguments. The syntax is to specify the type, three dots and the argument name. The variable number of arguments must be the last argument to the method. Other (normal) arguments may precede the variable argument list. Only one variable argument list may be specified. Main.java:
Continue reading...  

Typesafe enum in JDK 1.5

Earlier version of the JDK did not have true enumerated types. Many developers have implemented workarounds for this, a popular one described in Effective Java, item 21. Starting from 1.5, enumerated types have been integrated with the language, allowing developers to write more robust programs without having to write dull boilerplate code, which is automatically
Continue reading...  

Static imports in JDK 1.5

Static imports have been introduced in 1.5 to remove the burden of having to qualify constant names. With static imports, you import the static members from a class rather than the classes from a package. For example, suppose we have a class Einstein that calculates the formula E=m*c*c. comesusEinstein.java: Here is an example of how
Continue reading...  

NullPointerException when auto-unboxing

This can happen when you cast a null to a primitive type. It can be hard to spot these types of errors: Main.java: The reason for the NullPointerException is much clearer if you look at the equivalent:
Continue reading...  

What is autoboxing?

Autoboxing is the automatic conversion between primitive types and reference types. It eliminates the need to explicitely create wrapper objects for primitive types. Main.java: This means that you don’t need to create wrapper objects anymore to use primitives in collection classes. Main.java:
Continue reading...  

Pretty-printing an XML in Java

Imagine you want to format the following xml in a human-friendly format: test.xml: You can do this using the XSLT transformer package. Working code sample: Main.java: outputs:
Continue reading...  

Getting the current memory usage of a Process in windows with Java

You will have to use JNI for this. Using the following code, we will create a DLL that provides the method getProcessWorkingSet which will return the current working set size, and the method getProcessVMSize which will return the current pagefile usage. The working set size is the memory size as shown in the Windows Task
Continue reading...  

Getting the process ID on Windows from Java

You will have to use JNI for this. Using the following code, I’ll create a DLL that provides the method getPid which will return the current process ID. Pid.java: Compile and run javah on it to create the pid.h header file: It generates the C header file Pid.h: The C code that allows to get
Continue reading...  

Creating a JFormattedTextField that only accepts dates

Main.java and JFormattedDateTextField:
Continue reading...  

Creating a JList with icons and text

Main.java:
Continue reading...  

Have two JTrees vertically aligned in a JScrollPane

Main.java:
Continue reading...  

Changing the color of the lines between JTable header cells

Main.java:
Continue reading...  

Embedding a JTextArea and ImageIcon in a JTable cell

JTextAreaTableExample.java: Image used:
Continue reading...  

Changing the color of one JTable cell

Main.java:
Continue reading...  

Get a private key from a keystore

This example extracts a private key from a keystore and prints it out in PEM format. Main.java:
Continue reading...  

Aligning the text in a JComboBox to the right

Main.java:
Continue reading...  

Writing a custom FocusTraversalPolicy

[JDK 1.4+] Extend from FocusTraversalPolicy and implement the abstract methods! Main.java:
Continue reading...  

Changing the traversal keys that control focus

In 1.4, you can use the following method. Main.java:
Continue reading...  

Using an SWT Sash

Sash is the Swing equivalent of a JSplitPane. It is a widget that can be dragged to resize two areas in a GUI. Here’s an example of a Sash in a JFace application. Category.java: Link.java: CategoryTreeContentProvider.java: CategoryTreeLabelProvider.java: Main.java:
Continue reading...