tags:

views:

33

answers:

2

So, I'm trying to convert a Representation to a String or a StringWriter either using the getText() or write() method. It seems I can only call this method once successfully on a Representation... If I call the method again, it returns null or empty string on the second call. Why is this? I'd expect it to return the same thing every time:

public void SomeMethod(Representation rep)
{
    String repAsString = rep.getText();  // returns valid text for example: <someXml>Hello WOrld</someXml>

    String repAsString2 = rep.getText(); // returns null...  wtf?
}

If I'm "doing it wrong" then I'd be open to any suggestions as to how I can get to that data.

+2  A: 

The javadocs explain this:

The content of a representation can be retrieved several times if there is a stable and accessible source, like a local file or a string. When the representation is obtained via a temporary source like a network socket, its content can only be retrieved once.

So presumably it's being read directly from the network or something similar.

You can check this by calling isTransient(). If you need to be able to read it multiple times, presumably you should convert it to a string and then create a new Representation from that string.

Jon Skeet
Good investigating Jon... I'll give this a shot tonight and see if it works. Thanks much!
Polaris878
+2  A: 

It's because in general the Representation doesn't actually get read in from the InputStream until you ask for it with getText(), and once you've asked for it, all the bytes have been read and converted into the String.

This is the natural implementation for efficiency: rather than creating a potentially very large String and then converting that String into something useful (a JSON object, a DOM tree, or whatever), you write your converter to operate on the InputStream instead, avoiding the costs of making and reading that huge String.

So for example if you have a large XML file being PUT into a web service, you can feed the InputStream right into a SAX parser.

(As @John notes, a StringRepresentation wraps a String, and so can be read multiple times. But you must be reading a Request's representation, which is most likely an InputRepresentation.)

Jim Ferrans
Yeah I figured this was done for efficiency... as it would've been unwieldy creating a huge String for each call.
Polaris878