The Holy Java

Building the right thing, building it right, fast

Archive for April, 2010

File-based User Authentication under WebSphere 6

Posted by Jakub Holý on April 12, 2010

File-based User Authentication under WebSphere 6

When developing a web application for the WebSphere Application Server you sometimes need to enable security because the application expects HttpServletRequest.getUserPrincipal() to be non-null. While in the production environment you will likely configure WAS to delegate the authentication to an LDAP server, during development you would likely prefer to use a simpler method that doesn’t depend on an external service (and thus functions even when offline) and doesn’t force you to use some real confidential credentials.

The solution is to use the sample custom file-based user registry, which is shipped with WebSphere 6.x and which enables you to define your groups and users in two files. The steps to configure it are quite simple.

1. Open the WAS administration console

2. Configure the custom user registry under Security – Global security – Custom:
2.a Define basic properties:

2.b Define location of the user and group files:

3. Enable security and select the configured custom user registry:

4. ? Add self to the allowed console users (I’m not sure whether this is necessary):

5. Create the users and groups files defined in the step 2.b:
jh_user.props:
# jh_user.props file (user name, password, unique user id, group id, user label)
jholy@at.ibm.com:password:123:567:Jakub Holy

jh_group.props:
# jh_group.props file (group name, unique group id, comma-separated member list,
# a label)

AutomatedBridge_admins:567:jholy@at.ibm.com:AB Admins

6. Restart WAS

7. Log in to the admin console with the credentials you’ve configured (id jholy@at.ibm.com above).

Posted in WebSphere | Tagged: , | Comments Off

Most interesting links of March

Posted by Jakub Holý on April 11, 2010

I’ve decided to publish links to the most interesting blogs, articles and pages that I’ve stubled upon in a particular month. Enjoy the first dose! (In no particular order.)

I recommend the post 43 Essential Controls for Web Applications,which presents – with screenshots and short descriptions – the most used and useful javascript/ajax widgets for web pages, from the basic ones like auto-complete/suggestions and sliders through a calendar for less known yet very cool ones like sparklines. Read it to learn what’s hot and you shouldn’t miss in your application! (Warning: The number of widgets on a page is inversely proportional to its quality.)

Code Bubbles – a new IDE UI paradigm: An extremely interesting proposal of a completely different UI for IDEs based on related pieces of code instead of files.

How to Make Developers Write Performance Tests – why should we, as developers, be keen about writting performance tests for our code (e.g. because "Everyone wants to be a hero" and "It will come back anyway").

Twitter on Scala – why some parts of Twitter are being ported to Scala – shortcomings of JRuby (more excatly its virtual machine), advantages of Scala (high level, static, JVM), lessons learned.

Reasons why to switch from Log4j to Logback, a (not so) new logging framework by a Log4j father. Really compelling.

 10 Lessons Learned from Usability Testing – why doing usability testing can be cheap and afordable for anybody and whay you need. My experience is that users are too often frogotten and UT should certainly be done much more often – and this post argues that it’s indeed possible.

A discussion of various Source Code Management systems (scroll down) and which one to choose for Eclipse, including CVS, SVN, Git, Mercurial and Jazz SCM, with their advantages and disadvantages, really enlightening. For the busy yet curious ones, the winner was Git (though that doesn’t mean that for a different project you wouldn’t pick another one).

What’s new in Maven 3 – an interview with J. van Zyl. Among others: even better IDE integration, better dependency handling, mixins (since 3.1) for reusable pieces of configuration, a set of core plugins of guaranteed quality. Looking forward!

Posted in General, Top links of month | Comments Off

Enforcing a common log format with AspectJ

Posted by Jakub Holý on April 8, 2010

Enforcing a common log format with AspectJ

Andy Wilson has recently blogged about the need for uniformly formatted log messages containing all the necessary information to make log parsing easier and mentioned an extensive refactoring he did on a project to achieve this. One of the readers mentioned that he could save the effort of manually modifying the log statements and use AOP to add the formatting automatically. Well, here is the solution.

Before we dive into the code, I should mention that I do not include a user name in the log, because it is not clear how to obtain it. If it was e.g. stored in a ThreadLocal variable, it would be easy to access it and include it in the log statement. Another thing is that if we could limit ourselves to Log4j instead of commons-logging, we could achieve the same with less effort using a custom formatter and perhaps Log4j’s Nested Diagnostic Context.

The code is basically quite simple – we have one AspectJ aspect using the annotation-style, which intercepts calls to commons-logging’s info(Object) and info(Object, Throwable) and re-formatts the message before handing it over to the actual logger.

package net.jakubholy.example.aoplog.aspect;

import org.apache.commons.logging.*;
import org.aspectj.lang.*;
import org.aspectj.lang.annotation.*;

@Aspect
public class LogFormattingAspect {

    private static final Log LOG = LogFactory.getLog(LogFormattingAspect.class);

    @Around("call(public void org.apache.commons.logging.Log.info(Object)) && args(msg) && !within(LogFormattingAspect)")
    public Object formatMessageLog(
            final Object msg
            , final ProceedingJoinPoint invocation
            , final JoinPoint.EnclosingStaticPart callerContext) throws Throwable {
        return formatLogAndProceed(msg, null, invocation, callerContext);
    }

    @Around("call(public void org.apache.commons.logging.Log.info(Object, Throwable)) && args(msg, exception) && !within(LogFormattingAspect)")
    public Object formatMessageLog(
            final Object msg
            , final Throwable exception
            , final ProceedingJoinPoint invocation
            , final JoinPoint.EnclosingStaticPart callerContext) throws Throwable {
        return formatLogAndProceed(msg, exception, invocation, callerContext);
    }

    private Object formatLogAndProceed(final Object msg, final Throwable exception
            , final ProceedingJoinPoint invocation
            , final JoinPoint.EnclosingStaticPart callerContext
            ) throws Throwable {

        final String callingMethod = callerContext.getSignature().getName();

        LOG.info("Log.info has been called from the method " + callingMethod +
                " with message=" + msg + ", exception=" + exception);

        final Object[] arguments = invocation.getArgs();
        arguments[0] = formatMessage(callingMethod, msg);

        return invocation.proceed(arguments);
    }

    private String formatMessage(final String callingMethod,
            final Object originalMessage) {
        return "APPMSG: " + callingMethod + ": " + originalMessage;
    }
}

If you are new to AspectJ then you need to understand that

  • the methods annotated with @Around are invoked whenever Log.info(..) is called
  • AspectJ provides values for the interceptor method’s arguments including runtime and static information about the intercepted call, as represented by the *JoinPoint* instances
  • those methods extract some information about the actual call and its arguments from the invocation context provided by AspectJ
  • finally, they invoke the original intercepted method by calling proceed()

The part args(msg, exception) may seem tricky – it binds the intercepted method arguments to those of the intercepting method (i.e. final Object msg, final Throwable exception). This isn’t necessary since we may access them via invocation.getArgs() as we anyway do but it’s more convenient.

To apply the aspect to you code you need to weave them into it. You can choose either Load-Time Weaving (LTW), which uses Java 5’s -javaagent option and instruments classes as they’re loaded by the JVM based on configuration in an aop.xml file and which provides rather nice debugging output (when enabled), or Bytecode Weaving (also called build- or compile-time weaving), which injects the aspects into .class files using the command-line compiler/weaver ajc or AspectJ’s Ant tasks. During development I prefer LTW, which is more flexible, but for use in a production environment it’s better to weave the bytecode because LTW consumes more memory (due to custom classloaders) and CPU.

Try it out

The easiest way to try this out is to use Maven 2:

  1. Download the source code archive aop-log-formatter-0.0.1-sources.jar
  2. Unpack them somewhere
  3. In the directory with the sources (namely pom.xml), execute
    mvn -Pexecute-from-sources compile exec:exec
  4. This will download some maven/project dependencies (a lot, if you don’t use maven often, sorry), compile the sources and execute the application while printing its log to the console

If you do not want to use maven:

  1. Download the source code archive aop-log-formatter-0.0.1-sources.jar
  2. Download also the compiled binaries aop-log-formatter-0.0.1.jar
  3. Download the dependencies, as recorded in the project’s pom.xml (commons-logging, AspectJ weaver)
  4. Execute it with Load-Time Weaving (java 5 or higher required; it’s assumed that all dependencies are in the same folder):
    java -cp aop-log-formatter-0.0.1.jar:commons-logging-1.1.1.jar -javaagent:aspectjweaver-1.6.8.jar net.jakubholy.example.aoplog.ExampleLoggingClass

The output will be long, because the aop.xml included in the jar enables the most detailed AspetJ logging but in the end you should see something like:

[INFO] [INFO] LogFormattingAspect - Log.info has been called from the method main with message=A message w/o an exception., exception=null
[INFO] [INFO] ExampleLoggingClass - APPMSG: main: A message w/o an exception.
[INFO] [INFO] LogFormattingAspect - Log.info has been called from the method main with message=Another message accompanied by an exception., exception=java.lang.RuntimeException: I'm the exception!
[INFO] [INFO] ExampleLoggingClass - APPMSG: main: Another message accompanied by an exception. java.lang.RuntimeException: I'm the exception!

You can see that the ExampleLoggingClass log message has been decorated with the prefix APPMSG and the method name (main).

Posted in Languages | Tagged: , , | Comments Off