I'm a passionate enterprise web developer and an advocate of Apache Wicket. I started programming in Java since version 1.2 and I'm a strong supporter of open source technologies. Andrea has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Implement RSS Feeds with a Custom Wicket Resource

03.13.2013
| 3212 views |
  • submit to reddit
The following article contains some excerpts from the upcoming free guide to Apache Wicket (http://code.google.com/p/wicket-guide/) that I'm about to release. The code used in the article can be found on GitHub at https://github.com/bitstorm/Wicket-tutorial-examples/tree/master/CustomResourceMounting.

Please note that the code used in this article is for illustrative purpose only and is not meant to be an optimal implementation.

In Wicket the best way to add dynamic functionalities to our web application (such as csv export, pdf generated on the fly, etc...) is implementing a custom resource. A resource is an entity that can interact with the current request and response and it must implement interface IResource .

The custom resource we will build in this article is a basic RSS feeds generator which can be used to publish RSS feeds on our site.

Instead of generating a RSS feed by hand we will use Rome  framework and its utility classes. Wicket provides class AbstractResource as base class to implement new resources. This class defines abstract method newResourceResponse which is invoked when the resource is requested. The following is the code of our RSS feeds generator:

public class RSSProducerResource extends AbstractResource {

	@Override
	protected ResourceResponse newResourceResponse(Attributes attributes) {
		ResourceResponse resourceResponse = new ResourceResponse();
		resourceResponse.setContentType("text/xml");
		resourceResponse.setTextEncoding("utf-8");
		
		resourceResponse.setWriteCallback(new WriteCallback()
		{
			@Override
			public void writeData(Attributes attributes) throws IOException
			{
				OutputStream outputStream = attributes.getResponse().getOutputStream();
				Writer writer = new OutputStreamWriter(outputStream);
				SyndFeedOutput output = new SyndFeedOutput();
		        try {
					output.output(getFeed(), writer);
				} catch (FeedException e) {
					throw new WicketRuntimeException("Problems writing feed to response...");
				}
			}			
		});
		
		return resourceResponse;
	}
	
	//method getFeed() 
}

Method newResourceResponse returns an instance of ResourceResponse representing the response generated by the custom resource. Since RSS feed is basically a XML fragment, in the code above we have set the type of the response to text/xml and the text encoding to utf-8.

To specify the content that will be returned by our resource we must also provide an implementation of inner class WriteCallback, which is responsible for writing content data to response's output stream. In our project we used class SyndFeedOutput from Rome framework to write our feed to response. Method getFeed() is just an utility method that generates a sample RSS feed (which is an instance of standard interface com.sun.syndication.feed.synd.SyndFeed).

Now that we have our custom resource in place, we can use it in our applications. Class WebApplication provides method mountResource which can be used to mount a given resource to a specific path:


public class WicketApplication extends WebApplication
{    		
	@Override
	public void init()
	{
		super.init();
		ResourceReference resourceReference = new ResourceReference("rssProducer"){
			RSSProducerResource deviceMetaResource = new RSSProducerResource();
			@Override
			public IResource getResource() {
				return deviceMetaResource;
			}};
			
		mountResource("/foo/bar", resourceReference);				
	}
}

Only resource references can be mounted in Wicket, that's why we have implemented a custom reference that returns our RSS producer. With the configuration above every request to "/foo/bar" will be served by the custom resource and a RSS feed will be returned.

Testing resource's response

The main entity used to write unit tests in Wicket is class WicketTester. Among the other things, this class allows us to access to the last response generated during testing with methodgetLastResponse(). The returned value is an instance of class MockHttpServletResponse thatprovides helper methods to extract informations from mocked request.
One of these methods is getDocument() which returns the text contained in the last response. This method is used in the following test method to check if our RSS producer returns the expected XML as response:

@Test
public void testMountedResourceResponse() throws IOException, FeedException
{
	tester.startResource(new RSSProducerResource());
	String responseTxt = tester.getLastResponse().getDocument();
	//write the RSS feed used in the test into a ByteArrayOutputStream
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	Writer writer = new OutputStreamWriter(outputStream);
	SyndFeedOutput output = new SyndFeedOutput();
       	
	output.output(RSSProducerResource.getFeed(), writer);
	//the response and the written RSS must be equal 
	Assert.assertEquals(responseTxt, outputStream.toString());
}

To simulate a request to our custom resource we used WicketTester's method startResource.

Published at DZone with permission of its author, Andrea Del Bene. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Andrea Del Bene replied on Mon, 2013/03/11 - 11:19am

 I don't know why but code sections have lost their formatting style :(

UPDATE: I've managed to fix them

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.