Screwtape
Screwtape

Reputation: 1367

How to get Java Date object from Camel XPathBuilder XPath expression?

I've got a program that uses Camel's XPathBuilder to create and evaluate xpath expressions in a processor bean.

I've created the object

XPathBuilder xpath = XPathBuilder.xpath( "path/to/dateElement", java.util.Date );

and execute it

Object obj = xpath.evaluate( exchange, Object.class );

however when I log the value of obj it is null. If I request it as a String, it returns the XML date format string as I would expect.

Does XPathBuilder not support conversion to java.util.Date? (I can't see a list of supported output classes in the documentation anywhere.)

I tried casting the xpath expression explicitly to xs:dateTime, but that gave me an exception saying it couldn't convert the expression to a nodeList.

(It works fine when I want a java.lang.Long or java.lang.Double instead of java.util.Date)

How do I get the Xpath to return a Date object?

Thanks! Screwtape.

Upvotes: 0

Views: 1164

Answers (1)

Bedla
Bedla

Reputation: 4929

With XPathBuilder, only conversion to Number, String, Boolean, Node and NodeList is supported out-of-the-box. If you want to support other types, you need to implement custom Type Converter.

import org.apache.camel.Converter;
import org.apache.camel.TypeConverters;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class XmlDateTypeConverters implements TypeConverters {

    @Converter
    public Date convertNodeToDate(Node node) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
                .parse(node.getTextContent());
    }

    @Converter(allowNull = true)
    public Date convertNodeListToDate(NodeList nodeList) throws ParseException {
        if (nodeList.getLength()==0){
            return null;
        }
        return convertNodeToDate(nodeList.item(0));
    }
}

And registration of XmlDateTypeConverters to CamelContext depends on your preferences, with Java DSL it looks like this:

getContext().getTypeConverterRegistry().addTypeConverters(new XmlDateTypeConverters())

In Spring, is TypeConverter discovered automatically, if it is bean.

Upvotes: 1

Related Questions