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!

Marker-only validation error with RichFaces

January 12th, 2009 by Eduardo Costa

I’ve made a simple JSP 2.1 tag file to show only a small icon on my validation errors (and a tooltip to show message details). This is the .tag file:

<%@ tag pageEncoding="UTF-8" %>
<%@ attribute name="field" required="true" deferredValue="true" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="a4j" uri="http://richfaces.org/a4j" %>
<%@ taglib prefix="rich" uri="http://richfaces.org/rich" %>
<rich:message for="#{field}" showSummary="false" showDetail="false">
  <f:facet name="errorMarker">
    <a4j:outputPanel>
      <h:graphicImage value="path-to-bullet"/>
      <rich:toolTip>
        <rich:message for="#{field}"/>
      </rich:toolTip>
    </a4j:outputPanel>
  </f:facet>
</rich:message>

It can be used like this:

<tags:errorMessages field="id-of-the-field"/>

Instead of showing a big chunk of text, your webdesigner will only deal with a small bullet that will show a nice tooltip with the full message. Some “catches”:

  • <rich:message tooltip=”true”> does not show tooltip if you disable both summary and details;
  • Since <rich:toolTip> can’t work with <h:panelGrid>, the <a4j:outputPanel> will show the tooltip without adding any extra visual effect (like <rich:panel> does);
  • The inner <rich:message> will render the message inside the tooltip (notice that outer <rich:message> renders only the marker, because summary and details are “off”).

One more strange bug

November 28th, 2008 by Eduardo Costa

I’ve noticed that all Java applications on my machine are slowing down a lot. But, when I my brand-new and self-made budget application freezes while doing a “new JFileChooser()”, this really pi**es me off. Asking Google, I found another weird bug: when your Windows Desktop has a lot of ZIP files, Java will implicity use Windows “zip folder” feature.

You can also blame Microsoft, because Win32ShellFolder.isDirectory() returns “true” (in W32API terms) when checking zip files. Don’t you love proprietary API?

Workarounds:

  1. Clean your Desktop
  2. If you are as lazy as me, you can disable “zip folder” with:
    regsvr32 /u %windir%\system32\zipfldr.dll

NetBeans 6.5

November 19th, 2008 by Eduardo Costa

Finally, NB 6.5 was released! Grab your copy!

Unfortunatelly the download link is blocked here… I hate proxies…

Dynamic code in Java (a.k.a. “eval in Java”)

November 6th, 2008 by Eduardo Costa

I really don’t like eval-like structures. They are evil. It is a headache to test, makes code ugly, hard to optimize, etc. I simply don’t like them.

But I finally found a use to them. It’s very common to use scripting to create a flexible system. I have a ticket filter that uses Spring and EL to create filtering rules in a “building blocks”-way. It is cool, easy to maintain, but it is not optimized: hundreds of instances in a Composite Pattern (with some expressions) must be navigated to find a simple boolean answer: keep or discard?

Java 6 has a not-so-secret feature that allows invoking the javac using Java code: you pass the files to the framework, it builds compiled classes. You can find how in the JavaCompiler’s API. It mentions an example of a JavaSourceFromString class that you can implement and give the compiler java code stored in String. Very useful!

But, if you try and run a test (like this one), you will receive a nice class file. But that’s not what I want. I want it loaded and ready-to-go. How to interface with this new class when it is loaded? Reflection? Maybe, but I prefer another way: interfaces. I already have this simple one:

package pkg;
public interface Filter {
    boolean filter(VO vo);
}

It is the base of my filter infrastructure. If I change JavaBeat test code to something that “implements pkg.Filter”, my whole problem is solved, with minimal changes on the rest of the code.

Nice! We can interface with the class, but it is not loaded! I could read the class file and pass it to the ClassLoader, but I don’t want to create a file. This class does the trick:

class JavaObjectToByteArray extends SimpleJavaFileObject {
    private ByteArrayOutputStream output = new ByteArrayOutputStream();
    public JavaObjectToByteArray(String className, Kind kind)
            throws URISyntaxException {
        super(new URI(className), kind);
    }
    @Override
    public OutputStream openOutputStream() throws IOException {
        return output;
    }
}

You can pass this object by overriding ForwardingJavaFileManager.getJavaFileForOutput:

fileManager = new ForwardingJavaFileManager(fileManager) {
  @Override
  public JavaFileObject getJavaFileForOutput(Location location,
      String clazz, Kind kind, FileObject sibling) throws IOException {
    try {
      JavaObjectToByteArray jfo = new JavaObjectToByteArray(clazz, kind);
      cl = new ByteArrayClassLoader(className, jfo.output);
      return jfo;
    } catch (Exception ex) {
      throw new IOException(ex);
    }
  }
};

ByteArrayClassLoader is:

class ByteArrayClassLoader extends ClassLoader {
  private String clazz;
  private ByteArrayOutputStream baos;
  public ByteArrayClassLoader(String clazz, ByteArrayOutputStream baos) {
    this.baos = baos;
    this.className = className;
  }
  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    byte[] data = baos.toByteArray();
    return defineClass(name, data, 0, data.length);
  }
  public Class<?> loadClass() throws ClassNotFoundException {
    return loadClass(className);
  }
}

The “loadClass” method is a convenience method, since this class loader only loads one class. With one line of code, I can use my brand-new-dynamic-class:

Class<?> clz = cl.loadClass();
Filter f = (Filter) clz.newInstance();
System.out.println(f.filter(vo));

BTW, there’s only one small change in JavaBeat’s code. I need a “public” class, and this means the java file must be named “MyClass.java” (not “MyClass”). You only need to change JavaObjectFromString constructor from:

super(new URI(className), Kind.SOURCE);

to:

super(new URI(className + ".java"), Kind.SOURCE);

Easy, huh? It is not like “eval” in JavaScript, but it is better, since this class will be JIT’ed.

Configuring SOAPInput node listener port

October 31st, 2008 by Eduardo Costa

If you use IBM’s WebSphere Message Broker to expose a webservice using a SOAPInput node, you notice that it listens to the 7800 port by default (or 7801, 7802, if you deploy other message flows, too). If you want to configure that port (changing it to 8080 or any other port number), you need to issue this command:

$ mqsichangeproperties BRKNAME -e default -o HTTPConnector \
                               -n explicitlySetPortNumber -v 8080
BIP8071I: Successful command completion.

After restarting the broker, it will open the desired port.

BufferedImage and ByteBuffers

October 30th, 2008 by Eduardo Costa

Direct ByteBuffer are really cool, because they can allocate and wrap native memory outside the JVM heap. This is very useful with JNI or with large files. I’m playing with OpenGL and PCX files (this is evil, I know). Since I want to keep a small footprint, I want to keep only a pointer to PCX raw data (run-lenght encoded), and decompress it into a RGBA ByteBuffer as needed. This, in theory, allows me to share the same code with OpenGL and BufferedImage - since I’m bound only to a pointer of RGBA data. The former is easy: TextureData did the dirt job. The latter… Well… Not that easy. If you try something like this:

final IntBuffer buf = myPCXLoader.getImage();
DataBuffer dataBuffer = new DataBuffer(
    DataBuffer.TYPE_INT, buf.limit()) {
  @Override
  public int getElem(int bank, int i) {
    return buf.get(i);
  }
  @Override
  public void setElem(int bank, int i, int val) {
  }
};
SampleModel sm = new SinglePixelPackedSampleModel(
    DataBuffer.TYPE_INT, w, h,
    new int[] { 0xFF000000, 0xFF0000, 0xFF00, 0xFF });
WritableRaster raster = Raster.createWritableRaster(
    sm, dataBuffer, null);
BufferedImage img = new BufferedImage(
    new DirectColorModel(32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF),
    raster, false, null);

The red line leads me to an ugly exception:

java.awt.image.RasterFormatException: IntegerComponentRasters must
haveinteger DataBuffers
  at sun.awt.image.IntegerComponentRaster.<init>
    (IntegerComponentRaster.java:155)
  at sun.awt.image.IntegerInterleavedRaster.<init>
    (IntegerInterleavedRaster.java:111)
  at sun.awt.image.IntegerInterleavedRaster.<init>
    (IntegerInterleavedRaster.java:78)
  at java.awt.image.Raster.createWritableRaster(Raster.java:994)

Asking Google, I found that ByteComponentRaster checks if DataBuffer is a instanceof ByteDataBuffer (instead of checking its type). Disgusting… Looks like Sun hired some kind of Baby Junior Programmer taking his first cup of Java to make that part of java.awt…

I also found this 3-years-old-and-not-solved-yet bug, with an workaround:

WritableRaster raster = new WritableRaster(sm, dataBuffer,
    new java.awt.Point()) {};

Works like a charm!

Sun is really disappointing me. There are a lot of small, simple-to-solve, really old bugs and seems like nobody cares about them. I think this is why they are opening the source of their major products: let the community clean the mess…

Random numbers in JavaME (and JavaSE)

September 5th, 2008 by Eduardo Costa

In the absence of a Math.random() method in JavaME, you can use the java.util.Random class to do the job:

Random random = new Random(System.currentTimeMillis());
// JavaSE and CDLC 1.1
float f = random.nextFloat(); [0; 1[
// JavaSE and CDLC 1.0
int a = random.nextInt(); // [0; *[
int b = random.nextInt(20); // [0; 20[
int n = random.nextInt(max - min + 1) + min; // [min; max]

This tip can be used on JavaSE, if you want to generate a random number between “min” and “max”. It is easier than multiplying and casting to integer.

IOException when loading a sound/midi from a JAR/ZIP archive

August 28th, 2008 by Eduardo Costa

I have a MIDI file in a JAR archive. If I try to play it with the Sequencer class, I got an exception: “java.io.IOException: mark/reset not supported”. I’ve found this related bug. I don’t like workarounds (all bugs must die), but I developed this one:

public static InputStream loadStream(InputStream in) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buf = new byte[1024];
  int c;
  while ((c = in.read(buf)) != -1) {
    bos.write(buf, 0, c);
  }
  return new ByteArrayInputStream(bos.toByteArray());
}

With this method, I encapsulate the “unresetable” stream into a “resetable” ByteArrayInputStream.

MQSeries not closing connections

August 21st, 2008 by Eduardo Costa

I got this error while connecting to MQSeries:

MQJE001: An MQException occurred: Completion Code 2, Reason 2009
MQJE016: MQ queue manager closed channel immediately during connect
Closure reason = 2009

After some trial-and-error, I found the problem: MQ’s InitialContext opens a connection, but only closes it if I close the IC itself:

ic.close();

Since my application creates a lot of instances of InitialContext, a lot of connections got leaked, giving that annoying error.

+1 to the IBM’s hall-of-shame, section “useless error messages”.