Archive

Archive for April, 2010

frankel.ch goes mobile!

April 30th, 2010 Nicolas Frankel No comments

If you do browse this site with your computer, chances are you didn’t notice anything. On the contrary, if you browse it with a mobile device (an iPhone for example), it’s kind like a new user experience!

In fact, in almost 1 minute, I made this site adapted to mobile browsing. How? Just used my friend Google who found WPTouch, a WordPress plugin which in fact behaves like a configurable theme, but only on mobiles.

WPTouch features are impressive (and free). Most notably, supported user-agents include: Android, BlackBerry9500, BlackBerry9530, CUPCAKE, dream, iPhone, iPod, incognito, webOS, webmate.

If you own a WordPress blog and want to offer to users the best user experience, I would recommend using this plugin.

Categories: Technical Tags: ,

DRY and skinny war

April 21st, 2010 Nicolas Frankel 1 comment

In this article, I will show you how the DRY principle can be applied when using the skinny war configuration of the maven-war-plugin.

While packaging an EAR, it is sometimes suitable that all libraries of the different WARs be contained not in their respective WEB-INF/lib folders but at the EAR level so they are usable by all WARs. Some organizations even enforce this rule so that this is not merely desiarable but mandatory.

Using Maven, nothing could be simpler. The maven-war-plugin documents such a use case and calls it skinny war. Briefly, you have two actions to take:

  • you have to configure every WAR POM so that the artifact will not include any library like so:
    <project>
      ...
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
              <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
              <archive>
                <manifest>
                  <addClasspath>true</addClasspath>
                  <classpathPrefix>lib/</classpathPrefix>
                </manifest>
              </archive>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
  • you have to add every dependency of all you WARs in the EAR

The last action is the real nuisance since you have to do it manually. In the course of the project, a desynchronization is sure to happen as you add/remove dependencies from the WAR(s) and forget to repeat the action on the EAR. The DRY principle should be applied here, the problem lies in how to realize it.

There’s an easy solution to this problem: if a POM could regroup all my WAR dependencies, I would only have to draw a dependency from the WAR to it, and another from the EAR to it and it would fulfill my DRY requirement. Let’s do it!

The pomlib itself

Like I said before, the pomlib is just a project whose packaging is POM and that happens to have dependencies. To be simple, our only dependency will be Log4J 1.2.12 (so as not have transitive dependency, let’s keep it simple).

The POM will be:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>ch.frankel.blog.pomlib</groupId>
    <artifactId>pomlib-parent</artifactId>
    <version>1.0.0</version>
  </parent>
  <artifactId>pomlib-lib</artifactId>
  <packaging>pom</packaging>
  <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>
  </dependencies>
</project>

Like for any other project module, I put the versions in the parent POM.

The EAR and the WAR

Both should now add a dependency to the pomlib. For brevity, only the EAR POM is displayed, the WAR POM can be found in the sources if the need be.

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>ch.frankel.blog.pomlib</groupId>
    <artifactId>pomlib-parent</artifactId>
    <version>1.0.0</version>
  </parent>
  <artifactId>pomlib-ear</artifactId>
  <packaging>ear</packaging>
  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>pomlib-lib</artifactId>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>pomlib-war</artifactId>
      <type>war</type>
    </dependency>
  </dependencies>
</project>

Likewise, versions are put in the parent POM. Notice the import scope on the pomlib dependency, it’s the only magic.

Using mvn install from this point on will put the log4j dependency at the root of the generated EAR artifact and not in the WEB-INF/lib folder of the WAR.

Conclusion

Now that all dependencies are described in the pomlib, should you need to add/remove a dependency, it’s the only place you’ll need to modify. With just a little configuration, you’ve streamlined you delivery process and saved yourself from a huge amount of stress in the future.

By the way, if you use a simple Servlet container (like Tomcat or Jetty) as your development application server, you could even put the skinny war configuration in a profile. Maven will produce “fat” WARs by default, at development time. At delivery time, just activate the profile and here’s your EAR product, bundling skinny WARs.

You can find the source of this article in Maven/Eclipse format here.

Categories: Java Tags: ,

GMail HTML signature

April 18th, 2010 Nicolas Frankel 8 comments

This time, I won’t ramble about some point of details that only a handful of specialists have thought about. This time, this article has the potential to touch ten thousand of normal people across the world (I only exaggerate a little of course). This time, I will blog about GMail signatures.

Ever wanted to have a nicely crafted signature in your emails? Outlook has the feature. I guess other fat softwares have the feature. Guess what? GMail doesn’t. If you don’t believe it (neither did I at first), just try to create a signature that displays something completely extravagant, like a mailto hyperlink for example. You will find out you can’t since the text area only accepts plain text. HTML you could type won’t be treated as such but encoded to plain text. Strangely enough, the mail itself accepts HTML so I really don’t understand the reason behind this limitation.

Anyway, the first solution is to have somewhere a file where you can type your nicely crafted signature and paste it into every mail. But software is my trade, and it didn’t feel too satisfying…

Since I couldn’t possibly be the first (or the only one) to have this problem, I went on the hunt on the Internet and found Wisestamp. First, let’s say it is available for Firefox and Chrome, so if you don’t use one of them, tough luck.

Wisestamp has the following features:

  • HTML signature creation
  • two settings to alternate between business and personal signatures
  • GMail integration: a button appears in your GMail inteface
  • other web-based mails are supported: Yahoo, Hotmail and AOL
  • widgets for social networks
  • inclusion of a hyperlink for the latest link of a RSS feed

Compared to most similar tools, Wisestamp doesn’t just paste the signature below your mail. If you choose another signature (or even if you update it), it really will replace the  previous signature. It won’t add the newer one below the old one.

I only got one complaint: I would like more than two signatures so I can, for example, use different languages for my business signature. Then, the product is free so I consider myself lucky!

I can’t resist the pleasure of showing you my own signature:

PS: notice the Wisestamp integration.

If you have the same needs as me, I can only recommend the product.

Categories: Technical Tags: ,

Debugging Hibernate generated SQL

April 13th, 2010 Nicolas Frankel 1 comment

In this article, I will explain how to debug Hibernate’s generated SQL so that unexpected query results be traced faster either to a faulty dataset or a bug in the query.

There’s no need to present Hibernate anymore. Yet, for those who lived in a cave for the past years, let’s say that Hibernate is one of the two ORM frameworks (the second one being TopLink) that dramatically ease database access in Java.

One of Hibernate’s main goal is to lessen the amount of SQL you write, to the point that in many cases, you won’t even write one line. However, chances are that one day, Hibernate’s fetching mechanism won’t get you the result you expected and the problems will begin in earnest. From that point and before further investigation, you should determine which is true:

  • either the initial dataset is wrong
  • or the generated query is
  • or both if you’re really unlucky

Being able to quickly diagnose the real cause will gain you much time. In order to do this, the greatest step will be viewing the generated SQL: if you can execute it in the right query tool, you could then compare pure SQL results to Hibernate’s results and assert the true cause. There are two solutions for viewing the SQL.

Show SQL

The first solution is the simplest one. It is part of Hibernate’s configuration and is heavily documented. Just add the following line to your hibernate.cfg.xml file:

<hibernate-configuration>
  <session-factory>
...
    <property name="hibernate.show_sql">true</property>
  </session-factory>
</hibernate-configuration>

The previous snippet will likely show something like this in the log:
select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_

Not very readable but enough to copy/paste in your favourite query tool.

The main drawback of this is that if the query has parameters, they will display as ? and won’t show their values, like in the following output:

select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_ where (this_.PER_D_BIRTH_DATE=? and this_.PER_T_FIRST_NAME=? and this_.PER_T_LAST_NAME=?)

If they’re are too many parameters, you’re in for a world of pain and replacing each parameter with its value will take too much time.

Yet, IMHO, this simple configuration should be enabled in all environments (save production), since it can easily be turned off.

Proxy driver

The second solution is more intrusive and involves a third party product but is way more powerful. It consists of putting a proxy driver between JDBC and the real driver so that all generated SQL will be logged. It is compatible with all ORM solutions that rely on the JDBC/driver architecture.

P6Spy is a driver that does just that. Despite its age (the last release dates from 2003), it is not obsolete and server our purpose just fine. It consists of the proxy driver itself and a properties configuration file (spy.properties), that both should be present on the classpath.

In order to leverage P6Spy feature, the only thing you have to do is to tell Hibernate to use a specific driver:

<hibernate-configuration>
  <session-factory>
    <!-- Only this line changes -->
    <property name="connection.driver_class">com.p6spy.engine.spy.P6SpyDriver</property>
...
 </session-factory>
</hibernate-configuration>

This is a minimal spy.properties:

module.log=com.p6spy.engine.logging.P6LogFactory
realdriver=org.hsqldb.jdbcDriver
autoflush=true
excludecategories=debug,info,batch,result
appender=com.p6spy.engine.logging.appender.StdoutLogger

Notice the realdriver parameter so that P6Spy knows where to redirect the calls.

With just these, the above output becomes:
1270906515233|3|0|statement|select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_ where (this_.PER_D_BIRTH_DATE=? and this_.PER_T_FIRST_NAME=? and this_.PER_T_LAST_NAME=?)|select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_ where (this_.PER_D_BIRTH_DATE=’2010-04-10′ and this_.PER_T_FIRST_NAME=’Johnny’ and this_.PER_T_LAST_NAME=’Be Good’)

Of course, the configuration can go further. For example, P6Spy knows how to redirect the logs to a file, or to Log4J (it currently misses a SLF4J adapter but anyone could code one  easily).

If you need to use P6Spy in an application server, the configuration should be done on the application server itself, at the datasource level. In that case, every single use of this datasource will be traced, be it from Hibernate, TopLink, iBatis or plain old JDBC.

In Tomcat, for example, put spy.properties in common/classes and update the datasource configuration to use P6Spy driver.

The source code for this article can be found here.

To go further:

  • P6Spy official site
  • Log4jdbc, a Google Code contender that aims to offer the same features
Categories: Java Tags: , ,

Vaadin Spring integration

April 6th, 2010 Nicolas Frankel 9 comments

I lately became interested in Vaadin, another web framework but where everything is done on the server side: no need for developers to learn HTML, CSS nor JavaScript. Since Vaadin adress my remarks about web applications being to expensive because of a constant need of well-rounded developers, I dug a little deeper: it will probably be the subject of another post.

Anyway, i became a little disappointed when I wanted to use my favourite Dependency Injection framework, namely Spring, in Vaadin. After a little Google research, I found the Vaadin Wiki and more precisely the page talking about Vaadin Spring Integration. It exposes two ways to integrate Spring in Vaadin.

The first one uses the Helper “pattern”, a class with static method that has access to the Spring application context. IMHO, those Helper classes should be forgotten now we have DI since they completely defeat its purpose. If you need to explicitly call the Helper static method in order to get the bean, where’s the Inversion of Control?

The second solution uses Spring proprietary annotation @Autowired in order to use DI. Since IoC is all about decoupling, I’m vehemently opposed to coupling my code to the Spring framework.

Since neither option seemed viable to me, let me present you the one I imagined: it is very simple and consists of subclassing the Vaadin’s AbstractApplicationServlet and using it instead of the classical ApplicationServlet.

public class SpringVaadinServlet extends AbstractApplicationServlet {

  /** Class serial version unique identifier. */
  private static final long serialVersionUID = 1L;

  private Class clazz;

  @Override
  public void init(ServletConfig config) throws ServletException {

    super.init(config);

    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(
      config.getServletContext());

    Application application = (Application) wac.getBean("application", Application.class);

    clazz = application.getClass();
 }

  /**
  * Gets the application from the Spring context.
  *
  * @return The Spring bean named 'application'
  */
  @Override
  protected Application getNewApplication(HttpServletRequest request)
    throws ServletException {

    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(
      request.getSession().getServletContext());

    return (Application) wac.getBean("application", Application.class);
  }

  /**
  * @see com.vaadin.terminal.gwt.server.AbstractApplicationServlet#getApplicationClass()
  */
  @Override
  protected Class getApplicationClass()
  throws ClassNotFoundException {

    return clazz;
  }
}

This solution is concise and elegant (according to me). Its only drawback is that it couples the servlet to Spring. But a class-localized coupling is of no consequesence and perfectly acceptable. Morevoer, this lets you use Spring autowiring mechanism, JSR 250 autowiring or plain old XML explicit wiring.

Categories: JEE Tags: ,