5 Cool XFire Hacks

December 9th, 2005

In the spirit of “5ives”:http://5ives.com - I’ve decided to put together 5 XFire hacks.

*1. Inject the MessageContext*

Sometimes you’ll want to get ahold of data in the MessageContext like Headers or the SOAPAction or any number of other things. Doing so is as simple as can be. Just declare the MessageContext as part of your operation’s method signature. XFire will then inject it for you to use.

public String echo(String text, MessageContext context) {
   // do something with the MessageContext
   return text;
}

*2. Create a Source endpoint*

JAX-WS has the Provider interface which lets you implement a service which just works with the XML. Its quite easy to create this in XFire too. First write your class:

public class Provider {
  public Source invoke(Source source) {
    // do something with the xml
  }
}

Then create a service from it:

ObjectServiceFactory osf = new ObjectServiceFactory();
// the ServiceFactory defaults to a wrapped style, and we don't
// want our operation name showing up in our soap:Body -
// so switch to a "document" style.
osf.setStyle("document");
Service service = osf.create(Provider.class);
xfire.getServiceRegistry().register(service);

*3. Dynamic Client*

Invoking unknown services at runtime? This is pretty easy with our dynamic client:

Client client = new Client(new URL("http://localhost:8080/Echo?wsdl"));
Object[] response = client.invoke(”echo”, new Object[] {”hello”});
String echo = (String) response[0];

*4. On the fly transformation*

Lets say you’re writing a handler, but need to load up the request into an XML document. Since XFire just works with streams this can be a little bit tricky. But luckily there is an efficient and neat way to do this:

public class TransformationHandler extends AbstractHandler {
  public void invoke(MessageContext context) {
    XMLStreamReader reader = context.getInMessage().getXMLStreamReader();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = STAXUtils.read(builder, reader);

    // do something with the doc

    context.getInMessage().setXMLStreamReader(new W3CDOMStreamReader(doc.getDocumentElement()));
  }
}

*5. Grab the XMLStreamReader directly*

This is quite like #2, but quite a bit more efficient because you’re just working with the XMLStreamReader

public class MyService {
  public XMLStreamReader doFoo(XMLStreamReader source) {
    // do something with the xml

   return readerForOutput;
  }
}

You’ll need to use the MessageBinding when creating the service for it to be able to understand the XMLStreamReader:

ObjectServiceFactory osf = new ObjectServiceFactory();
osf.setStyle("message");
Service service = osf.create(MyService.class);
xfire.getServiceRegistry().register(service);

Comments are closed.