Showing posts with label java. Show all posts
Showing posts with label java. Show all posts


convertToUTF - NOT!

Fell over yet another ingenious‎ way of doing absolutely nothing today:

private String convertToUTF(String input) {
    final Charset UTF_8 = Charset.forName("UTF-8");
    return new String(input.getBytes(UTF_8),UTF_8);


Conditional assignment in Java and BPEL


if (i > 1000) i = 0;

BPEL (in JDeveloper with Oracle 11g SOA suite):

Drag in a "Switch".
Doubleclick the "case" side of the switch.
Select "Variable" for left hand side.
Click your way through a tree structure to find the variable 'i', and select that.
Click the operator drop-down.
Select >.
Select "Expression" for right hand side.
Click on button to open the expression builder.
Type 1000.
Close the expression builder.
Drag in an assignment icon and drop it in the case side of the switch.
Double click it.
Click the plus button and select copy from the menu that appears.
Select "Expression" for the "from" side.
Click on button to open the expression builder.
Type 0 (zero).
Close the expression builder.
Select "Variable" for the "to" side.
Click your way through a tree structure to find the variable 'i', and select that.
Back to the BEPL diagram and click the "otherwise" side of the switch.
Press delete.
Click OK to confirm that you want to delete the "otherwise" side of the switch.

Now you've got a diagram with an icon showing that there is a condition and another one showing that if the condition is satisfied an assignment will be performed.
To see exactly what the condition is you will have to double click the switch icon.
To see what gets assigned to what you will have to double click the assignment icon.

They made all those tools for us so that we could be more agile!
Now, that's progress!

The above description of the procedure for adding a conditional assignment in a BPEL diagram i JDeveloper may not be 100% correct. It's close, but I probably forgot a few steps, and I don't have the time or the hardware to install all that crap and check.
You probably get the idea anyway.


JAOO, Århus 2009 - Impressions from day one

This is my 3rd visit to JAOO, and as always it's a great experience.

Opening Keynote

The opening keynote was titled "Scaling Up Agility: The Architected Agile Approach". Sounded interesting. Unfortunately it wasn't. Presenting slides with too complex diagrams and turning your back on the audience while reading from your slides will kill any presentation, no matter how interesting the subject.

Fortunately it soon got much better.

Breaking Barriers with HTML5 WebSockets

Jonas Jacoby demonstrated how the new WebSocket protocol will eliminate a lot of the limitations imposed on us by http's request-response model.
You still initiate the communication by issuing a http request, but once the connection is established you can upgrade it to the ws: protocol, and have full-duplex communication. After that you can do pretty much the same as with a normal TCP socket and let applications running in a browser work much more like today's "fat clients".

An excellent presentation on technologies which I'm sure very soon will change the way we make web-applications.

Extreme Java Productivity with Spring Roo and Spring 3.0

Rod Johnson gave an very impressive demonstration of Roo's capabilities. I won't try to describe what Roo is - I'm sure you'll find far better descriptions of that than I could ever hope to write on SpringSource's websites and in other blogs, so I'll just say, that I was very impressed by the way they used AspectJ to separate the code generated by Roo from hand-written code, and how they used that to get those stupid getter and setter methods out of the source code we need to maintain by hand.
Certainly something I'll try out very soon.



Operations and Monitoring with Spring

Eberhard Wolff would very much like to sell "enterprise editions" of Spring and Spring DM Server. If I were in Operations I'd probably have found this more interesting. The DM Server / OSGi demo was nice though.

Making use of Patterns

I went here because the presentation was done by Martin Fowler and, as always, it was interesting and very well presented. Don't really know what to pass on, though. If I have to single something out, the biggest take-away for me probably was the idea that trying to pass on knowledge to someone not yet proficient in the field in question just won't work. Sounds like I should go home and read the GOF patterns book again (I first read it when I just had started learning Java, and didn't "get" half of it).

xUnit Test Patterns - Refactoring Test Code to Improve ROI

Gerard Meszaros gave some very concrete examples on how to refactor test code to make it more readable and maintainable. His "xUnit Test Patterns" book is definitely on my must-read-soon list.

Energy-efficient Cloud Computing

Very impressive hardware those Google guys have. And yes, we definitely need to do something about the energy consumption of computers and data centers.


Bridging java.util.logging to SLF4J

This little code snippet will pass everything logged using java.util.logging (JUL) to SLF4J AND remove JUL's default Handler, so to avoid having everything logged twice:

// Jersey uses java.util.logging - bridge to slf4

The reason I'm posting this is that it took me a little longer than expected to write it. I've never really used JUL, but I've recently been working on a small JAX-RS application using the Jersey framework.

Jersey uses JUL as it's logging framework. The rest of the application uses SLF4J and Logback, so I wanted everything logged using JUL redirected to SLF4J. For that purpose the SLF4J project provides jul-to-slf4j.jar and the class SLF4JBridgeHandler as described here.

According to the above mentioned site all that's required is to call SLF4JBridgeHandler.install(), and that also works very well, except it just installs an extra Handler on JUL's root logger - it dosn't remove the handler which is there by default. That also makes sense, but since I've never used JUL it took me a while to figure out how to make it stop logging anything. I've seen a lot of people asking how to "replace" JUL logging with SLF4J, and answers was far fewer, so I thought I'd share my solution.


Truely false

Just started working on a codebase where one of my predecessors consistently uses the following construct when testing if a Boolean variable is false:

if ((someBooleanVariable.toString().equals("false")) == true) { }

Beautiful, isn't it?


Test Logging

How do you test (in a unittest) that a method writes the log statements you expect it to write?

Apparantly being able to do that is not a very common requirement - at least Google wasn't it's normal helpful self when I asked it how to, and frankly I never needed it myself. Before now, that is.

AbstractInterruptibleChannel.close() throws one of those pesky checked IOExceptions, which you always have to write a lot of verbose and error-prone code to "handle", and which you really can't do anything about anyway.

Code working with two IO channels normally looks something like this:

AbstractInterruptibleChannel c1, c2;
try {
    // Open and use channels c1 and c2
} catch (IOException ioe) {
    // Display or log errormessage or whatever
} finally {
    try {
    } catch (IOException e) {
        logger.error("Failed to close a channel.", e);
    try {
    } catch (IOException e) {
        logger.error("Failed to close a channel.", e);

I would much rather have something like this:

AbstractInterruptibleChannel c1, c2;
try {
    // Open and use channels c1 and c2
} catch (IOException ioe) {
    // Display or log errormessage or whatever
} finally {
    closeChannels(c1, c2);

Therefore I wrote a small utility method to close IO Channels and encapsulate the try/catch hassle normally associated with that:

public static void closeChannels(AbstractInterruptibleChannel... channels) {
    for (AbstractInterruptibleChannel channel : channels) {
        if (channel == null) continue;
        try {
        } catch (Exception e) {
            logger.error("Failed to close channel.", e);

It suppresses errors - if an Exception occurs it will be logged, but otherwise silently ignored. And now we are finally getting to what I really wanted to write about. I wanted to verify that the method acually logs an error message when it fails to close a channel.
That sounds like something which should be very easy to do. It's not hard, but not exactly obvious either. As mentioned earlier I first tried Google without result. The SLF4J. and Logback manuals didn't have any examples exactly matching my needs either, but based on the Logback documentation I did manage to write a Filter to capture whatever was logged during executon of the test. It took quite a bit of code though, and after Ceki Gülcü (the author of Logback) pointed out that there are applicaple examples in the Logback code I dropped the Filter idea and used Logbacks ListAppender instead:

public void testCloseChannels() { 
    // Capture log entries from FileUtil 
    Logger logger = (Logger) LoggerFactory.getLogger(FileUtil.class); 
    ListAppender<LoggingEvent> listAppender = new ListAppender<LoggingEvent>(); 
    // Close a mix of normal, broken and completely missing channels 
    closeChannelse(null, new UnclosableChannelStub(), null, new ChannelStub(), new ChannelStub()); 
    // Restore normal logging 
    // Perform checks 
    assertEquals("Exactly 1 failure should have been logged.", 1, listAppender.list.size()); 

Now the test works exactly as I wanted.

For a while I have wanted to take a closer look at Hamcrest and, to avoid doing any real work, I decided to further refine the test to use Hamcrest matchers to perform the same test.

The following is an example of a Matcher which matches LoggingEvents with a particular message text.

public class LoggingEventMatchers {

     * Does the LoggingEvent have a particular message?
    public static TypeSafeMatcher&lt;LoggingEvent&gt; message(String message) {
        return new MessageMatcher(message);

     * Matcher to check if an LoggingEvent has a particular message.
     * @author Claus Nielsen
    private static class MessageMatcher extends TypeSafeMatcher&lt;LoggingEvent&gt; {

        private final String theMessage;

         * Constructor.
         * @param theMessage
         *            The predicate evaluates to true for LoggingEvents
         *            with this message.
        private MessageMatcher(String theMessage) {
            this.theMessage = theMessage;

        public boolean matchesSafely(LoggingEvent event) {
            return theMessage.equals(event.getMessage());

        public void describeTo(Description description) {
            description.appendText("the message ").appendValue(theMessage);



In addition to writing a set of matchers similar to the one above, I moved the logger configuration code to a seperate class called LogCapturingTestTemplate, and now the test itself is as simple as this:

 public void testErrorLoggedForUnclosableChannels() {
 // Capture logging events while closing come Channels.
 final CapturedLoggingEvents loggingEvents = new LogCapturingTestTemplate(FileUtil.class) {
  protected void monitorThis() {
   closeChannels(null, c1, new UnclosableChannelStub(), null, c2);
  assertThat(loggingEvents.getEvents(), hasItem(
   allOf(level(ERROR), message(FileUtil.FAILED_TO_CLOSE_CHANNEL))

This test is actually far more specific. Where the previous version only checked that exactly one entry was logged during the call to closeChannels, this test checks that an ERROR message with a specific message is logged.
Full source code for both the test and the Hamcrest-style matchers is part of the clanie-core project (version 0.0.1). The source is available in the Git repository, and both binary builds, source, javadoc and project documentation can be found in the Maven repository.