Adding manpower to a late software project makes it later
Filed under: scala — Tags: , , — Michael Glauche @ 11:01

What is scala ?

Scala is a relativ new compiled programming language that takes a lot of ideas from python, ruby and others. From the scala homepage:

Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. Code sizes are typically reduced by a factor of two to three when compared to an equivalent Java application.

Why do we need another programming language ?

I mean, there are a wealth of different languages that created quite a buzz recently like ruby, python, c#. Why do you need scala ? For one, scala is a compliled language unlike ruby and python. The scala compliler generates java-bytecode that is compatible with the java jre.
This looks like a small feature but it is really one of the most interesting features of scala:

Seamles Integration in java

You can directly use java objects in scala and vice versa. Scala directly compiles to java .class files. You can deploy scala applications to your J2EE container. Which means if you are a java shop you can use your existing tools and servers to deploy scala applications. No need for a new application server, JBoss, websphere and others will work fine.

This is a very important point for larger companies. Changes in these companies can only happen graduately, so you can keep your existing knowledge and workers. The server administrators still only need to maintain the same application server they’ve been knowing for years. You even can continue to use your own libraries you’ve developed in java over the years. These points are very important if you want to make a successfull migration towards scala.

Why use Scala over Java ?

If scala is fully compatible with java, why use it ? Why learn a new language when the old one seems good enough ?

  • Scala corrects many of javas mistakes
    • Everything is an Object in scala
    • Type inference -> only need to declare the type on the right side of the assignment (i.e. var dummy= Map[String,Int]() )
    • True Mixins
    • Scala is both, a object oriented and a functional programming language
  • Fresh start
    • Clean Language, nothing feels like an addon (like generics for example)
    • much more compact, like no need for getters and setters
    • No semicolons

Hello World in scala

Enough of the theory. How does a typical scala program look like ?

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, world!")
  }
}

Filed under: java — Tags: , , , — Michael Glauche @ 22:21

A bit of History

At the time the now discontinued log4j was the most commonly used logging framework for java sun decided to implement JSR 47: java.util.logging. There were a lot of discussion, but it seems not been fruitful. java.util.logging was introduced in JDK 1.4 and hasn’t changed much despite its obvious shortcomings.

The Good, The Bad and the Ugly

One of jul best selling points is the integration to J2SE 1.4. Why need another logging framework when there is one bundled with the SDK ? Unfortunately it seems the guys responsible for jul did create a similar mess like java.util.Date.

Whats good in JUL ?

  • Integration
    Everything is included in the SDK
  • Easy to get started
    Logger logger = Logger.getLogger(“de.glauche.test”);
    logger.info(“my info message”);

Whats not so good in JUL ?

  • Strange log levels: SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST
    The first seems ok, but FINE, FINER, FINEST ?
  • logger.info, logger.severe etc. only accept Strings
    This is a really bad case of inconsistent API, to log an exception for example you need to use logger.log(Level.SEVERE,”Some String”, exception); Why are there no shortcuts like logger.severe(“Some String”,exception); ?
  • no parameterized logging, which can be a severe performance penality

What is Parameterized Logging ? (and why should i care for it ?)

Imagine you have lots of debug logging statements in your code:

   logger.debug("Number " + i + " has the Value:  " + entry[i]);

Here, every time the code is reached the String is build first, which can be quite time-consuming if there are many variables which need to be converted to string and concatinated. This can affect the performance of the program quite a bit, especially if it is in some inner loop.
One common solution is to wrap the debug statement with an if-clause:

if(logger.getLevel() >= Level.DEBUG) {
   logger.debug("Number " + i + " has the Value:  " + entry[i]);
}

Needless to say this leads to quite messy code, is unreadable and inflexible. Fortunately there is a very underused Class in java called MessageFormat, where you can use placeholders for parameters.
So, when using something like MesageFormat, you can use: format(String pattern, Object[] arguments) for a logger. The logger could decide if the log entry needs to be constructed or not. In worst case the overhead is just a function call.

SLF4j does exactly this. It uses parameterized strings as logmessages as default. So, the above log entry in slf4j would look like this:

   logger.debug("Number {} has the Value: {}",i,entry[i]);

Unfortunately SLF4j does not use javas overloading mechanism, so you can only add two Objects, or you need to create an array of them:

   logger.debug("Value {} was inserted between {} and {}.", new Object[] {newVal, below, above});

and the Ugly ?

So, whats really ugly in JUL ?

The configuration

The default configuration resides in the JDK/lib directory (!), but can be overwritten by a command line parameter. This is very bad in the J2EE enviroment where one JDK instance can contain many independed applications.
The configuration file is rather nice and straitforward, it is easy to replace parts, or set up log levels.

but wait, there is an API to configure JUL !

There is a limited API to configure the log settings, yes. But it has some drawbacks. First, it is not so easy to replace certain parts. For example when you just want to get rid of the ugly two line default output and have all info in one clean line. With the config file it is easy, but with the API you need to implement your own Handler first.
Another big drawback is that if you configure the root logger (“”), it is still classloader dependent. If some parts of your (J2EE for example) application use different classloader mechanism, the default configuration will be used.

so how does SLF4j help ?

SLF4j is, as the name implies a simple facade for logging. It does not really log anything for itself. For the real logging you can use the build in simplelogger, JUL (if you just want some nicer API for example), logback and even Log4J. On the other hand you can also redirect log-entries from other system into SLF4j, for example Java commons Logging (JCL).
This is especailly nice, as many different libraries still use JCL or log4j.
SLF4j configures the output by the logging implementation in the classpath. Switching the real logging mechanism is as easy as replacing a jar file in your classpath.
SLF4j is fast, one does not need to write if () wrappers around the debug statments, and it has nice parameterized logging.
On the bad side, you usually need at least two additional jars as dependencies in your project, the facade and the actual logger.

There’s also a short introduction how to automaticly construct logging fields in classes with the help of guice.

Filed under: Testing,java — Tags: , , — Michael Glauche @ 16:04

Using Selenium for web-gui tests is really nice. You can record your workflow with the excelent selenium plugin for firefox and use them to write your own test.
The only problem seems to be Drag&Drop. The senenium runner has some drag&drop methods, but they don’t seem to work in any way. But selenium offeres mouse controll where you can simulate mouse clicks not only at an absolute position, but rather relative to a dom object. So, if your dragable <div> element has ID1 and the dropzone has ID2 you could write the following in your testrunner:

   selenium.mouseDownAt("//div[@id='ID1']","10,10");
   selenium.mouseMoveAt("//div[@id='ID2']","10,10");
   selenium.mouseOver("//div[@id='ID2']");
   selenium.mouseUpAt("//div[@id='ID2']","10,10");

The important command for this is probably the mouseOver one, without that the richfaces d&d component for JSF would not work.

Filed under: guice,java — Tags: , , , — Michael Glauche @ 17:05

After getting angry at the java.util.logger once again i was thinking how to replace it with the SLF4J logger. Although Guice provides a very nice internal binding to java.util.logger, slf4j does offer a much nicer syntax.
The devil is in the detail, as allways … if you want your logger to be initialized with the current class you can’t simply inject the logger … But .. there is a nice tutorial on the guice wiki about injecting a log4j logger. SLF4J works the same.

First you need a new annotiation, like InjectLogger:

import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectLogger {
}

next is a TypeListener, that listenes to org.slf4j.Logger classes with the annotiation InjectLogger:

import java.lang.reflect.Field;

import org.slf4j.Logger;

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

public class Slf4jTypeListener implements TypeListener {

	public <I> void hear(TypeLiteral<I> aTypeLiteral, TypeEncounter<I> aTypeEncounter) {

		for (Field field : aTypeLiteral.getRawType().getDeclaredFields()) {
			if (field.getType() == Logger.class
	            && field.isAnnotationPresent(InjectLogger.class)) {
	        	aTypeEncounter.register(new Slf4jMembersInjector<I>(field));
	        }
	      }
	}
}

Finally, you need the Slf4jMembersInjector, which does the actual injection:

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.MembersInjector;

public class Slf4jMembersInjector<T>  implements MembersInjector<T> {
	private final Field field;
    private final Logger logger;

    Slf4jMembersInjector(Field aField) {
    	field = aField;
    	logger = LoggerFactory.getLogger(field.getDeclaringClass());
    	field.setAccessible(true);
    }

	public void injectMembers(T anArg0) {
		try {
			field.set(anArg0, logger);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}

Now you just need to bind your TypeListener inside your module class:

   bindListener(Matchers.any(), new Slf4jTypeListener());

The actual usage is simple, but instead of @Inject we need to use @InjectLogger :

    @InjectLogger Logger logger;

Older Posts »

16 queries. 0.506 seconds. Powered by WordPress

Home