tomee-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Anthony Fryer <apfr...@hotmail.com>
Subject Re: cxf advanced examples
Date Thu, 05 Jun 2014 23:16:07 GMT
I have a simple cxf interceptor in a project that just forces the text of an
xml element in a web service response to be wrapped in a CDATA element.  It
would probably make for a good example.

There's 2 classes I have to implement the interceptor...

public class CDataContentWriter extends DelegatingXMLStreamWriter {
	private static final Pattern XML_CHARS = Pattern.compile("[&<>]");
	private String currentElementLocalName;

	public CDataContentWriter(XMLStreamWriter writer) {
		super(writer);
	}

	@Override
	public void writeCharacters(String text) throws XMLStreamException {
		boolean useCData = XML_CHARS.matcher(text).find();
		if (useCData) {
			super.writeCData(text);
		} else {
			super.writeCharacters(text);
		}
	}

	@Override
	public void writeStartElement(String prefix, String local, String uri)
			throws XMLStreamException {
		currentElementLocalName = local;
		super.writeStartElement(prefix, local, uri);
	}
}

public class CDataWriterInterceptor extends
AbstractPhaseInterceptor<Message> {

	public CDataWriterInterceptor() {
		super(Phase.PRE_STREAM);
		addAfter(AttachmentOutInterceptor.class.getName());
	}

	@Override
	public void handleMessage(Message message) throws Fault {
		message.put("disable.outputstream.optimization", Boolean.TRUE);
		XMLStreamWriter writer =
StaxUtils.createXMLStreamWriter(message.getContent(OutputStream.class));
		message.setContent(XMLStreamWriter.class, new CDataContentWriter(writer));
	}
}

Then in my resources.xml (or you could use tomee.xml) i declare the
interceptor as a service...

<resources>
    ....
   <Service id="cdataWriterInterceptor"
class-name="au.com.cyberavenue.cxf.CDataWriterInterceptor"/>
   
</resources> 

Lastly, I had to create an openejb-jar.xml (located in my WEB-INF folder)
which is where i hook up the interceptor service to individual web
services...

<openejb-jar xmlns="http://www.openejb.org/openejb-jar/1.1">

  <ejb-deployment ejb-name="GetBoardingPassDataImpl">
    <properties>
      cxf.jaxws.out-interceptors = cdataWriterInterceptor
    </properties>
  </ejb-deployment>
  
  <ejb-deployment ejb-name="BoardingPassBarCodeImpl">
    <properties>
      cxf.jaxws.out-interceptors = cdataWriterInterceptor
    </properties>
  </ejb-deployment>
  
</openejb-jar>

So I ended up with 2 webservices where the response xml will have CDATA
elements instead of escaped strings.  Hope this helps.

Regards,

Anthony





--
View this message in context: http://openejb.979440.n4.nabble.com/cxf-advanced-examples-tp4669927p4669928.html
Sent from the OpenEJB User mailing list archive at Nabble.com.

Mime
View raw message