tags:

views:

436

answers:

2

I've a simple little servlet, basically:

void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
    JAXBContext jaxb = myContext.getXMLContext().getSearchparamContext();
    SearchParams params = null;
     try {
        Unmarshaller um = jaxb.createUnmarshaller();
        um.setSchema(myContext.getXMLContext().getSearchParamsSchema()); 
         JAXBElement<SearchParams> je = (JAXBElement<SearchParams>) um.unmarshal(request.getInputStream());
        params = je.getValue();
    } catch (JAXBException e) {
        logger.log(Level.WARNING,"Error parsing xml from user "+ request.getRemoteUser(),e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
...

Is there any way I can get hold of the original XML here, if parsing fails - mostly for tracing purposes. Or should I just save to a file and unmarshal from that ?

+1  A: 

You can read the request.getInputStream() into a String, and unmarshal that String, by calling um.unmarshall(new StringReader(str)); Then that String will also be accessible in the catch-clause

Bozho
please don't read it into a String. if you must read it into memory, use a byte[].
james
+3  A: 

If you want to do that, you'll need to read the request InputStream into a temporary buffer (e.g. a String or a byte[]), and then pass that through JAXB. If your documents are large, then this could hurt your performance, but then if your documents are large, then JAXB is going to be slow anyway.

If you have the good sense to use Apache Commons IO, then this is easy:

String buffer = IOUtils.toString(request.getReader());
Object obj = jaxbContext.createUnmarshaller().unmarshal(new StringReader(buffer));
// do something else with the buffer here
skaffman
if he has good sense, he should be using a byte[] not a string. less chance of breaking the xml data.
james