Java Service Provider Interface (SPI)

March 19th, 2009 by Eduardo Costa

Long time ago, I had a bad time trying to develop a “plugin mechanism” to my “open source Toad“. What I didn’t know is how to use the service provider infrastructure avaliable since Java 1.3 (what a shame!).

If you want to create a service provider interface (SPI):

  1. Define an interface or abstract class (this will be implemented/overrided by the provider)
  2. Use “ServiceLoader.load” when you need the concrete instances (it’s an iterator that can be used in a “foreach”)

If you want to provide a service (the plugin itself):

  1. Implement/override the code of SPI
  2. Create a META-INF/services folder
  3. Create a file with the same name of the SPI class and add the name of the concrete classes from step 1

And we are done! A simple, yet robust, solution to add extensibility.

Password and confirmation with JSF

March 17th, 2009 by Eduardo Costa

If you need to validate a field in JSF and the value is dependent of another field (like password/confirmation), BalusC posted a nice tutorial about it. You need to create a JSF Validator and add a <f:attribute/> to your field. Easier than I thought…

Spring injection outside application context

March 17th, 2009 by Eduardo Costa

Are you using ApplicationContext (and friends) to create a single “spring context” for all your web application? If so, you are on the right way. And it is possible that you feel the need to inject properties where Spring isn’t accessible (like a Servlet Filter). You can use this little trick:

public static void inject(ServletContext context,
    Object bean) {
  WebApplicationContext wCtx =
      WebApplicationContextUtils
          .getWebApplicationContext(context);
  if (wCtx != null) {
    wCtx.getAutowireCapableBeanFactory()
        .autowireBeanProperties(bean,
            AutowireCapableBeanFactory.AUTOWIRE_NO,
            false);
  }
}

Hibernate JPA and Enums

March 17th, 2009 by Eduardo Costa

Assume you have a simple enum:

public enum Status {
  ACCEPTED, REJECTED, NOTREADDEN
}

And your legacy database stores it as ordinal values (ACCEPTED = 0, REJECTED = 1, NOTREADDEN = 2). For reasons lost in time, DBA created the column as “varchar”. If you want to use JPA, you will have a bad time using Hibernate:

java.lang.IllegalArgumentException: No enum const class mypkg.Status.1
  java.lang.Enum.valueOf(Enum.java:196)
  org.hibernate.type.EnumType.nullSafeGet(EnumType.java:110)

After digging into EnumType.java, I noticed it is hardcoded “if-varchar-then-name-else-ordinal”. I assume they never dealed with ancient, legacy databases.

If I switch to TopLink, it works as expected… One thumb down to Hibernate…

JAAS and Filters

March 17th, 2009 by Eduardo Costa

Small tip of the day. If you define a servlet filter and container managed security on the same application, keep these in mind:

  • If your filter is “url-mapped”, it is executed BEFORE the security manager;
  • If it is “servlet-mapped”, it is executed AFTER the security manager.

I tested it when developing a filter to handle “user life cycle” (expired passwords, agreement signing, etc). If I map both filter and security to “/*”, filter was run. If I map security to “/*” and filter to “Faces Servlet”, it is not executed until authenticated (even when accessing “/faces/index.jsp”).

Tomcat manager with SSO and a different Realm

March 16th, 2009 by Eduardo Costa

Tomcat Manager’s default configuration isn’t pratical (nor secure): you must store your users and passwords in a plain XML file. Of course, you can change the “<Realm>” definition on “<Engine name=’Catalina’>”, but it has no effect if you need a host with Single Sign On.

Since Manager needs to share the same host with managed applications, you need to create a context.xml for your Manager:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/manager" privileged="true">
  <Realm className="my.secure.and.custom.Realm"/>
</Context>

Put it on “conf/<engine>/<host>/manager.xml”. The “privileged=’true’” will prevent a “java.lang.SecurityException: Servlet of class org.apache.catalina.manager.HTMLManagerServlet is privileged and cannot be loaded by this web application”.

You must change “webapps/manager/WEB-INF/web.xml” and replace “<role-name>manager</role-name>” with the name of the role you want.

Spring classes and their long names

March 16th, 2009 by Eduardo Costa

Spring team likes big names. One of the biggest is “SimpleRemoteStatelessSessionProxyFactoryBean“. This is not a problem, since I’m not a Fortran programmer. Unfortunatelly, I found two classes with similar names that aren’t type-safe (i.e.: I don’t receive a ClassCast or similar if I swap them): MethodInvokingFactoryBean e MethodInvokingJobDetailFactoryBean. I use the latter a lot, but, after using NB’s autocomplete feature, I selected the former instead:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetObject" ref="cache"/>
  <property name="targetMethod" value="reload"/>
</bean>

Results? NullPointerException:

org.quartz.SchedulerException: Registration of jobs and triggers failed: null [See nested exception: java.lang.NullPointerException]
  at org.springframework.scheduling.quartz.SchedulerFactoryBean.registerJobsAndTriggers(SchedulerFactoryBean.java:861)
  at org.springframework.scheduling.quartz.SchedulerFactoryBean.afterPropertiesSet(SchedulerFactoryBean.java:649)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334)
  ... 13 more
Caused by: java.lang.NullPointerException
  at org.quartz.core.QuartzScheduler.addJob(QuartzScheduler.java:808)
  at org.quartz.impl.StdScheduler.addJob(StdScheduler.java:288)
  at org.springframework.scheduling.quartz.SchedulerFactoryBean.addJobToScheduler(SchedulerFactoryBean.java:883)
  at org.springframework.scheduling.quartz.SchedulerFactoryBean.addTriggerToScheduler(SchedulerFactoryBean.java:906)
  at org.springframework.scheduling.quartz.SchedulerFactoryBean.registerJobsAndTriggers(SchedulerFactoryBean.java:842)
  ... 16 more

This wasn’t easy to solve, since the NPE wasn’t obvious. Both MIFB and MIJDFB are “factory” instances (they create real instances as needed), and, in this case, no type check was done.

Jasper Reports tutorial - part 2 - tables

March 16th, 2009 by Eduardo Costa

I never planned a “part 2″ about Jasper Reports, but the previous “tutorial” lacks a small concept: how do I make tables? It’s obvious, but only after you figure it out. If you downloaded Jasper Reports examples, you can look at “datasource” sample. Nice one, but not as simple as you may want.

I only want to add a basic table which row data comes from a Java Collection. It is very easy to adapt the JasperFiller: just change JREmptyDatasource with JRBeanCollectionDataSource.

Adapting JRXML is easy, too, but it not obvious for a newbie. I admit I expected something like a “table” element (blame years of HTML), but in JR, you only need to define the “detail” element with the contents you want to repeat for each element on DataSource. Create it as you want, tune the band height to the height of a row, and you have your HTML-ish table.

BTW, you need to define all fields at the top of your JRXML, since JR’s DataSources does not contains metadata.

As a last tip, keep these in mind:

  • <title> only appears on first page;
  • <pageHeader> and <pageFooter> appears on every page;
  • <lastPageFooter> apperars only on last page, REPLACING <pageFooter>

Jasper Reports (quick and dirt) tutorial

March 12th, 2009 by Eduardo Costa

If you want a simple Jasper Reports tutorial, you will have a bad time googling it. The official site has a nice theorical introduction, but after reading it, you will not have a working “hello world” example. Unfortunatelly, the “definitive guide” is a book you need to buy.

Since I prefer a “try-before-you-buy” approach, I asked Google and I’ve found a simple “hello world” JRXML reading this tutorial from David Heffelfinger’s article. Good one, but I will upgrade it. The XML can use XSD:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport name="report name"
  xmlns="http://jasperreports.sourceforge.net/jasperreports"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports
    http://jasperreports.sourceforge.net/xsd/jasperreport.xsd">
  <detail>
    ...
  </detail>
</jasperReport>

If you are using NetBeans 6, go to “Tools > Options > Miscellaneous > Files”, add “jrxml” extension and associate with “application/xml”. Now, it will autocomplete jasper tags for you. You can use iReport NB plugin, too, but I like to know how it work.

Well, you need to compile this JRXML before using it. David shows how to do programmatically. If you want to add only the compiled version to your JAR file, you can add this to your Ant build file (this is a NB version, change parameters as needed):

<target name="-post-init">
  <!-- Init jasper ant task -->
  <taskdef classpath="${javac.classpath}"
      classname="net.sf.jasperreports.ant.JRAntCompileTask"
      name="jrc" />
</target>
<target name="-post-compile">
  <!-- without a tempdir, JR may
       create files on NB folder! -->
  <mkdir dir="${build.dir}/jasper"/>
  <!-- compile "src/JRXML" to "build/JASPER" -->
  <jrc destdir="${build.classes.dir}"
       tempdir="${build.dir}/jasper">
    <src>
      <fileset dir="${src.dir}" includes="**/*.jrxml" />
    </src>
    <classpath>
      <path path="${javac.classpath}"/>
    </classpath>
  </jrc>
</target>

Now you have a “.jasper” file on your build dir, together with your compiled classes - just ready for use! Let’s use it:

InputStream in = getClass().getResourceAsStream("/my-pkg/myReport.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(in,
        new HashMap(), new JREmptyDataSource());
JasperExportManager.exportReportToHtmlFile(jasperPrint,
        "output-path/report.html");

Pretty easy, huh? One last note - you will need more libs than just “jasperreports.jar” on your classpath:

  • commons-digester
  • commons-logging
  • commons-collections
  • commons-beanutils
  • itext (only if you want to export as PDF)

Writing XML with namespaces using DOM

February 12th, 2009 by Eduardo Costa

Java has a lot of ways to interact with XML files: JAXB, SAX, DOM… I don’t have a favorite one: each one has its own pros and cons. SAX is great to parse adhoc, JAXB is better when you can map your XML into a POJO tree, and DOM is the choice when your XML is well-formed, but can’t be easily mapped into POJO.

I’m playing with JSPX files (JSP using XML syntax), and I got an idea: “why can’t I build an JSPX using DOM”? Gene Davis has a great tutorial about creating an XML using DOM. No external library needed (like JDOM). It is almost perfect, but, if I want to create a JSPX, I will use a lot of namespaces. DOM specification level 2 doesn’t support namespaces directly, but you can use dirt tricks to get this. Based on Gene’s example, you only need to change the root element:

Element root = doc.createElement("jsp:root");
root.setAttribute("xmlns:jsp", "http://jsp");
root.setAttribute("xmlns:f", "http://faces");
doc.appendChild(root);

The trick is to consider the namespace declarations as attributes (since this is what they are). The result XML becames:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<jsp:root xmlns:jsp="http://jsp" xmlns:f="http://faces">
    <!--Just a thought-->
    <jsp:child name="value">Filler, ... I could have had a foo!</jsp:child>
</jsp:root>

BTW, I changed the child to “jsp:child” (without the xmlns attributes), removed the “OMIT_XML_DECLARATION” output property, and, to indent correctly, I added this property:

trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

Apache attribute on Sun’s RI… Yikes!